Show bot cards inline in the conversation, like a plan
Questions, extension proposals, hook proposals and secret requests used to be a chip on the line that opened their card in a modal. The plan card already showed in full under the message, so the others now do too: `RefCardShell` gives them one frame (icon, title, status, the card body), and the old `*-ref-chip.tsx` files and `RefChipModal` are gone. A card is a block, which React refuses inside a `p`, so `MarkdownParagraph` splits the message's paragraph around card refs (`isCardRefHref`): the text stays in paragraphs, each card gets its own full-width line in reading order, decided questions and proposals included, so nothing waits to be opened. Tests cover each card rendering its content expanded and the paragraph hoisting, replacing the chip and modal tests.
This commit is contained in:
@@ -95,12 +95,12 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` holds the tools to `PlanModeToolNames` (reads and the plan/question/suggestion cards, never `load_tools`), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[secret:ID]` (masked env, Reveal/Copy), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). A plan, questions, a proposal, a hook proposal and a secret request show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
|
||||
- **Message images:** a bot message shows the images it's about under its text (`MessageImages` in `(partials)/`, on `BotMessageLine` and `CrewMessageLine`): its image attachments plus every image `[file:ID]` it names (`liveFileRefIds`, which keeps the renderer's code rules), deduped when a named file is also attached (`file_id`). Each is a `MessageAttachment` thumbnail opening the shared `FilePreviewModal`; in a thread its gallery is the whole conversation (`sessionImageGallery` + `SessionGalleryContext` from `MessageThread`): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through `useBotFile`/`useReferencedFiles` (page props first, then the cached `api/admin/bots/files` read shared with `FileRefChip`). A thumbnail URL serves the original when no smaller copy was made (`mediaServeWritePath`), since bot files keep no thumbnail.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delete_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a conversation's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next (side arrows at the far middle left/right, the header's stepper, and the arrow keys) step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **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).
|
||||
- **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`).
|
||||
- **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).
|
||||
|
||||
@@ -3,10 +3,10 @@ import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import H3 from "@moduletrace/twui/layout/H3";
|
||||
import H4 from "@moduletrace/twui/layout/H4";
|
||||
import H5 from "@moduletrace/twui/layout/H5";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import MarkdownCodeBlock from "../(partials)/markdown-code-block";
|
||||
import MarkdownParagraph from "../(partials)/markdown-paragraph";
|
||||
import MarkdownLink from "../(partials)/markdown-link";
|
||||
import MarkdownList from "../(partials)/markdown-list";
|
||||
|
||||
@@ -20,11 +20,7 @@ const HeadingClassName = "my-0! text-[15px]! leading-6! tracking-normal! font-bo
|
||||
* elements.
|
||||
*/
|
||||
export const MessageMarkdownComponents: Components = {
|
||||
p: ({ children }) => (
|
||||
<P noMargin className="w-full text-sm leading-5 text-ink">
|
||||
{children}
|
||||
</P>
|
||||
),
|
||||
p: ({ children }) => <MarkdownParagraph>{children}</MarkdownParagraph>,
|
||||
h1: ({ children }) => <H3 className={HeadingClassName}>{children}</H3>,
|
||||
h2: ({ children }) => <H3 className={HeadingClassName}>{children}</H3>,
|
||||
h3: ({ children }) => <H4 className={HeadingClassName}>{children}</H4>,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { MessageCircleQuestion } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useBotQuestion from "../(hooks)/use-bot-question";
|
||||
import BotQuestionCard from "./bot-question-card";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
|
||||
type Props = {
|
||||
question_id: number;
|
||||
};
|
||||
|
||||
const StatusLabels = {
|
||||
pending: "Waiting for you",
|
||||
answered: "Answered",
|
||||
skipped: "Skipped",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Questions a bot asked before acting (`botQuestionRef`), shown in the
|
||||
* message as the card the user answers them in, like a plan's card, so
|
||||
* they need not open anything to see what is being asked. Anyone they
|
||||
* weren't asked of sees their number only.
|
||||
*/
|
||||
export default function BotQuestionRefCard({ question_id }: Props) {
|
||||
const { view, loading, setView } = useBotQuestion({ question_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `questions ${question_id}` : `questions ${question_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const count = view.questions.length;
|
||||
const pending = view.status == "pending";
|
||||
|
||||
return (
|
||||
<RefCardShell
|
||||
icon={<MessageCircleQuestion size={14} aria-hidden />}
|
||||
title={view.title || (count == 1 ? "1 question" : `${count} questions`)}
|
||||
status={StatusLabels[view.status]}
|
||||
tone={pending ? "warning" : view.status == "answered" ? "success" : "gray"}
|
||||
description={
|
||||
pending
|
||||
? `${view.bot_name} wants to be sure what you want before it acts. Your answers go to it as your message.`
|
||||
: `What ${view.bot_name} asked before going on.`
|
||||
}
|
||||
>
|
||||
<BotQuestionCard view={view} onDecided={setView} onDone={() => {}} />
|
||||
</RefCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { MessageCircleQuestion } from "lucide-react";
|
||||
import useBotQuestion from "../(hooks)/use-bot-question";
|
||||
import BotQuestionCard from "./bot-question-card";
|
||||
import RefChipModal from "./ref-chip-modal";
|
||||
|
||||
type Props = {
|
||||
question_id: number;
|
||||
};
|
||||
|
||||
const StatusLabels = {
|
||||
pending: "waiting for you",
|
||||
answered: "answered",
|
||||
skipped: "skipped",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Questions a bot asked before acting (`botQuestionRef`): a chip naming
|
||||
* them and where they stand, which opens the card the user answers them
|
||||
* in. Anyone they weren't asked of sees their number only.
|
||||
*/
|
||||
export default function BotQuestionRefChip({ question_id }: Props) {
|
||||
const { view, loading, setView } = useBotQuestion({ question_id });
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `questions ${question_id}` : `questions ${question_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const count = view.questions.length;
|
||||
const name = view.title || (count == 1 ? "1 question" : `${count} questions`);
|
||||
const status = StatusLabels[view.status];
|
||||
const pending = view.status == "pending";
|
||||
|
||||
return (
|
||||
<RefChipModal
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
variant={pending ? undefined : "outlined"}
|
||||
color={pending ? undefined : "gray"}
|
||||
size="smaller"
|
||||
title={pending ? `Answer ${name}` : `${name}: ${status}`}
|
||||
onClick={() => setOpen(true)}
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold whitespace-nowrap",
|
||||
!pending && "text-ink",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0",
|
||||
)}
|
||||
>
|
||||
<MessageCircleQuestion size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{`${name} · ${status}`}</Span>
|
||||
</Button>
|
||||
}
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
|
||||
{view.title || `${view.bot_name} asks before going on`}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{pending
|
||||
? `${view.bot_name} wants to be sure what you want before it acts. Your answers go to it as your message.`
|
||||
: `What ${view.bot_name} asked before going on.`}
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-2 max-h-[65vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
<BotQuestionCard view={view} onDecided={setView} onDone={() => setOpen(false)} />
|
||||
</Stack>
|
||||
</RefChipModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Webhook } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useHookProposal from "../(hooks)/use-hook-proposal";
|
||||
import hookProposalTitle from "../(utils)/hook-proposal-title";
|
||||
import proposalStatusLabel from "../(utils)/proposal-status-label";
|
||||
import HookProposalCard from "./hook-proposal-card";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
|
||||
type Props = {
|
||||
proposal_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A hook a bot proposed (`hookProposalRef`), shown in the message as the
|
||||
* card the user confirms or rejects it from, like a plan's card. Anyone it
|
||||
* wasn't proposed to sees its number only.
|
||||
*/
|
||||
export default function HookProposalRefCard({ proposal_id }: Props) {
|
||||
const { view, loading, setView } = useHookProposal({ proposal_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `hook proposal ${proposal_id}` : `hook proposal ${proposal_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const title = hookProposalTitle({ view });
|
||||
const status = proposalStatusLabel({ view });
|
||||
const open = view.status == "pending" && !view.expired;
|
||||
|
||||
return (
|
||||
<RefCardShell
|
||||
icon={<Webhook size={14} aria-hidden />}
|
||||
title={title}
|
||||
status={status}
|
||||
tone={open ? "warning" : view.status == "confirmed" ? "success" : "gray"}
|
||||
description={`${status}. ${view.bot_name} proposed this; nothing is saved until you confirm. Everything above the bot's own words is read from what Confirm would save.`}
|
||||
>
|
||||
<HookProposalCard view={view} onDecided={setView} onDone={() => {}} />
|
||||
</RefCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Webhook } from "lucide-react";
|
||||
import useHookProposal from "../(hooks)/use-hook-proposal";
|
||||
import hookProposalTitle from "../(utils)/hook-proposal-title";
|
||||
import proposalStatusLabel from "../(utils)/proposal-status-label";
|
||||
import HookProposalCard from "./hook-proposal-card";
|
||||
import RefChipModal from "./ref-chip-modal";
|
||||
|
||||
type Props = {
|
||||
proposal_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A hook a bot proposed (`hookProposalRef`): a chip naming it and where
|
||||
* it stands, which opens the card the user confirms or rejects it from.
|
||||
* Anyone it wasn't proposed to sees its number only.
|
||||
*/
|
||||
export default function HookProposalRefChip({ proposal_id }: Props) {
|
||||
const { view, loading, setView } = useHookProposal({ proposal_id });
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `hook proposal ${proposal_id}` : `hook proposal ${proposal_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const title = hookProposalTitle({ view });
|
||||
const status = proposalStatusLabel({ view });
|
||||
|
||||
return (
|
||||
<RefChipModal
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Review: ${title}`}
|
||||
onClick={() => setOpen(true)}
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold text-ink whitespace-nowrap",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0",
|
||||
)}
|
||||
>
|
||||
<Webhook size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{`${title} · ${status}`}</Span>
|
||||
</Button>
|
||||
}
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`${status}. ${view.bot_name} proposed this; nothing is saved until you confirm. Everything above the bot's own words is read from what Confirm would save.`}
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-2 max-h-[65vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
<HookProposalCard view={view} onDecided={setView} onDone={() => setOpen(false)} />
|
||||
</Stack>
|
||||
</RefChipModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Children, isValidElement, type ReactNode } from "react";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { isCardRefHref } from "../(utils)/card-ref-href";
|
||||
|
||||
const TextClassName = "w-full text-sm leading-5 text-ink";
|
||||
|
||||
/**
|
||||
* A paragraph of a bot message. A card ref (a plan, questions, a proposal,
|
||||
* a hook proposal, a secret request) is a block, which React refuses
|
||||
* inside a `p`, so the paragraph is split around it: the text stays in
|
||||
* paragraphs and each card gets a line of its own, still in the message's
|
||||
* reading order.
|
||||
*/
|
||||
export default function MarkdownParagraph({ children }: { children?: ReactNode }) {
|
||||
const nodes = Children.toArray(children);
|
||||
|
||||
if (!nodes.some(isCardElement)) {
|
||||
return (
|
||||
<P noMargin className={TextClassName}>
|
||||
{children}
|
||||
</P>
|
||||
);
|
||||
}
|
||||
|
||||
const blocks: ReactNode[] = [];
|
||||
let line: ReactNode[] = [];
|
||||
|
||||
const flush = () => {
|
||||
const kept = line.filter((node) => typeof node != "string" || node.trim());
|
||||
|
||||
if (kept.length) {
|
||||
blocks.push(
|
||||
<P key={`line-${blocks.length}`} noMargin className={TextClassName}>
|
||||
{kept}
|
||||
</P>,
|
||||
);
|
||||
}
|
||||
|
||||
line = [];
|
||||
};
|
||||
|
||||
nodes.forEach((node, index) => {
|
||||
if (isCardElement(node)) {
|
||||
flush();
|
||||
blocks.push(
|
||||
<Stack key={`card-${index}`} className="w-full items-stretch">
|
||||
{node}
|
||||
</Stack>,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
line.push(node);
|
||||
});
|
||||
|
||||
flush();
|
||||
|
||||
return <Stack className="w-full gap-1! items-stretch">{blocks}</Stack>;
|
||||
}
|
||||
|
||||
function isCardElement(node: ReactNode): boolean {
|
||||
if (!isValidElement(node)) return false;
|
||||
|
||||
const href = (node.props as { href?: unknown }).href;
|
||||
|
||||
return typeof href == "string" && isCardRefHref({ href });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { BookOpen, PlugZap, Wrench } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { ExtensionProposalView } from "@/src/types";
|
||||
import useExtensionProposal from "../(hooks)/use-extension-proposal";
|
||||
import proposalStatusLabel from "../(utils)/proposal-status-label";
|
||||
import proposalTitle from "../(utils)/proposal-title";
|
||||
import ProposalCard from "./proposal-card";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
|
||||
type Props = {
|
||||
proposal_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* An MCP server, tool or skill the coordinator proposed (`proposalRef`),
|
||||
* shown in the message as the card the super admin confirms or rejects it
|
||||
* from, like a plan's card, so the decision is never hidden behind a chip.
|
||||
* Anyone it wasn't proposed to sees its number only.
|
||||
*/
|
||||
export default function ProposalRefCard({ proposal_id }: Props) {
|
||||
const { view, loading, setView } = useExtensionProposal({ proposal_id });
|
||||
|
||||
if (!view) {
|
||||
return <Span className="font-bold">{loading ? `proposal ${proposal_id}` : `proposal ${proposal_id} (not available)`}</Span>;
|
||||
}
|
||||
|
||||
const Icon = view.kind == "mcp" ? PlugZap : view.kind == "skill" ? BookOpen : Wrench;
|
||||
const title = proposalTitle({ view });
|
||||
const status = proposalStatusLabel({ view });
|
||||
const open = view.status == "pending" && !view.expired;
|
||||
|
||||
return (
|
||||
<RefCardShell
|
||||
icon={<Icon size={14} aria-hidden />}
|
||||
title={title}
|
||||
status={status}
|
||||
tone={open ? "warning" : view.status == "confirmed" ? "success" : "gray"}
|
||||
description={`${status}. The coordinator proposed this; nothing is saved until you confirm. Everything above the bot's own notes is read from what Confirm would save.`}
|
||||
>
|
||||
<ProposalCard view={view as ExtensionProposalView} onDecided={setView} />
|
||||
</RefCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { BookOpen, PlugZap, Wrench } from "lucide-react";
|
||||
import type { ExtensionProposalView } from "@/src/types";
|
||||
import useExtensionProposal from "../(hooks)/use-extension-proposal";
|
||||
import proposalStatusLabel from "../(utils)/proposal-status-label";
|
||||
import proposalTitle from "../(utils)/proposal-title";
|
||||
import ProposalCard from "./proposal-card";
|
||||
import RefChipModal from "./ref-chip-modal";
|
||||
|
||||
type Props = {
|
||||
proposal_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* An MCP server, tool or skill the coordinator proposed (`proposalRef`): a chip
|
||||
* naming it and where it stands, which opens the card the super admin
|
||||
* confirms or rejects it from. Anyone it wasn't proposed to sees its
|
||||
* number only.
|
||||
*/
|
||||
export default function ProposalRefChip({ proposal_id }: Props) {
|
||||
const { view, loading, setView } = useExtensionProposal({ proposal_id });
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const decided = (next: ExtensionProposalView) => {
|
||||
setView(next);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
if (!view) {
|
||||
return <Span className="font-bold">{loading ? `proposal ${proposal_id}` : `proposal ${proposal_id} (not available)`}</Span>;
|
||||
}
|
||||
|
||||
const Icon = view.kind == "mcp" ? PlugZap : view.kind == "skill" ? BookOpen : Wrench;
|
||||
const title = proposalTitle({ view });
|
||||
const status = proposalStatusLabel({ view });
|
||||
|
||||
return (
|
||||
<RefChipModal
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Review: ${title}`}
|
||||
onClick={() => setOpen(true)}
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold text-ink whitespace-nowrap",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0",
|
||||
)}
|
||||
>
|
||||
<Icon size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{`${title} · ${status}`}</Span>
|
||||
</Button>
|
||||
}
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`${status}. The coordinator proposed this; nothing is saved until you confirm. Everything above the bot's own notes is read from what Confirm would save.`}
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-2 max-h-[65vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
<ProposalCard view={view} onDecided={decided} />
|
||||
</Stack>
|
||||
</RefChipModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
|
||||
type Props = {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
status: string;
|
||||
tone: "success" | "warning" | "gray";
|
||||
description?: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The frame every card a bot puts up in the conversation shares (a plan's
|
||||
* steps, its questions, a proposal, a secret request): a header naming it
|
||||
* and where it stands, then the card itself. The header is built from
|
||||
* spans and rows so the whole card reads as one block in the message, the
|
||||
* way the plan card does, instead of a chip that hides it behind a modal.
|
||||
*/
|
||||
export default function RefCardShell({ icon, title, status, tone, description, children }: Props) {
|
||||
return (
|
||||
<Stack className="my-1 w-full gap-0! items-stretch overflow-hidden rounded-default border border-solid border-hairline bg-paper">
|
||||
<Row className="w-full flex-nowrap items-center gap-2 border-0 border-b border-solid border-hairline bg-surface py-1.5 pr-2 pl-3">
|
||||
<Span className="shrink-0 text-ink-secondary">{icon}</Span>
|
||||
<Span className="min-w-0 grow truncate text-sm font-bold text-ink">{title}</Span>
|
||||
<Tag color={tone} className="shrink-0">
|
||||
{status}
|
||||
</Tag>
|
||||
</Row>
|
||||
<Stack className="w-full gap-2! items-stretch p-3">
|
||||
{description ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{description}</Span>
|
||||
) : null}
|
||||
{children}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type {
|
||||
BotQuestionView,
|
||||
ExtensionProposalView,
|
||||
HookProposalView,
|
||||
SecretRequestView,
|
||||
} from "@/src/types";
|
||||
|
||||
const question: BotQuestionView = {
|
||||
id: 1,
|
||||
title: "Deploy now?",
|
||||
questions: [{ question: "When?", kind: "single", options: ["Now", "Later"], allow_other: false }],
|
||||
answers: null,
|
||||
status: "pending",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
};
|
||||
|
||||
const secret_request: SecretRequestView = {
|
||||
id: 3,
|
||||
key: "GITHUB_TOKEN",
|
||||
description: "A token to push.",
|
||||
reason: "To push the branch.",
|
||||
status: "pending",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
env_id: null,
|
||||
};
|
||||
|
||||
const proposal: ExtensionProposalView = {
|
||||
id: 4,
|
||||
kind: "mcp",
|
||||
extension_id: null,
|
||||
name: "GitHub",
|
||||
status: "pending",
|
||||
expired: false,
|
||||
expires_at: 0,
|
||||
outcome: "",
|
||||
result_id: null,
|
||||
host: null,
|
||||
envs: [],
|
||||
details: [],
|
||||
research: "",
|
||||
sources: [],
|
||||
};
|
||||
|
||||
const hook_proposal: HookProposalView = {
|
||||
id: 5,
|
||||
action: "create",
|
||||
hook_id: null,
|
||||
title: "GitHub pushes",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
status: "pending",
|
||||
expired: false,
|
||||
expires_at: 0,
|
||||
outcome: "",
|
||||
result_id: null,
|
||||
makes_url: true,
|
||||
details: [],
|
||||
reason: "So it hears about pushes.",
|
||||
};
|
||||
|
||||
mock.module("../(hooks)/use-bot-question", () => ({
|
||||
default: () => ({ view: question, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-secret-request", () => ({
|
||||
default: () => ({ view: secret_request, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-extension-proposal", () => ({
|
||||
default: () => ({ view: proposal, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-hook-proposal", () => ({
|
||||
default: () => ({ view: hook_proposal, loading: false, setView: () => {} }),
|
||||
}));
|
||||
|
||||
const { default: BotQuestionRefCard } = await import("./bot-question-ref-card");
|
||||
const { default: SecretRequestRefCard } = await import("./secret-request-ref-card");
|
||||
const { default: ProposalRefCard } = await import("./proposal-ref-card");
|
||||
const { default: HookProposalRefCard } = await import("./hook-proposal-ref-card");
|
||||
const { default: MarkdownParagraph } = await import("./markdown-paragraph");
|
||||
const { default: MarkdownLink } = await import("./markdown-link");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
/**
|
||||
* A card a bot puts up in the chat (a plan's steps, its questions, a
|
||||
* proposal, a secret request) shows in full under the message, the way the
|
||||
* plan card does, instead of behind a chip that opens a modal.
|
||||
*/
|
||||
describe("cards in a bot message", () => {
|
||||
test("questions show what is asked and can be answered there", () => {
|
||||
const html = renderToString(<BotQuestionRefCard question_id={question.id} />);
|
||||
|
||||
expect(html).toContain("Deploy now?");
|
||||
expect(html).toContain("Waiting for you");
|
||||
expect(html).toContain("When?");
|
||||
expect(html).toContain("Now");
|
||||
});
|
||||
|
||||
test("a secret request shows the key it asks for", () => {
|
||||
const html = renderToString(<SecretRequestRefCard request_id={secret_request.id} />);
|
||||
|
||||
expect(html).toContain("GITHUB_TOKEN");
|
||||
expect(html).toContain("Waiting for you");
|
||||
expect(html).toContain("never does");
|
||||
});
|
||||
|
||||
test("an extension proposal shows what would be saved", () => {
|
||||
const html = renderToString(<ProposalRefCard proposal_id={proposal.id} />);
|
||||
|
||||
expect(html).toContain("Add MCP server GitHub");
|
||||
expect(html).toContain("Waiting for you");
|
||||
});
|
||||
|
||||
test("a hook proposal shows what it would hear", () => {
|
||||
const html = renderToString(<HookProposalRefCard proposal_id={hook_proposal.id} />);
|
||||
|
||||
expect(html).toContain("Add hook GitHub pushes");
|
||||
expect(html).toContain("Waiting for you");
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A markdown paragraph is a `p`, which takes phrasing content only, so a
|
||||
* card ref written on its own line has to be lifted out of it: otherwise
|
||||
* React reports "p cannot contain a nested div" for every card on the
|
||||
* page.
|
||||
*/
|
||||
describe("MarkdownParagraph", () => {
|
||||
test("keeps plain text in one paragraph", () => {
|
||||
const html = renderToString(<MarkdownParagraph>Just a line.</MarkdownParagraph>);
|
||||
|
||||
expect(html).toContain("Just a line.");
|
||||
expect(html).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("lifts a card ref out of the paragraph, text before and after", () => {
|
||||
const html = renderToString(
|
||||
<MarkdownParagraph>
|
||||
{"Before "}
|
||||
<MarkdownLink href={`#question-${question.id}`}>questions</MarkdownLink>
|
||||
{" after"}
|
||||
</MarkdownParagraph>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Before");
|
||||
expect(html).toContain("Deploy now?");
|
||||
expect(html).toContain("after");
|
||||
|
||||
const before = html.indexOf("Before");
|
||||
const paragraph_end = html.indexOf("</p>", before);
|
||||
const card = html.indexOf("Deploy now?");
|
||||
const after = html.indexOf("after", card);
|
||||
|
||||
expect(paragraph_end).toBeGreaterThan(before);
|
||||
expect(card).toBeGreaterThan(paragraph_end);
|
||||
expect(after).toBeGreaterThan(card);
|
||||
expect(html.indexOf("<p", after)).toBeGreaterThan(card);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import RefChipModal from "./ref-chip-modal";
|
||||
|
||||
/**
|
||||
* A ref chip sits in a markdown paragraph, which takes phrasing content
|
||||
* only. twui's own `Modal` target wrapper is a div, so the chip used to
|
||||
* put a div in the paragraph and React logged "p cannot contain a nested
|
||||
* div" for every question or proposal chip on the page.
|
||||
*/
|
||||
describe("RefChipModal", () => {
|
||||
test("wraps its trigger in a span, with no block element beside it", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<RefChipModal trigger={<Button type="button" title="Review">Review</Button>} open={false} onClose={() => {}}>
|
||||
<Span>Card</Span>
|
||||
</RefChipModal>
|
||||
</P>,
|
||||
);
|
||||
|
||||
// twui's own Button fills itself with a div, valid inside a button
|
||||
// (React only warns about a p in button scope), so the paragraph
|
||||
// is broken only by a div before the button: twui's Modal used to
|
||||
// wrap its target in one.
|
||||
const first_button = html.indexOf("<button");
|
||||
|
||||
expect(html).toContain('<span class="twui-span inline-flex max-w-full align-middle">');
|
||||
expect(html).toContain("Review");
|
||||
expect(first_button).toBeGreaterThan(-1);
|
||||
expect(html.slice(0, first_button)).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("mounts the card only while open", () => {
|
||||
const html = renderToString(
|
||||
<RefChipModal trigger={<Button type="button" title="Review">Review</Button>} open={false} onClose={() => {}}>
|
||||
<Span>Card</Span>
|
||||
</RefChipModal>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain("Card");
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
|
||||
type Props = {
|
||||
trigger: ReactNode;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* A ref chip's trigger and the card it opens (`[question:ID]`,
|
||||
* `[proposal:ID]`, ...). The chip sits in a markdown paragraph, which takes
|
||||
* phrasing content only: the trigger is a span around the caller's button,
|
||||
* and the card is mounted only while open, since twui's own `target`
|
||||
* wrapper is a div and a div inside the paragraph is invalid (React says
|
||||
* so in the console).
|
||||
*/
|
||||
export default function RefChipModal({ trigger, open, onClose, className, children }: Props) {
|
||||
return (
|
||||
<>
|
||||
<Span className="inline-flex max-w-full align-middle">{trigger}</Span>
|
||||
{open ? (
|
||||
<Modal
|
||||
open
|
||||
setOpen={(next_open) => {
|
||||
if (!next_open) onClose();
|
||||
}}
|
||||
className={className}
|
||||
>
|
||||
{children}
|
||||
</Modal>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import type {
|
||||
BotQuestionView,
|
||||
ExtensionProposalView,
|
||||
HookProposalView,
|
||||
SecretRefView,
|
||||
SecretRequestView,
|
||||
} from "@/src/types";
|
||||
|
||||
const question: BotQuestionView = {
|
||||
id: 1,
|
||||
title: "Deploy now?",
|
||||
questions: [{ question: "When?", kind: "single", options: ["Now", "Later"], allow_other: false }],
|
||||
answers: null,
|
||||
status: "pending",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
};
|
||||
|
||||
const secret_request: SecretRequestView = {
|
||||
id: 3,
|
||||
key: "GITHUB_TOKEN",
|
||||
description: "A token to push.",
|
||||
reason: "To push the branch.",
|
||||
status: "pending",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
env_id: null,
|
||||
};
|
||||
|
||||
const proposal: ExtensionProposalView = {
|
||||
id: 4,
|
||||
kind: "mcp",
|
||||
extension_id: null,
|
||||
name: "GitHub",
|
||||
status: "pending",
|
||||
expired: false,
|
||||
expires_at: 0,
|
||||
outcome: "",
|
||||
result_id: null,
|
||||
host: null,
|
||||
envs: [],
|
||||
details: [],
|
||||
research: "",
|
||||
sources: [],
|
||||
};
|
||||
|
||||
const hook_proposal: HookProposalView = {
|
||||
id: 5,
|
||||
action: "create",
|
||||
hook_id: null,
|
||||
title: "GitHub pushes",
|
||||
bot_id: 2,
|
||||
bot_name: "Ada",
|
||||
status: "pending",
|
||||
expired: false,
|
||||
expires_at: 0,
|
||||
outcome: "",
|
||||
result_id: null,
|
||||
makes_url: true,
|
||||
details: [],
|
||||
reason: "So it hears about pushes.",
|
||||
};
|
||||
|
||||
const secret: SecretRefView = {
|
||||
id: 6,
|
||||
key: "NPM_TOKEN",
|
||||
description: "A token to publish.",
|
||||
can_reveal: true,
|
||||
};
|
||||
|
||||
mock.module("../(hooks)/use-bot-question", () => ({
|
||||
default: () => ({ view: question, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-secret-request", () => ({
|
||||
default: () => ({ view: secret_request, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-extension-proposal", () => ({
|
||||
default: () => ({ view: proposal, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-hook-proposal", () => ({
|
||||
default: () => ({ view: hook_proposal, loading: false, setView: () => {} }),
|
||||
}));
|
||||
mock.module("../(hooks)/use-secret-ref", () => ({
|
||||
default: () => ({ view: secret, loading: false }),
|
||||
}));
|
||||
|
||||
const { default: BotQuestionRefChip } = await import("./bot-question-ref-chip");
|
||||
const { default: SecretRequestRefChip } = await import("./secret-request-ref-chip");
|
||||
const { default: ProposalRefChip } = await import("./proposal-ref-chip");
|
||||
const { default: HookProposalRefChip } = await import("./hook-proposal-ref-chip");
|
||||
const { default: SecretRefChip } = await import("./secret-ref-chip");
|
||||
|
||||
/**
|
||||
* twui's Button fills itself with a div, valid inside a button (React only
|
||||
* warns about a p in button scope), so what a paragraph may not hold is a
|
||||
* div outside one: twui's Modal used to wrap each chip's trigger in one.
|
||||
*/
|
||||
function outsideButtons(html: string) {
|
||||
return html.replaceAll(/<button[\s\S]*?<\/button>/g, "");
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
/**
|
||||
* Message markdown renders bot text in real paragraphs, so every ref chip
|
||||
* that lands in it must be phrasing content: a block element beside its
|
||||
* text was React's "p cannot contain a nested div" warning, once per chip
|
||||
* on the page.
|
||||
*/
|
||||
describe("ref chips in a markdown paragraph", () => {
|
||||
test("a question chip", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<BotQuestionRefChip question_id={question.id} />
|
||||
</P>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Deploy now?");
|
||||
expect(outsideButtons(html)).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("a secret request chip", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<SecretRequestRefChip request_id={secret_request.id} />
|
||||
</P>,
|
||||
);
|
||||
|
||||
expect(html).toContain("GITHUB_TOKEN");
|
||||
expect(outsideButtons(html)).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("an extension proposal chip", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<ProposalRefChip proposal_id={proposal.id} />
|
||||
</P>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Add MCP server GitHub");
|
||||
expect(outsideButtons(html)).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("a hook proposal chip", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<HookProposalRefChip proposal_id={hook_proposal.id} />
|
||||
</P>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Add hook GitHub pushes");
|
||||
expect(outsideButtons(html)).not.toContain("<div");
|
||||
});
|
||||
|
||||
test("a secret chip", () => {
|
||||
const html = renderToString(
|
||||
<P noMargin>
|
||||
<SecretRefChip env_id={secret.id} />
|
||||
</P>,
|
||||
);
|
||||
|
||||
expect(html).toContain("NPM_TOKEN");
|
||||
expect(outsideButtons(html)).not.toContain("<div");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { KeyRound } from "lucide-react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useSecretRequest from "../(hooks)/use-secret-request";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
import SecretRequestCard from "./secret-request-card";
|
||||
|
||||
type Props = {
|
||||
request_id: number;
|
||||
};
|
||||
|
||||
const StatusLabels = {
|
||||
pending: "Waiting for you",
|
||||
saved: "Saved",
|
||||
declined: "Declined",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* A secret a bot asked for (`secretRequestRef`), shown in the message as
|
||||
* the card the user types it into, like a plan's card. It never passes
|
||||
* through the bot's model. Anyone it wasn't asked of sees its number only.
|
||||
*/
|
||||
export default function SecretRequestRefCard({ request_id }: Props) {
|
||||
const { view, loading, setView } = useSecretRequest({ request_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `secret request ${request_id}` : `secret request ${request_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const pending = view.status == "pending";
|
||||
|
||||
return (
|
||||
<RefCardShell
|
||||
icon={<KeyRound size={14} aria-hidden />}
|
||||
title={`${view.bot_name} asks for ${view.key}`}
|
||||
status={StatusLabels[view.status]}
|
||||
tone={pending ? "warning" : view.status == "saved" ? "success" : "gray"}
|
||||
description={
|
||||
pending
|
||||
? "Type it here rather than in the chat: what you write in the chat goes to the bot's model provider, this never does."
|
||||
: `${view.bot_name} asked for this key. It never went through the bot's model.`
|
||||
}
|
||||
>
|
||||
<SecretRequestCard view={view} onDecided={setView} onDone={() => {}} />
|
||||
</RefCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import useSecretRequest from "../(hooks)/use-secret-request";
|
||||
import SecretRequestCard from "./secret-request-card";
|
||||
import RefChipModal from "./ref-chip-modal";
|
||||
|
||||
type Props = {
|
||||
request_id: number;
|
||||
};
|
||||
|
||||
const StatusLabels = {
|
||||
pending: "waiting for you",
|
||||
saved: "saved",
|
||||
declined: "declined",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* A secret a bot asked for (`secretRequestRef`): a chip naming its key and
|
||||
* where it stands, which opens the card the user types it into. Anyone it
|
||||
* wasn't asked of sees its number only.
|
||||
*/
|
||||
export default function SecretRequestRefChip({ request_id }: Props) {
|
||||
const { view, loading, setView } = useSecretRequest({ request_id });
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `secret request ${request_id}` : `secret request ${request_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const status = StatusLabels[view.status];
|
||||
|
||||
return (
|
||||
<RefChipModal
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={view.status == "pending" ? `Enter ${view.key}` : `${view.key}: ${status}`}
|
||||
onClick={() => setOpen(true)}
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold text-ink whitespace-nowrap",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0",
|
||||
)}
|
||||
>
|
||||
<KeyRound size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{`${view.key} · ${status}`}</Span>
|
||||
</Button>
|
||||
}
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{`${view.bot_name} asks for ${view.key}`}</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`Type it here rather than in the chat: what you write in the chat goes to the bot's model provider, this never does.`}
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-2 max-h-[65vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
<SecretRequestCard view={view} onDecided={setView} onDone={() => setOpen(false)} />
|
||||
</Stack>
|
||||
</RefChipModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { HookProposalRefHrefPrefix, ProposalRefHrefPrefix, SecretRequestRefHrefPrefix } from "@/src/utils/link-computer-refs";
|
||||
import { botPlanRefId } from "@/src/utils/bot-plan-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
|
||||
/**
|
||||
* Whether a ref link stands for a card shown in full under the message (a
|
||||
* plan, questions, a proposal, a hook proposal, a secret request) rather
|
||||
* than a chip on the line. Those cards are blocks, so the message's
|
||||
* paragraph has to lift them out of itself (React refuses a block inside a
|
||||
* `p`).
|
||||
*/
|
||||
export function isCardRefHref({ href }: { href?: string }): boolean {
|
||||
if (!href) return false;
|
||||
|
||||
return Boolean(
|
||||
botPlanRefId({ href }) ||
|
||||
botQuestionRefId({ href }) ||
|
||||
href.startsWith(ProposalRefHrefPrefix) ||
|
||||
href.startsWith(HookProposalRefHrefPrefix) ||
|
||||
href.startsWith(SecretRequestRefHrefPrefix),
|
||||
);
|
||||
}
|
||||
@@ -20,17 +20,17 @@ import { taskRefId } from "@/src/utils/task-ref";
|
||||
import { askRefId } from "@/src/utils/ask-ref";
|
||||
import { generalSettingsRefId } from "@/src/utils/general-settings-ref";
|
||||
import BotPlanCard from "../(partials)/bot-plan-card";
|
||||
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
|
||||
import BotQuestionRefCard from "../(partials)/bot-question-ref-card";
|
||||
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
import ComputerRefChip from "../(partials)/computer-ref-chip";
|
||||
import FileRefChip from "../(partials)/file-ref-chip";
|
||||
import FolderRefChip from "../(partials)/folder-ref-chip";
|
||||
import GraphicRefCard from "../(partials)/graphic-ref-card";
|
||||
import HookProposalRefChip from "../(partials)/hook-proposal-ref-chip";
|
||||
import ProposalRefChip from "../(partials)/proposal-ref-chip";
|
||||
import HookProposalRefCard from "../(partials)/hook-proposal-ref-card";
|
||||
import ProposalRefCard from "../(partials)/proposal-ref-card";
|
||||
import SecretRefChip from "../(partials)/secret-ref-chip";
|
||||
import SecretRequestRefChip from "../(partials)/secret-request-ref-chip";
|
||||
import SecretRequestRefCard from "../(partials)/secret-request-ref-card";
|
||||
import SettingRefChip from "../(partials)/setting-ref-chip";
|
||||
import TakeOverChip from "../(partials)/take-over-chip";
|
||||
import TaskRefChip from "../(partials)/task-ref-chip";
|
||||
@@ -90,13 +90,13 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
if (href?.startsWith(ProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(ProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <ProposalRefChip proposal_id={proposal_id} />;
|
||||
if (proposal_id) return <ProposalRefCard proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(HookProposalRefHrefPrefix)) {
|
||||
const proposal_id = Number(href.slice(HookProposalRefHrefPrefix.length));
|
||||
|
||||
if (proposal_id) return <HookProposalRefChip proposal_id={proposal_id} />;
|
||||
if (proposal_id) return <HookProposalRefCard proposal_id={proposal_id} />;
|
||||
}
|
||||
|
||||
if (href?.startsWith(SecretRefHrefPrefix)) {
|
||||
@@ -108,11 +108,11 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
if (href?.startsWith(SecretRequestRefHrefPrefix)) {
|
||||
const request_id = Number(href.slice(SecretRequestRefHrefPrefix.length));
|
||||
|
||||
if (request_id) return <SecretRequestRefChip request_id={request_id} />;
|
||||
if (request_id) return <SecretRequestRefCard request_id={request_id} />;
|
||||
}
|
||||
|
||||
const question_id = botQuestionRefId({ href });
|
||||
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
|
||||
if (question_id) return <BotQuestionRefCard question_id={question_id} />;
|
||||
|
||||
const suggestion_id = botSuggestionRefId({ href });
|
||||
if (suggestion_id) return <BotSuggestionsRef suggestion_id={suggestion_id} />;
|
||||
|
||||
Reference in New Issue
Block a user