Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): question cards, answer summaries, and themed chat blocks (#354)

Leo020a7b5c9630
diff --git a/.changeset/question-cards-and-chat-blocks.md b/.changeset/question-cards-and-chat-blocks.md
new file mode 100644
index 000000000..30566005e
--- /dev/null
+++ b/.changeset/question-cards-and-chat-blocks.md
@@ -0,0 +1,5 @@
+---
+"akeru-bot": minor
+---
+
+Bot questions now appear as a card with one question at a time, round marks for single-choice and checkboxes for multi-select, number-key shortcuts, and an in-card field for your own answer. Answers show as a summary instead of a plain text message. Replies can render charts, stats, task lists, timelines, flow diagrams, and choices in your theme's colors. The Akeru Paper and Akeru Noir themes no longer use purple, and the question card no longer links to the bot's computer.
diff --git a/apps/mobile/src/lib/mobileDefaultTheme.ts b/apps/mobile/src/lib/mobileDefaultTheme.ts
index 398642f11..e9890095c 100644
--- a/apps/mobile/src/lib/mobileDefaultTheme.ts
+++ b/apps/mobile/src/lib/mobileDefaultTheme.ts
@@ -22,9 +22,9 @@ export const DEFAULT_MOBILE_THEME_VARIABLES = {
"--color-separator": "rgba(0, 0, 0, 0.04)",
"--color-subtle": "rgba(0, 0, 0, 0.04)",
"--color-subtle-strong": "rgba(0, 0, 0, 0.08)",
- "--color-inline-skill-background": "rgba(217, 70, 239, 0.12)",
- "--color-inline-skill-border": "rgba(217, 70, 239, 0.25)",
- "--color-inline-skill-foreground": "#a21caf",
+ "--color-inline-skill-background": "rgba(59, 130, 246, 0.12)",
+ "--color-inline-skill-border": "rgba(59, 130, 246, 0.25)",
+ "--color-inline-skill-foreground": "#1d4ed8",
"--color-primary": "#262626",
"--color-primary-foreground": "#ffffff",
"--color-primary-shadow": "#000000",
@@ -65,7 +65,7 @@ export const DEFAULT_MOBILE_THEME_VARIABLES = {
"--color-user-bubble": "#e9e9eb",
"--color-user-bubble-foreground": "#1c1c1e",
"--color-user-bubble-foreground-muted": "rgba(28, 28, 30, 0.6)",
- "--color-user-bubble-skill-foreground": "#a21caf",
+ "--color-user-bubble-skill-foreground": "#1d4ed8",
"--color-backdrop": "rgba(0, 0, 0, 0.22)",
"--color-drawer": "rgba(255, 255, 255, 0.99)",
"--color-drawer-shadow": "rgba(0, 0, 0, 0.12)",
@@ -93,9 +93,9 @@ export const DEFAULT_MOBILE_THEME_VARIABLES = {
"--color-separator": "rgba(255, 255, 255, 0.03)",
"--color-subtle": "rgba(255, 255, 255, 0.04)",
"--color-subtle-strong": "rgba(255, 255, 255, 0.08)",
- "--color-inline-skill-background": "rgba(217, 70, 239, 0.12)",
- "--color-inline-skill-border": "rgba(217, 70, 239, 0.25)",
- "--color-inline-skill-foreground": "#f0abfc",
+ "--color-inline-skill-background": "rgba(59, 130, 246, 0.12)",
+ "--color-inline-skill-border": "rgba(59, 130, 246, 0.25)",
+ "--color-inline-skill-foreground": "#93c5fd",
"--color-primary": "#f5f5f5",
"--color-primary-foreground": "#0a0a0a",
"--color-primary-shadow": "#000000",
@@ -136,7 +136,7 @@ export const DEFAULT_MOBILE_THEME_VARIABLES = {
"--color-user-bubble": "#2c2c2e",
"--color-user-bubble-foreground": "#ffffff",
"--color-user-bubble-foreground-muted": "rgba(255, 255, 255, 0.78)",
- "--color-user-bubble-skill-foreground": "#f0abfc",
+ "--color-user-bubble-skill-foreground": "#93c5fd",
"--color-backdrop": "rgba(0, 0, 0, 0.48)",
"--color-drawer": "rgba(14, 14, 14, 0.99)",
"--color-drawer-shadow": "rgba(0, 0, 0, 0.32)",
diff --git a/apps/mobile/src/lib/mobileTheme.test.ts b/apps/mobile/src/lib/mobileTheme.test.ts
index 843d0f436..065ec7694 100644
--- a/apps/mobile/src/lib/mobileTheme.test.ts
+++ b/apps/mobile/src/lib/mobileTheme.test.ts
@@ -122,12 +122,12 @@ describe("mobile themes", () => {
getMobileThemeVariables(DEFAULT_MOBILE_THEME_ID, "light")[
"--color-user-bubble-skill-foreground"
],
- ).toBe("#a21caf");
+ ).toBe("#1d4ed8");
expect(
getMobileThemeVariables(DEFAULT_MOBILE_THEME_ID, "dark")[
"--color-user-bubble-skill-foreground"
],
- ).toBe("#f0abfc");
+ ).toBe("#93c5fd");
});
it("applies palette overrides on top of the selected built-in theme", () => {
diff --git a/apps/mobile/src/lib/mobileTheme.ts b/apps/mobile/src/lib/mobileTheme.ts
index 89c4af52c..7d131cc3a 100644
--- a/apps/mobile/src/lib/mobileTheme.ts
+++ b/apps/mobile/src/lib/mobileTheme.ts
@@ -242,6 +242,21 @@ function readableMessageAccent(accent: string, surface: string): string {
return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
+/**
+ * The theme's action color marks skills in a sent message, unless it reads as the message text
+ * itself (a monochrome theme). Then skills keep the default skill color, as on web.
+ */
+function skillAccent(accent: string, text: string, appearance: MobileThemeAppearance): string {
+ const accentChannels = rgbChannels(accent);
+ const textChannels = rgbChannels(text);
+
+ if (accentChannels && textChannels && contrastRatio(accentChannels, textChannels) < 1.5) {
+ return DEFAULT_MOBILE_THEME_VARIABLES[appearance]["--color-user-bubble-skill-foreground"];
+ }
+
+ return accent;
+}
+
export function themeColorWithAlpha(color: string, alpha: number): string {
const hex = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color);
@@ -324,7 +339,7 @@ export function createMobileThemeVariables(
"--color-user-bubble-foreground": c.messageForeground,
"--color-user-bubble-foreground-muted": withAlpha(c.messageForeground, 0.78),
"--color-user-bubble-skill-foreground": readableMessageAccent(
- c.messageAction,
+ skillAccent(c.messageAction, c.messageForeground, appearance),
c.messageSurface,
),
"--color-backdrop": withAlpha("#000000", appearance === "dark" ? 0.48 : 0.22),
diff --git a/apps/web/index.html b/apps/web/index.html
index 983a421d2..51b05f783 100644
--- a/apps/web/index.html
+++ b/apps/web/index.html
@@ -29,12 +29,12 @@
light: {
background: "#ffffff",
foreground: "#262626",
- accent: "#8B6FC9",
+ accent: "#262626",
},
dark: {
background: "#050505",
foreground: "#f5f5f5",
- accent: "#8B6FC9",
+ accent: "#f5f5f5",
},
};
// These are the runtime defaults used to complete a custom palette
@@ -62,13 +62,13 @@
light: {
background: "oklch(0.99 0.001 286.375)",
foreground: "oklch(0.21 0.006 285.885)",
- accent: "oklch(0.607447 0.134946 296.512)",
+ accent: "oklch(0.21 0.006 285.885)",
chrome: "oklch(0.975 0.0015 286.375)",
},
dark: {
background: "oklch(0.105 0 0)",
foreground: "oklch(0.97 0.0013 286.375)",
- accent: "oklch(0.607447 0.134946 296.512)",
+ accent: "oklch(0.97 0.0013 286.375)",
chrome: "oklch(0.135 0 0)",
},
},
@@ -76,13 +76,13 @@
light: {
background: "oklch(0.985 0.001 85)",
foreground: "oklch(0.235 0.003 70)",
- accent: "oklch(0.607447 0.134946 296.512)",
+ accent: "oklch(0.235 0.003 70)",
chrome: "oklch(0.962 0.0015 85)",
},
dark: {
background: "oklch(0.114918 0 0)",
- foreground: "oklch(0.967434 0.001326 286.375)",
- accent: "oklch(0.607447 0.134946 296.512)",
+ foreground: "oklch(0.967 0 0)",
+ accent: "oklch(0.967 0 0)",
chrome: "oklch(0.177638 0 0)",
},
},
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 418531492..84c8ebfb1 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -63,6 +63,12 @@ import {
orderedListGutter,
} from "./markdown/MarkdownLists";
import { ChatMarkdownRendererContext } from "./markdown/MarkdownRendererContext";
+import { GenerativeBlock } from "./markdown/generative/GenerativeBlock";
+import { GenerativeBlockPending } from "./markdown/generative/GenerativeFrame";
+import {
+ decodeGenerativeBlock,
+ generativeKindForLanguage,
+} from "./markdown/generative/generativeSchemas";
import { MarkdownDetails, MarkdownTable } from "./markdown/MarkdownTable";
import {
CHAT_MARKDOWN_REHYPE_PLUGINS_WITH_RAW_HTML,
@@ -405,6 +411,16 @@ const CHAT_MARKDOWN_COMPONENTS: Components = {
return <MarkdownMermaidDiagram code={codeBlock.code} theme={resolvedTheme} />;
}
+ const generativeKind = generativeKindForLanguage(language);
+
+ if (generativeKind) {
+ const block = decodeGenerativeBlock(generativeKind, codeBlock.code);
+
+ if (block) return <GenerativeBlock block={block} />;
+
+ if (isStreaming) return <GenerativeBlockPending />;
+ }
+
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
if (MARKDOWN_DIFF_LANGUAGES.has(language.toLowerCase())) {
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
index 4077787ff..6099dbeb0 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
@@ -5,74 +5,140 @@ import { describe, expect, it } from "vite-plus/test";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import type { PendingUserInput } from "../../session-logic";
-const prompt: PendingUserInput = {
- requestId: ApprovalRequestId.make("request-1"),
- createdAt: "2026-08-15T00:00:00.000Z",
- questions: [
- {
- id: "question-1",
- header: "Approach",
- question: "Which approach should the migration take?",
- options: [
- { label: "Incremental", description: "Move one module at a time" },
- { label: "Big bang", description: "Move everything in one release" },
- ],
- multiSelect: false,
- },
+const approachQuestion = {
+ id: "question-1",
+ header: "Approach",
+ question: "Which approach should the migration take?",
+ options: [
+ { label: "Incremental", description: "Move one module at a time" },
+ { label: "Big bang", description: "Move everything in one release" },
],
+ multiSelect: false,
};
-function renderPanel() {
+const areasQuestion = {
+ id: "question-2",
+ header: "Areas",
+ question: "Which areas should it cover first?",
+ options: [
+ { label: "Server", description: "Server" },
+ { label: "Web", description: "Web" },
+ ],
+ multiSelect: true,
+};
+
+function prompt(questions: PendingUserInput["questions"]): PendingUserInput {
+ return {
+ requestId: ApprovalRequestId.make("request-1"),
+ createdAt: "2026-08-15T00:00:00.000Z",
+ questions,
+ };
+}
+
+function renderPanel(
+ questions: PendingUserInput["questions"],
+ answers: Parameters<typeof ComposerPendingUserInputPanel>[0]["answers"] = {},
+ step = 0,
+) {
return renderToStaticMarkup(
<ComposerPendingUserInputPanel
- pendingUserInputs={[prompt]}
+ pendingUserInputs={[prompt(questions)]}
respondingRequestIds={[]}
- answers={{}}
- questionIndex={0}
- onToggleOption={() => {}}
+ answers={answers}
+ step={step}
+ onStepChange={() => {}}
+ onSelectOption={() => {}}
+ onAnswerWithText={() => {}}
+ onSubmit={() => {}}
/>,
);
}
+const disabledButton = (label: string) =>
+ new RegExp(`<button[^>]*disabled=""[^>]*>${label}</button>`);
+
describe("ComposerPendingUserInputPanel", () => {
- it("renders a standalone question card with letter shortcuts", () => {
- const markup = renderPanel();
+ it("sends a lone single-choice question on click, so it shows no steps or Submit", () => {
+ const markup = renderPanel([approachQuestion]);
expect(markup).toContain('data-testid="pending-user-input-card"');
expect(markup).toContain('aria-label="Which approach should the migration take?"');
- expect(markup).toContain("<kbd");
- expect(markup).toContain(">A</kbd>");
- expect(markup).toContain(">B</kbd>");
- expect(markup).not.toContain("data-pending-user-input-toggle");
+ expect(markup).toContain(">1</kbd>");
+ expect(markup).toContain(">2</kbd>");
+ expect(markup).not.toContain(">Submit</button>");
+ expect(markup).not.toContain("gen-step");
});
- it("starts expanded so the question and its options are visible", () => {
- const markup = renderPanel();
+ it("shows one question at a time with its place in the set", () => {
+ const markup = renderPanel([approachQuestion, areasQuestion]);
expect(markup).toContain("Which approach should the migration take?");
- expect(markup).toContain("Incremental");
- expect(markup).toContain("Big bang");
+ expect(markup).not.toContain("Which areas should it cover first?");
+ expect(markup).toContain("1 of 2");
+ expect(markup).toContain('data-state="current"');
+ expect(markup).not.toContain(">Back</button>");
});
- it("shows a submit action after a multi-select answer is selected", () => {
- const multiSelectPrompt: PendingUserInput = {
- ...prompt,
- questions: [{ ...prompt.questions[0]!, multiSelect: true }],
+ it("waits for Next on an unanswered step", () => {
+ const open = renderPanel([approachQuestion, areasQuestion]);
+ expect(open).toMatch(disabledButton("Next"));
+
+ const answered = renderPanel([approachQuestion, areasQuestion], {
+ "question-1": { selectedOptionLabels: ["Incremental"] },
+ });
+
+ expect(answered).toContain(">Next</button>");
+ expect(answered).not.toMatch(disabledButton("Next"));
+ });
+
+ it("offers Back and Submit on the last step, enabled once every question is answered", () => {
+ const partial = renderPanel([approachQuestion, areasQuestion], {}, 1);
+
+ expect(partial).toContain("Which areas should it cover first?");
+ expect(partial).toContain("Pick any that apply.");
+ expect(partial).toMatch(/<svg[^>]*>.*<\/svg>Back<\/button>/);
+ expect(partial).toMatch(disabledButton("Submit"));
+
+ const complete = renderPanel(
+ [approachQuestion, areasQuestion],
+ {
+ "question-1": { selectedOptionLabels: ["Incremental"] },
+ "question-2": { selectedOptionLabels: ["Web"] },
+ },
+ 1,
+ );
+
+ expect(complete).toContain('data-state="done"');
+ expect(complete).toContain(">Submit</button>");
+ expect(complete).not.toMatch(disabledButton("Submit"));
+ });
+
+ it("dims the other options of an answered single choice, but never of a multi-select", () => {
+ const answers = {
+ "question-1": { selectedOptionLabels: ["Incremental"] },
+ "question-2": { selectedOptionLabels: ["Web"] },
};
- const markup = renderToStaticMarkup(
- <ComposerPendingUserInputPanel
- pendingUserInputs={[multiSelectPrompt]}
- respondingRequestIds={[]}
- answers={{ "question-1": { selectedOptionLabels: ["Incremental"] } }}
- questionIndex={0}
- onToggleOption={() => {}}
- onAdvance={() => {}}
- />,
+ expect(renderPanel([approachQuestion, areasQuestion], answers, 0)).toContain(
+ 'data-answered="true"',
);
+ expect(renderPanel([approachQuestion, areasQuestion], answers, 1)).toContain(
+ 'data-answered="false"',
+ );
+ });
+
+ it("offers a row for a typed answer and fills it in once one is typed", () => {
+ const empty = renderPanel([approachQuestion, areasQuestion], {});
+
+ expect(empty).toContain('placeholder="Type your own answer"');
+ expect(empty).not.toContain('data-selected="true"');
+
+ const markup = renderPanel([approachQuestion, areasQuestion], {
+ "question-1": { customAnswer: "Whatever is safest" },
+ });
- expect(markup).toContain(">Submit</button>");
- expect(markup).toContain('aria-pressed="true"');
- expect(markup).toContain('aria-pressed="false"');
+ expect(markup).toContain('value="Whatever is safest"');
+ expect(markup).toContain('data-selected="true"');
+ expect(markup).not.toContain('aria-pressed="true"');
});
});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index 75f4e0fb2..16974a182 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -1,284 +1,307 @@
-import { type ApprovalRequestId } from "@akeru/contracts";
-import { memo, useCallback, useEffect, useRef, useState } from "react";
-import { type PendingUserInput } from "../../session-logic";
+import { type ApprovalRequestId, type UserInputQuestion } from "@akeru/contracts";
+import { ChevronLeftIcon } from "lucide-react";
+import { memo, useEffect, useRef, useState, type RefObject } from "react";
+import { useI18n } from "~/i18n";
import {
- derivePendingUserInputProgress,
+ buildPendingUserInputAnswers,
type PendingUserInputDraftAnswer,
+ pendingUserInputKeyAction,
+ resolvePendingUserInputAnswer,
} from "../../pendingUserInput";
-import { CheckIcon } from "lucide-react";
+import { type PendingUserInput } from "../../session-logic";
import { Button } from "../ui/button";
-import { useI18n } from "~/i18n";
-import { cn } from "~/lib/utils";
+import { Card } from "../ui/card";
+import { ChoiceButton, OwnAnswerRow } from "./PendingUserInputChoices";
interface PendingUserInputPanelProps {
pendingUserInputs: PendingUserInput[];
respondingRequestIds: ApprovalRequestId[];
answers: Record<string, PendingUserInputDraftAnswer>;
- questionIndex: number;
- onToggleOption: (questionId: string, optionLabel: string) => void;
- onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
- onAdvance?: () => void;
- className?: string;
+ /** The question on screen. Typed replies answer this one too. */
+ step: number;
+ onStepChange: (step: number) => void;
+ onSelectOption: (questionId: string, optionLabel: string) => void;
+ /** Answers the question on screen with text typed into the card's own-answer row. */
+ onAnswerWithText: (text: string) => void;
+ onSubmit?: () => void;
+ /** `docked` drops the card chrome when a host surface already frames the panel. */
+ surface?: "card" | "docked";
}
+/**
+ * The bot's open question as one card that shows a single question at a time. A single-choice
+ * pick moves to the next question and the last one sends; multi-select steps wait for Next.
+ * Number keys pick options on the question on screen, other typing goes to the own-answer row,
+ * and Enter moves on.
+ */
export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
pendingUserInputs,
respondingRequestIds,
answers,
- questionIndex,
- onToggleOption,
- onSelectSingleOption,
- onAdvance,
- className,
+ step,
+ onStepChange,
+ onSelectOption,
+ onAnswerWithText,
+ onSubmit,
+ surface = "card",
}: PendingUserInputPanelProps) {
- if (pendingUserInputs.length === 0) return null;
const activePrompt = pendingUserInputs[0];
if (!activePrompt) return null;
return (
- <ComposerPendingUserInputCard
+ <PendingUserInputCard
key={activePrompt.requestId}
prompt={activePrompt}
isResponding={respondingRequestIds.includes(activePrompt.requestId)}
answers={answers}
- questionIndex={questionIndex}
- onToggleOption={onToggleOption}
- {...(className ? { className } : {})}
- {...(onSelectSingleOption ? { onSelectSingleOption } : {})}
- {...(onAdvance ? { onAdvance } : {})}
+ step={step}
+ onStepChange={onStepChange}
+ onSelectOption={onSelectOption}
+ onAnswerWithText={onAnswerWithText}
+ surface={surface}
+ {...(onSubmit ? { onSubmit } : {})}
/>
);
});
-const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
+function isTypingTarget(target: EventTarget | null) {
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return true;
+
+ return (
+ target instanceof HTMLElement &&
+ target.closest('[contenteditable]:not([contenteditable="false"])') !== null
+ );
+}
+
+/** Enter on a focused link, button, or field belongs to that control, not to the card. */
+function isInteractiveTarget(target: EventTarget | null) {
+ return (
+ target instanceof Element &&
+ target.closest(
+ 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="tab"]',
+ ) !== null
+ );
+}
+
+function PendingUserInputCard({
prompt,
isResponding,
answers,
- questionIndex,
- onToggleOption,
- onSelectSingleOption,
- onAdvance,
- className,
+ step: requestedStep,
+ onStepChange,
+ onSelectOption,
+ onAnswerWithText,
+ onSubmit,
+ surface,
}: {
prompt: PendingUserInput;
isResponding: boolean;
answers: Record<string, PendingUserInputDraftAnswer>;
- questionIndex: number;
- onToggleOption: (questionId: string, optionLabel: string) => void;
- onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
- onAdvance?: () => void;
- className?: string;
+ step: number;
+ onStepChange: (step: number) => void;
+ onSelectOption: (questionId: string, optionLabel: string) => void;
+ onAnswerWithText: (text: string) => void;
+ onSubmit?: () => void;
+ surface: "card" | "docked";
}) {
const { t } = useI18n();
- const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
- const activeQuestion = progress.activeQuestion;
- const autoAdvanceTimerRef = useRef<number | null>(null);
-
- const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
- questionId: string;
- optionLabel: string;
- } | null>(null);
-
- useEffect(
- () => () => {
- if (autoAdvanceTimerRef.current !== null) {
- window.clearTimeout(autoAdvanceTimerRef.current);
- }
- },
- [],
- );
-
- useEffect(() => {
- if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
- return;
- }
+ const { questions } = prompt;
+ const step = Math.min(Math.max(requestedStep, 0), questions.length - 1);
+ const question = questions[step];
+ const isLastStep = step === questions.length - 1;
+ const complete = buildPendingUserInputAnswers(questions, answers) !== null;
- if (optimisticSingleSelect.questionId !== activeQuestion.id) {
- setOptimisticSingleSelect(null);
+ const stepAnswered = question
+ ? resolvePendingUserInputAnswer(question, answers[question.id])
+ : null;
- return;
- }
+ const sendsOnClick = questions.length === 1 && question?.multiSelect === false;
- if (
- progress.customAnswer.trim().length === 0 &&
- progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel)
- ) {
- setOptimisticSingleSelect(null);
- }
- }, [
- activeQuestion,
- optimisticSingleSelect,
- progress.customAnswer,
- progress.selectedOptionLabels,
- ]);
+ // Back slides the previous question in from the left; every other move comes from the right.
+ const [shown, setShown] = useState({ step, direction: "forward" });
+ const ownAnswerRef = useRef<HTMLInputElement>(null);
+ const cardRef = useRef<HTMLElement>(null);
- const handleOptionSelection = useCallback(
- (questionId: string, optionLabel: string) => {
- if (activeQuestion?.multiSelect) {
- onToggleOption(questionId, optionLabel);
+ if (shown.step !== step) setShown({ step, direction: step < shown.step ? "back" : "forward" });
- return;
- }
-
- setOptimisticSingleSelect({ questionId, optionLabel });
-
- if (onSelectSingleOption) {
- onSelectSingleOption(questionId, optionLabel);
-
- return;
- }
-
- onToggleOption(questionId, optionLabel);
-
- if (onAdvance) {
- if (autoAdvanceTimerRef.current !== null) {
- window.clearTimeout(autoAdvanceTimerRef.current);
- }
-
- autoAdvanceTimerRef.current = window.setTimeout(() => {
- autoAdvanceTimerRef.current = null;
- onAdvance();
- }, 200);
- }
- },
- [activeQuestion, onAdvance, onSelectSingleOption, onToggleOption],
- );
+ const primary = sendsOnClick
+ ? null
+ : isLastStep
+ ? { label: t("Submit"), enabled: complete && onSubmit !== undefined, run: () => onSubmit?.() }
+ : { label: t("Next"), enabled: stepAnswered !== null, run: () => onStepChange(step + 1) };
useEffect(() => {
- if (!activeQuestion || isResponding) return;
+ if (!question || isResponding) return;
const handler = (event: globalThis.KeyboardEvent) => {
- if (event.metaKey || event.ctrlKey || event.altKey) return;
- const target = event.target;
+ if (event.metaKey || event.ctrlKey || event.altKey || isTypingTarget(event.target)) return;
- if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
- return;
- }
+ if (event.key === "Enter") {
+ if (event.defaultPrevented || isInteractiveTarget(event.target) || !primary?.enabled) {
+ return;
+ }
+
+ event.preventDefault();
+ primary.run();
- if (
- target instanceof HTMLElement &&
- target.closest('[contenteditable]:not([contenteditable="false"])')
- ) {
return;
}
- const normalizedKey = event.key.toLocaleLowerCase();
+ // A key pressed on some other control on the page belongs to that control.
+ const target = event.target instanceof Node ? event.target : null;
- const optionIndex = /^[1-9]$/.test(normalizedKey)
- ? Number.parseInt(normalizedKey, 10) - 1
- : /^[a-i]$/.test(normalizedKey)
- ? normalizedKey.charCodeAt(0) - 97
- : -1;
+ if (isInteractiveTarget(event.target) && !cardRef.current?.contains(target)) return;
- if (optionIndex < 0) return;
+ const action = pendingUserInputKeyAction(event.key, question.options.length);
+ const option = action?.kind === "pick" ? question.options[action.optionIndex] : undefined;
- if (optionIndex >= activeQuestion.options.length) return;
- const option = activeQuestion.options[optionIndex];
-
- if (!option) return;
- event.preventDefault();
- handleOptionSelection(activeQuestion.id, option.label);
+ if (option) {
+ event.preventDefault();
+ onSelectOption(question.id, option.label);
+ } else if (action?.kind === "type") {
+ // Focus moves before the character lands, so it starts the typed answer.
+ ownAnswerRef.current?.focus();
+ }
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
- }, [activeQuestion, handleOptionSelection, isResponding]);
-
- if (!activeQuestion) {
- return null;
- }
-
- const customAnswerActive = progress.customAnswer.trim().length > 0;
+ }, [question, isResponding, onSelectOption, primary]);
+
+ if (!question) return null;
+
+ const body = (
+ <div className="flex flex-col gap-3.5 px-4 pt-3.5 pb-3.5">
+ {questions.length > 1 ? (
+ <div className="flex items-center gap-3">
+ <div className="flex flex-1 gap-1" aria-hidden="true">
+ {questions.map((entry, index) => (
+ <span
+ key={entry.id}
+ className="gen-step h-1 flex-1 rounded-full"
+ data-state={
+ index === step
+ ? "current"
+ : resolvePendingUserInputAnswer(entry, answers[entry.id])
+ ? "done"
+ : "todo"
+ }
+ />
+ ))}
+ </div>
+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
+ {t("{step} of {total}", { step: String(step + 1), total: String(questions.length) })}
+ </span>
+ </div>
+ ) : null}
+ <div
+ key={question.id}
+ className={shown.direction === "back" ? "motion-page-back" : "motion-page-forward"}
+ >
+ <PendingQuestion
+ question={question}
+ draft={answers[question.id]}
+ disabled={isResponding}
+ onSelectOption={onSelectOption}
+ onAnswerWithText={onAnswerWithText}
+ ownAnswerRef={ownAnswerRef}
+ />
+ </div>
+ <div className="flex items-center gap-3">
+ {step > 0 ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={isResponding}
+ onClick={() => onStepChange(step - 1)}
+ >
+ <ChevronLeftIcon />
+ {t("Back")}
+ </Button>
+ ) : null}
+ <span className="flex-1" />
+ {primary ? (
+ <Button size="sm" disabled={isResponding || !primary.enabled} onClick={primary.run}>
+ {primary.label}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
return (
<section
- aria-label={activeQuestion.question}
- className={cn(
- "w-full max-w-2xl rounded-2xl border border-border bg-foreground/5 p-3",
- className,
- )}
+ ref={cardRef}
+ aria-label={question.question}
+ className="chat-generative w-full max-w-2xl"
+ data-generative="question"
data-testid="pending-user-input-card"
>
- <div className="flex items-start gap-3">
- <p className="min-w-0 flex-1 text-15px font-medium leading-6 text-foreground">
- {activeQuestion.question}
- </p>
- {prompt.questions.length > 1 ? (
- <span className="mt-1 shrink-0 text-11px text-muted-foreground tabular-nums">
- {questionIndex + 1}/{prompt.questions.length}
- </span>
- ) : null}
- </div>
- {activeQuestion.multiSelect ? (
- <p className="mt-1 text-xs text-muted-foreground">{t("Select one or more.")}</p>
- ) : null}
- <div className="mt-3 overflow-hidden rounded-xl border border-border/80 bg-background/25 divide-y divide-border/70">
- {activeQuestion.options.map((option, index) => {
- const isOptimisticallySelected =
- optimisticSingleSelect?.questionId === activeQuestion.id &&
- optimisticSingleSelect.optionLabel === option.label;
-
- const isSelected =
- isOptimisticallySelected ||
- (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
-
- const shortcutKey = index < 9 ? String.fromCharCode(65 + index) : null;
-
- const className = cn(
- "group flex min-h-12 w-full items-center gap-3 px-3 py-2.5 text-left outline-none transition-colors duration-150 focus-visible:relative focus-visible:z-10 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/35",
- isSelected
- ? "bg-muted/70 text-foreground"
- : "bg-transparent text-foreground/90 hover:bg-muted/35",
- isResponding && "opacity-50 cursor-not-allowed",
- !isResponding && "cursor-pointer",
- );
+ {surface === "card" ? <Card>{body}</Card> : body}
+ </section>
+ );
+}
- const content = (
- <>
- {shortcutKey !== null ? (
- <kbd className="flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-muted/70 text-11px font-medium text-muted-foreground">
- {shortcutKey}
- </kbd>
- ) : null}
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span className="text-sm font-medium">{option.label}</span>
- {option.description && option.description !== option.label ? (
- <span className="text-secondary-label text-11px">{option.description}</span>
- ) : null}
- </div>
- {isSelected ? <CheckIcon className="size-3.5 shrink-0 text-primary" /> : null}
- </>
- );
+function PendingQuestion({
+ question,
+ draft,
+ disabled,
+ onSelectOption,
+ onAnswerWithText,
+ ownAnswerRef,
+}: {
+ question: UserInputQuestion;
+ draft: PendingUserInputDraftAnswer | undefined;
+ disabled: boolean;
+ onSelectOption: (questionId: string, optionLabel: string) => void;
+ onAnswerWithText: (text: string) => void;
+ ownAnswerRef: RefObject<HTMLInputElement | null>;
+}) {
+ const { t } = useI18n();
+ const customAnswer = draft?.customAnswer?.trim() ?? "";
+ const resolved = resolvePendingUserInputAnswer(question, draft);
+ const selectedLabels = customAnswer ? [] : [resolved ?? []].flat();
- return (
- <button
- key={`${activeQuestion.id}:${option.label}`}
- type="button"
- aria-pressed={isSelected}
- disabled={isResponding}
- onClick={() => {
- handleOptionSelection(activeQuestion.id, option.label);
- }}
- className={className}
- >
- {content}
- </button>
- );
- })}
+ return (
+ <div className="flex flex-col gap-2.5">
+ <div className="flex flex-col gap-0.5">
+ {question.header && question.header !== question.question ? (
+ <span className="text-xs font-medium text-muted-foreground">{question.header}</span>
+ ) : null}
+ <span className="text-sm font-semibold text-foreground">{question.question}</span>
+ {question.multiSelect ? (
+ <span className="text-xs text-muted-foreground">{t("Pick any that apply.")}</span>
+ ) : null}
</div>
- {activeQuestion.multiSelect && onAdvance ? (
- <div className="mt-3 flex justify-end">
- <Button
- size="xs"
- disabled={isResponding || progress.selectedOptionLabels.length === 0}
- onClick={onAdvance}
+ <div
+ className="gen-choices flex flex-col gap-2"
+ data-answered={!question.multiSelect && resolved !== null}
+ >
+ {question.options.map((option, index) => (
+ <ChoiceButton
+ key={option.label}
+ kind={question.multiSelect ? "checkbox" : "radio"}
+ pressed={selectedLabels.includes(option.label)}
+ disabled={disabled}
+ shortcut={index < 9 ? String(index + 1) : null}
+ onClick={() => onSelectOption(question.id, option.label)}
>
- {questionIndex < prompt.questions.length - 1 ? t("Continue") : t("Submit")}
- </Button>
- </div>
- ) : null}
- </section>
+ <span className="text-sm font-medium text-foreground">{option.label}</span>
+ {option.description && option.description !== option.label ? (
+ <span className="text-xs text-muted-foreground">{option.description}</span>
+ ) : null}
+ </ChoiceButton>
+ ))}
+ <OwnAnswerRow
+ kind={question.multiSelect ? "checkbox" : "radio"}
+ answer={customAnswer}
+ disabled={disabled}
+ inputRef={ownAnswerRef}
+ onAnswer={onAnswerWithText}
+ />
+ </div>
+ </div>
);
-});
+}
diff --git a/apps/web/src/components/chat/PendingUserInputChoices.tsx b/apps/web/src/components/chat/PendingUserInputChoices.tsx
new file mode 100644
index 000000000..070dc6a65
--- /dev/null
+++ b/apps/web/src/components/chat/PendingUserInputChoices.tsx
@@ -0,0 +1,136 @@
+import { CheckIcon, CornerDownLeftIcon, PencilLineIcon } from "lucide-react";
+import { useState, type ReactNode, type RefObject } from "react";
+import { useI18n } from "~/i18n";
+import { cn } from "~/lib/utils";
+import { Kbd } from "../ui/kbd";
+
+/** Single-choice questions show a radio mark; multi-select questions show a checkbox. */
+export type ChoiceKind = "radio" | "checkbox";
+
+/** The selection mark at the start of a choice row. Purely visual; the row carries the state. */
+function ChoiceMark({
+ kind,
+ checked,
+ className,
+}: {
+ kind: ChoiceKind;
+ checked: boolean;
+ className?: string;
+}) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn("gen-mark", className)}
+ data-kind={kind}
+ data-checked={checked ? "true" : undefined}
+ >
+ {kind === "checkbox" ? (
+ <CheckIcon className="gen-mark-tick" strokeWidth={3} />
+ ) : (
+ <span className="gen-mark-dot" />
+ )}
+ </span>
+ );
+}
+
+/** The number key that picks this row. Hidden on touch screens, where there is no keyboard. */
+function ShortcutHint({ shortcut }: { shortcut: string }) {
+ return <Kbd className="mt-0.5 shrink-0 pointer-coarse:hidden">{shortcut}</Kbd>;
+}
+
+export function ChoiceButton({
+ kind,
+ pressed,
+ disabled,
+ shortcut,
+ onClick,
+ children,
+}: {
+ kind: ChoiceKind;
+ pressed: boolean;
+ disabled: boolean;
+ shortcut: string | null;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ className="gen-choice flex w-full items-start gap-3 rounded-xl border border-border bg-background px-3 py-2.5 text-left transition-colors enabled:hover:bg-accent disabled:cursor-default"
+ aria-pressed={pressed}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <ChoiceMark kind={kind} checked={pressed} className="mt-0.5" />
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">{children}</span>
+ {shortcut ? <ShortcutHint shortcut={shortcut} /> : null}
+ </button>
+ );
+}
+
+/**
+ * The last row takes a typed answer in place, styled like the options above it. Enter answers
+ * the question on screen; a reply sent from the composer lands here too.
+ */
+export function OwnAnswerRow({
+ kind,
+ answer,
+ disabled,
+ inputRef,
+ onAnswer,
+}: {
+ kind: ChoiceKind;
+ answer: string;
+ disabled: boolean;
+ inputRef: RefObject<HTMLInputElement | null>;
+ onAnswer: (text: string) => void;
+}) {
+ const { t } = useI18n();
+ const [text, setText] = useState(answer);
+ const [shownAnswer, setShownAnswer] = useState(answer);
+
+ // An answer sent from the composer replaces whatever is in the row.
+ if (shownAnswer !== answer) {
+ setShownAnswer(answer);
+ setText(answer);
+ }
+
+ const trimmed = text.trim();
+ const answered = answer !== "" && trimmed === answer;
+
+ return (
+ <label
+ className={cn(
+ "gen-choice flex w-full items-center gap-3 rounded-xl border border-border bg-background px-3 py-2.5 transition-colors focus-within:border-solid has-focus-visible:ring-2 has-focus-visible:ring-ring",
+ !trimmed && "border-dashed",
+ )}
+ data-selected={answered ? "true" : undefined}
+ >
+ {answered ? (
+ <ChoiceMark kind={kind} checked />
+ ) : (
+ <PencilLineIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
+ )}
+ <input
+ ref={inputRef}
+ type="text"
+ className="min-w-0 flex-1 bg-transparent text-sm font-medium text-foreground outline-none placeholder:font-normal placeholder:text-muted-foreground"
+ placeholder={t("Type your own answer")}
+ aria-label={t("Type your own answer")}
+ value={text}
+ disabled={disabled}
+ onChange={(event) => setText(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter" || event.nativeEvent.isComposing || !trimmed) return;
+ event.preventDefault();
+ onAnswer(trimmed);
+ }}
+ />
+ {trimmed && !answered ? (
+ <Kbd className="shrink-0">
+ <CornerDownLeftIcon />
+ </Kbd>
+ ) : null}
+ </label>
+ );
+}
diff --git a/apps/web/src/components/chat/UserInputAnswerCard.test.tsx b/apps/web/src/components/chat/UserInputAnswerCard.test.tsx
new file mode 100644
index 000000000..b75142b27
--- /dev/null
+++ b/apps/web/src/components/chat/UserInputAnswerCard.test.tsx
@@ -0,0 +1,58 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vite-plus/test";
+
+import { UserInputAnswerCard } from "./UserInputAnswerCard";
+
+const scope = {
+ id: "scope",
+ header: "Scope",
+ question: "Which suites should I touch?",
+ multiSelect: true,
+ options: [
+ { label: "Server", description: "Reaper tests" },
+ { label: "Web", description: "Reconnect tests" },
+ { label: "Mobile", description: "Session restore tests" },
+ ],
+};
+
+const fix = {
+ id: "fix",
+ header: "Fix",
+ question: "How should I fix the reaper tests?",
+ multiSelect: false,
+ options: [
+ { label: "Wait on receipts", description: "Replace the sleeps" },
+ { label: "Raise the timeout", description: "Keeps the race" },
+ ],
+};
+
+describe("UserInputAnswerCard", () => {
+ it("lists multi-select picks in the order the bot offered them", () => {
+ const markup = renderToStaticMarkup(
+ <UserInputAnswerCard answered={[{ question: scope, answers: ["Mobile", "Server"] }]} />,
+ );
+
+ expect(markup.indexOf("Server")).toBeLessThan(markup.indexOf("Mobile"));
+ expect(
+ renderToStaticMarkup(
+ <UserInputAnswerCard answered={[{ question: scope, answers: ["Server", "Server"] }]} />,
+ ).match(/>Server</g),
+ ).toHaveLength(1);
+ expect(markup).toContain("Answered");
+ });
+
+ it("marks a typed answer with a pencil and leaves a single pick plain", () => {
+ const typed = renderToStaticMarkup(
+ <UserInputAnswerCard answered={[{ question: fix, answers: ["Receipts, then delete"] }]} />,
+ );
+
+ const picked = renderToStaticMarkup(
+ <UserInputAnswerCard answered={[{ question: fix, answers: ["Wait on receipts"] }]} />,
+ );
+
+ expect(typed).toContain("lucide-pencil-line");
+ expect(picked).not.toContain("lucide-pencil-line");
+ // Only the header badge carries a check; a single pick reads as plain text.
+ expect(picked.match(/lucide-check\b/g)).toHaveLength(1);
+ });
+});
diff --git a/apps/web/src/components/chat/UserInputAnswerCard.tsx b/apps/web/src/components/chat/UserInputAnswerCard.tsx
new file mode 100644
index 000000000..afe82bae0
--- /dev/null
+++ b/apps/web/src/components/chat/UserInputAnswerCard.tsx
@@ -0,0 +1,76 @@
+import type { AnsweredUserInputQuestion } from "@akeru/client-runtime/user-input-answers";
+import { CheckIcon, PencilLineIcon } from "lucide-react";
+import { useI18n } from "~/i18n";
+
+/**
+ * A submitted answer to a bot's questions, read back as a short summary: one divided row per
+ * question with what was picked. Multi-select picks list one per line, and an answer typed in
+ * place of the options is marked with a pencil.
+ */
+export function UserInputAnswerCard({
+ answered,
+}: {
+ readonly answered: ReadonlyArray<AnsweredUserInputQuestion>;
+}) {
+ const { t } = useI18n();
+
+ return (
+ <div
+ className="chat-generative flex w-72 max-w-full flex-col overflow-hidden rounded-2xl border border-border bg-card"
+ data-generative="answer"
+ data-testid="user-input-answer-card"
+ >
+ <div className="flex items-center gap-2 border-b border-border px-3.5 py-2 text-xs font-medium text-muted-foreground">
+ <span className="gen-answer-badge">
+ <CheckIcon className="size-2.5" strokeWidth={3} />
+ </span>
+ {answered.length === 1
+ ? t("Answered")
+ : t("Answered {count} questions", { count: String(answered.length) })}
+ </div>
+ <dl className="flex flex-col divide-y divide-border">
+ {answered.map(({ question, answers }) => {
+ const optionOrder = question.options.map((option) => option.label);
+ const optionLabels = new Set(optionOrder);
+
+ // Picks read in the order the bot offered them; typed answers come last.
+ const rank = (answer: string) =>
+ optionLabels.has(answer) ? optionOrder.indexOf(answer) : optionOrder.length;
+
+ return (
+ <div key={question.id} className="flex flex-col gap-1 px-3.5 py-2.5">
+ <dt className="text-xs text-muted-foreground">
+ {question.header && question.header !== question.question
+ ? question.header
+ : question.question}
+ </dt>
+ {[...new Set(answers)]
+ .toSorted((left, right) => rank(left) - rank(right))
+ .map((answer) => (
+ <dd
+ key={answer}
+ className="flex items-start gap-2 text-sm font-medium text-foreground"
+ >
+ {optionLabels.has(answer) ? (
+ question.multiSelect ? (
+ <CheckIcon
+ aria-hidden="true"
+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"
+ />
+ ) : null
+ ) : (
+ <PencilLineIcon
+ aria-hidden="true"
+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"
+ />
+ )}
+ <span className="min-w-0 break-words">{answer}</span>
+ </dd>
+ ))}
+ </div>
+ );
+ })}
+ </dl>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/computer/OpenComputerAction.tsx b/apps/web/src/components/computer/OpenComputerAction.tsx
deleted file mode 100644
index dcda14912..000000000
--- a/apps/web/src/components/computer/OpenComputerAction.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { ComputerIcon } from "@hugeicons/core-free-icons";
-import type { ScopedThreadRef } from "@akeru/contracts";
-
-import { openComputerViewer } from "../../computerViewerStore";
-import { useI18n } from "../../i18n";
-import type { Bot } from "../roster/types";
-import { AppIcon } from "../ui/app-icon";
-import { Button } from "../ui/button";
-
-/** Opens the bot's computer beside a request for human input, when the chat has a thread. */
-export function OpenComputerAction({
- threadRef,
- bot,
-}: {
- readonly threadRef: ScopedThreadRef | null;
- readonly bot: Pick<Bot, "name" | "sandbox" | "engine">;
-}) {
- const { t } = useI18n();
-
- if (threadRef === null) return null;
-
- return (
- <Button
- size="xs"
- variant="ghost"
- data-open-computer=""
- onClick={() =>
- openComputerViewer({
- threadRef,
- botName: bot.name,
- sandbox: bot.sandbox,
- engine: bot.engine,
- })
- }
- >
- <AppIcon className="size-3.5" icon={ComputerIcon} />
- {t("Open {name}'s computer", { name: bot.name })}
- </Button>
- );
-}
diff --git a/apps/web/src/components/markdown/generative/GenerativeBlock.tsx b/apps/web/src/components/markdown/generative/GenerativeBlock.tsx
new file mode 100644
index 000000000..6a06b6ee2
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeBlock.tsx
@@ -0,0 +1,24 @@
+import type { GenerativeBlockSpec } from "./generativeSchemas";
+import { GenerativeChart } from "./GenerativeChart";
+import { GenerativeChoices } from "./GenerativeChoices";
+import { GenerativeFlow } from "./GenerativeFlow";
+import { GenerativeStats } from "./GenerativeStats";
+import { GenerativeTasks } from "./GenerativeTasks";
+import { GenerativeTimeline } from "./GenerativeTimeline";
+
+export function GenerativeBlock({ block }: { readonly block: GenerativeBlockSpec }) {
+ switch (block.kind) {
+ case "chart":
+ return <GenerativeChart spec={block.spec} />;
+ case "stats":
+ return <GenerativeStats spec={block.spec} />;
+ case "tasks":
+ return <GenerativeTasks spec={block.spec} />;
+ case "flow":
+ return <GenerativeFlow spec={block.spec} />;
+ case "choices":
+ return <GenerativeChoices spec={block.spec} />;
+ case "timeline":
+ return <GenerativeTimeline spec={block.spec} />;
+ }
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeChart.tsx b/apps/web/src/components/markdown/generative/GenerativeChart.tsx
new file mode 100644
index 000000000..204d8166c
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeChart.tsx
@@ -0,0 +1,269 @@
+import { useState, type PointerEvent } from "react";
+import type { ChartSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+const PLOT_WIDTH = 600;
+
+const PLOT_HEIGHT = 160;
+
+const MAX_SERIES = 4;
+
+function niceMax(value: number): number {
+ if (value <= 0) return 1;
+ const magnitude = 10 ** Math.floor(Math.log10(value));
+ const step = [1, 2, 2.5, 5, 10].find((candidate) => candidate * magnitude >= value) ?? 10;
+
+ return step * magnitude;
+}
+
+export function formatChartValue(value: number, unit: string | undefined): string {
+ const rounded = Math.abs(value) >= 100 ? Math.round(value) : Math.round(value * 10) / 10;
+ const text = rounded.toLocaleString();
+
+ if (!unit) return text;
+
+ return unit === "%" || unit === "s" || unit === "ms" ? `${text}${unit}` : `${text} ${unit}`;
+}
+
+function linePath(values: ReadonlyArray<number>, max: number, count: number): string {
+ return values
+ .map((value, index) => {
+ const x = count <= 1 ? 0 : (index / (count - 1)) * PLOT_WIDTH;
+ const y = PLOT_HEIGHT - (value / max) * PLOT_HEIGHT;
+
+ return `${index === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`;
+ })
+ .join(" ");
+}
+
+function ChartLegend({ spec }: { readonly spec: ChartSpec }) {
+ if (spec.series.length < 2) return null;
+
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {spec.series.slice(0, MAX_SERIES).map((series, index) => (
+ <span
+ key={series.name}
+ className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"
+ data-series={index}
+ >
+ <span className="gen-swatch size-2 rounded-full" />
+ {series.name}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function ChartTooltip({ spec, index }: { readonly spec: ChartSpec; readonly index: number }) {
+ return (
+ <div className="flex flex-col gap-0.5 rounded-md border border-border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-md">
+ <div className="font-medium">{spec.x[index]}</div>
+ {spec.series.slice(0, MAX_SERIES).map((series, seriesIndex) => (
+ <div
+ key={series.name}
+ className="flex items-center justify-between gap-4"
+ data-series={seriesIndex}
+ >
+ <span className="inline-flex items-center gap-1.5 text-muted-foreground">
+ <span className="gen-swatch size-1.5 rounded-full" />
+ {series.name}
+ </span>
+ <span className="font-mono tabular-nums">
+ {formatChartValue(series.values[index] ?? 0, spec.unit)}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function XAxis({ labels }: { readonly labels: ReadonlyArray<string> }) {
+ // Long axes show every other label so they never collide in a chat column.
+ const stride = labels.length > 8 ? Math.ceil(labels.length / 6) : 1;
+
+ return (
+ <div className="mt-1.5 flex justify-between text-10px text-muted-foreground tabular-nums">
+ {labels.map((label, index) => (
+ <span key={label} className={index % stride === 0 ? "" : "invisible"}>
+ {label}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function LineChart({ spec, max }: { readonly spec: ChartSpec; readonly max: number }) {
+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);
+ const count = spec.x.length;
+
+ const handlePointer = (event: PointerEvent<HTMLDivElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const ratio = (event.clientX - bounds.left) / bounds.width;
+ setHoverIndex(Math.min(count - 1, Math.max(0, Math.round(ratio * (count - 1)))));
+ };
+
+ const hoverLeft = hoverIndex === null || count <= 1 ? 0 : (hoverIndex / (count - 1)) * 100;
+
+ return (
+ <div>
+ <div
+ className="relative h-40"
+ onPointerMove={handlePointer}
+ onPointerLeave={() => setHoverIndex(null)}
+ >
+ <svg
+ className="absolute inset-0 size-full overflow-visible"
+ viewBox={`0 0 ${PLOT_WIDTH} ${PLOT_HEIGHT}`}
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ >
+ {[0, 0.5, 1].map((fraction) => (
+ <line
+ key={fraction}
+ className="gen-gridline"
+ x1={0}
+ x2={PLOT_WIDTH}
+ y1={PLOT_HEIGHT * fraction}
+ y2={PLOT_HEIGHT * fraction}
+ />
+ ))}
+ {spec.series.slice(0, MAX_SERIES).map((series, index) => {
+ const path = linePath(series.values, max, count);
+
+ return (
+ <g key={series.name} data-series={index}>
+ {spec.type === "area" ? (
+ <path
+ className="gen-area"
+ d={`${path} L${PLOT_WIDTH},${PLOT_HEIGHT} L0,${PLOT_HEIGHT} Z`}
+ />
+ ) : null}
+ <path className="gen-line" d={path} />
+ </g>
+ );
+ })}
+ </svg>
+ <span className="absolute top-0 left-0 -translate-y-1/2 bg-card pr-1 text-10px text-muted-foreground tabular-nums">
+ {formatChartValue(max, spec.unit)}
+ </span>
+ {hoverIndex !== null ? (
+ <>
+ <div
+ className="gen-crosshair pointer-events-none absolute inset-y-0 left-(--gen-x) w-px"
+ style={{ "--gen-x": `${hoverLeft}%` }}
+ />
+ <div
+ className={
+ hoverLeft > 60
+ ? "pointer-events-none absolute top-1 right-(--gen-x-end) z-10 mr-2"
+ : "pointer-events-none absolute top-1 left-(--gen-x) z-10 ml-2"
+ }
+ style={{ "--gen-x": `${hoverLeft}%`, "--gen-x-end": `${100 - hoverLeft}%` }}
+ >
+ <ChartTooltip spec={spec} index={hoverIndex} />
+ </div>
+ </>
+ ) : null}
+ </div>
+ <XAxis labels={spec.x} />
+ </div>
+ );
+}
+
+function BarChart({ spec, max }: { readonly spec: ChartSpec; readonly max: number }) {
+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);
+ const series = spec.series.slice(0, MAX_SERIES);
+
+ return (
+ <div>
+ <div className="relative flex h-40 items-end gap-2 border-b border-border/70">
+ <span className="absolute top-0 left-0 -translate-y-1/2 bg-card pr-1 text-10px text-muted-foreground tabular-nums">
+ {formatChartValue(max, spec.unit)}
+ </span>
+ {spec.x.map((label, index) => (
+ <div
+ key={label}
+ className="relative flex h-full flex-1 items-end justify-center gap-0.5"
+ onPointerEnter={() => setHoverIndex(index)}
+ onPointerLeave={() => setHoverIndex(null)}
+ >
+ {series.map((entry, seriesIndex) => (
+ <div
+ key={entry.name}
+ className="gen-bar h-(--gen-h) w-full max-w-7 data-[dim=true]:opacity-45"
+ data-series={seriesIndex}
+ data-dim={hoverIndex !== null && hoverIndex !== index}
+ style={{ "--gen-h": `${((entry.values[index] ?? 0) / max) * 100}%` }}
+ />
+ ))}
+ {hoverIndex === index ? (
+ <div className="pointer-events-none absolute bottom-full z-10 mb-1">
+ <ChartTooltip spec={spec} index={index} />
+ </div>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ <div className="mt-1.5 flex gap-2 text-10px text-muted-foreground">
+ {spec.x.map((label) => (
+ <span key={label} className="flex-1 truncate text-center">
+ {label}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** The chart's numbers as a table for screen readers; the drawing itself is hidden from them. */
+function ChartDataTable({ spec }: { readonly spec: ChartSpec }) {
+ return (
+ <table className="sr-only">
+ {spec.title ? <caption>{spec.title}</caption> : null}
+ <thead>
+ <tr>
+ <th scope="col" />
+ {spec.series.map((series) => (
+ <th key={series.name} scope="col">
+ {series.name}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {spec.x.map((label, index) => (
+ <tr key={label}>
+ <th scope="row">{label}</th>
+ {spec.series.map((series) => (
+ <td key={series.name}>{formatChartValue(series.values[index] ?? 0, spec.unit)}</td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
+
+export function GenerativeChart({ spec }: { readonly spec: ChartSpec }) {
+ const peak = Math.max(0, ...spec.series.flatMap((series) => series.values));
+ const max = niceMax(peak);
+
+ return (
+ <GenerativeFrame
+ kind="chart"
+ title={spec.title}
+ subtitle={spec.subtitle}
+ aside={<ChartLegend spec={spec} />}
+ >
+ <div aria-hidden="true">
+ {spec.type === "bar" ? (
+ <BarChart spec={spec} max={max} />
+ ) : (
+ <LineChart spec={spec} max={max} />
+ )}
+ </div>
+ <ChartDataTable spec={spec} />
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeChoices.tsx b/apps/web/src/components/markdown/generative/GenerativeChoices.tsx
new file mode 100644
index 000000000..29c924e96
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeChoices.tsx
@@ -0,0 +1,65 @@
+import { use, useState } from "react";
+import { useI18n } from "../../../i18n";
+import { Badge } from "../../ui/badge";
+import { ChatReplyContext } from "./chatReplyContext";
+import type { ChoicesSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+/**
+ * Option cards. In bot and group chats a click sends the option's reply right away.
+ * Where there is no chat to reply into, such as a delegated bot's read-only work view,
+ * the options are shown but cannot be picked.
+ */
+export function GenerativeChoices({ spec }: { readonly spec: ChoicesSpec }) {
+ const { t } = useI18n();
+ const reply = use(ChatReplyContext);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [sending, setSending] = useState(false);
+ const answered = reply !== null && selected !== null && !sending;
+
+ const choose = async (option: ChoicesSpec["options"][number]) => {
+ if (!reply) return;
+
+ setSelected(option.label);
+ setSending(true);
+ const sent = await reply.send(option.reply);
+ setSending(false);
+
+ if (!sent) setSelected(null);
+ };
+
+ const locked = reply === null || reply.disabled || sending || answered;
+
+ return (
+ <GenerativeFrame kind="choices" title={spec.question}>
+ <div
+ className="gen-choices flex flex-col gap-2"
+ data-answered={selected !== null}
+ data-unavailable={locked && selected === null}
+ >
+ {spec.options.map((option) => (
+ <button
+ key={option.label}
+ type="button"
+ className="gen-choice flex w-full items-start justify-between gap-3 rounded-xl border border-border bg-background px-3 py-2.5 text-left transition-colors enabled:hover:bg-accent disabled:cursor-default"
+ aria-pressed={selected === option.label}
+ disabled={locked}
+ onClick={() => void choose(option)}
+ >
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-sm font-medium text-foreground">{option.label}</span>
+ {option.detail ? (
+ <span className="text-xs text-muted-foreground">{option.detail}</span>
+ ) : null}
+ </span>
+ {option.recommended ? (
+ <Badge variant="secondary" className="shrink-0">
+ {t("Recommended")}
+ </Badge>
+ ) : null}
+ </button>
+ ))}
+ </div>
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeFlow.tsx b/apps/web/src/components/markdown/generative/GenerativeFlow.tsx
new file mode 100644
index 000000000..37e679590
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeFlow.tsx
@@ -0,0 +1,167 @@
+import type { FlowSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+// Node size matches the w-32 h-13.5 classes on each node box.
+const NODE_WIDTH = 128;
+
+const NODE_HEIGHT = 54;
+
+const COLUMN_GAP = 44;
+
+const ROW_GAP = 14;
+
+interface PlacedNode {
+ readonly node: FlowSpec["nodes"][number];
+ readonly x: number;
+ readonly y: number;
+}
+
+/**
+ * Ranks nodes left to right by longest incoming path; cycles stop at the first revisit.
+ * Entry nodes then move right to sit just before their nearest child, so edges never skip a column.
+ */
+export function layoutFlow(spec: FlowSpec) {
+ const ids = new Set(spec.nodes.map((node) => node.id));
+ const edges = spec.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to));
+ const rank = new Map<string, number>();
+
+ const rankOf = (id: string, visiting: Set<string>): number => {
+ const known = rank.get(id);
+
+ if (known !== undefined) return known;
+
+ if (visiting.has(id)) return 0;
+ visiting.add(id);
+ const parents = edges.filter((edge) => edge.to === id).map((edge) => edge.from);
+
+ const value =
+ parents.length === 0 ? 0 : Math.max(...parents.map((p) => rankOf(p, visiting) + 1));
+
+ visiting.delete(id);
+ rank.set(id, value);
+
+ return value;
+ };
+
+ for (const node of spec.nodes) rankOf(node.id, new Set());
+
+ for (const node of spec.nodes) {
+ const isEntry = !edges.some((edge) => edge.to === node.id);
+
+ const childRanks = edges
+ .filter((edge) => edge.from === node.id)
+ .map((edge) => rank.get(edge.to) ?? 0);
+
+ if (isEntry && childRanks.length > 0)
+ rank.set(node.id, Math.max(0, Math.min(...childRanks) - 1));
+ }
+
+ const columns: Array<Array<FlowSpec["nodes"][number]>> = [];
+
+ for (const node of spec.nodes) {
+ (columns[rank.get(node.id) ?? 0] ??= []).push(node);
+ }
+
+ // Ranks can skip a column (a cycle never reaches rank 0), so read holes as empty columns.
+ const tallest = Math.max(...Array.from(columns, (column) => column?.length ?? 0));
+ const height = tallest * NODE_HEIGHT + (tallest - 1) * ROW_GAP;
+ const placed = new Map<string, PlacedNode>();
+
+ columns.forEach((column, columnIndex) => {
+ if (!column) return;
+ const columnHeight = column.length * NODE_HEIGHT + (column.length - 1) * ROW_GAP;
+ const top = (height - columnHeight) / 2;
+ column.forEach((node, rowIndex) => {
+ placed.set(node.id, {
+ node,
+ x: columnIndex * (NODE_WIDTH + COLUMN_GAP),
+ y: top + rowIndex * (NODE_HEIGHT + ROW_GAP),
+ });
+ });
+ });
+
+ const width = columns.length * NODE_WIDTH + (columns.length - 1) * COLUMN_GAP;
+
+ return { placed, edges, width, height };
+}
+
+export function GenerativeFlow({ spec }: { readonly spec: FlowSpec }) {
+ const { placed, edges, width, height } = layoutFlow(spec);
+
+ const highlighted = new Set(
+ edges.filter((edge) => edge.highlight).flatMap((edge) => [edge.from, edge.to]),
+ );
+
+ const routes = edges.flatMap((edge) => {
+ const from = placed.get(edge.from);
+ const to = placed.get(edge.to);
+
+ if (!from || !to) return [];
+ const startX = from.x + NODE_WIDTH;
+ const startY = from.y + NODE_HEIGHT / 2;
+ const endX = to.x;
+ const endY = to.y + NODE_HEIGHT / 2;
+ const bend = Math.max(24, Math.abs(endX - startX) / 2);
+ const path = `M${startX},${startY} C${startX + bend},${startY} ${endX - bend},${endY} ${endX - 5},${endY}`;
+
+ return [{ edge, path, endX, endY, midX: (startX + endX) / 2, midY: (startY + endY) / 2 }];
+ });
+
+ return (
+ <GenerativeFrame kind="flow" title={spec.title}>
+ <div className="overflow-x-auto pb-1">
+ <div
+ className="relative mx-auto h-(--gen-h) w-(--gen-w)"
+ style={{ "--gen-w": `${width}px`, "--gen-h": `${height}px` }}
+ >
+ <svg
+ className="absolute inset-0 overflow-visible"
+ width={width}
+ height={height}
+ aria-hidden="true"
+ >
+ {routes.map(({ edge, path, endX, endY }) => (
+ <g key={`${edge.from}-${edge.to}`} data-highlight={edge.highlight === true}>
+ <path className="gen-edge" d={path} />
+ <path
+ className="gen-edge-head"
+ d={`M${endX - 6},${endY - 4} L${endX},${endY} L${endX - 6},${endY + 4} Z`}
+ />
+ </g>
+ ))}
+ </svg>
+ {routes.map(({ edge, midX, midY }) =>
+ edge.label ? (
+ <span
+ key={`${edge.from}-${edge.to}-label`}
+ className="absolute top-(--gen-y) left-(--gen-x) -translate-x-1/2 -translate-y-1/2 rounded-full border border-border/70 bg-card px-1.5 text-10px whitespace-nowrap text-muted-foreground"
+ style={{ "--gen-x": `${midX}px`, "--gen-y": `${midY}px` }}
+ >
+ {edge.label}
+ </span>
+ ) : null,
+ )}
+ {[...placed.values()].map(({ node, x, y }) => (
+ <div
+ key={node.id}
+ className="gen-flow-node absolute top-(--gen-y) left-(--gen-x) flex h-13.5 w-32 flex-col justify-center rounded-lg border border-border bg-background px-2.5"
+ data-highlight={highlighted.has(node.id)}
+ data-tone={node.tone ?? "neutral"}
+ style={{ "--gen-x": `${x}px`, "--gen-y": `${y}px` }}
+ >
+ <span className="flex items-center gap-1.5 truncate text-xs font-medium text-foreground">
+ {node.tone && node.tone !== "neutral" ? (
+ <span className="gen-tone-dot size-1.5 shrink-0 rounded-full" />
+ ) : null}
+ {node.label}
+ </span>
+ {node.detail ? (
+ <span className="truncate text-10px text-muted-foreground">{node.detail}</span>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ </div>
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeFrame.tsx b/apps/web/src/components/markdown/generative/GenerativeFrame.tsx
new file mode 100644
index 000000000..5c562bd9b
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeFrame.tsx
@@ -0,0 +1,56 @@
+import type { ReactNode } from "react";
+import { Card } from "../../ui/card";
+import { Skeleton } from "../../ui/skeleton";
+
+/** Shared card chrome for every generative block: optional header, then the body. */
+export function GenerativeFrame({
+ kind,
+ title,
+ subtitle,
+ aside,
+ children,
+}: {
+ readonly kind: string;
+ readonly title?: string | undefined;
+ readonly subtitle?: string | undefined;
+ readonly aside?: ReactNode;
+ readonly children: ReactNode;
+}) {
+ const hasHeader = title !== undefined || subtitle !== undefined || aside !== undefined;
+
+ return (
+ <div className="chat-generative" data-generative={kind}>
+ <Card>
+ {hasHeader ? (
+ // On a narrow card the aside (a chart legend) wraps below the title instead of truncating it.
+ <div className="flex flex-wrap items-start justify-between gap-x-3 gap-y-1.5 px-4 pt-3.5">
+ <div className="min-w-0 flex-1 basis-40">
+ {title ? (
+ <div className="truncate text-sm font-semibold text-foreground">{title}</div>
+ ) : null}
+ {subtitle ? (
+ <div className="truncate text-xs text-muted-foreground">{subtitle}</div>
+ ) : null}
+ </div>
+ {aside ? <div className="shrink-0">{aside}</div> : null}
+ </div>
+ ) : null}
+ <div className="px-4 pt-3 pb-3.5">{children}</div>
+ </Card>
+ </div>
+ );
+}
+
+/** Placeholder while a block's JSON is still streaming in. */
+export function GenerativeBlockPending() {
+ return (
+ <div className="chat-generative" data-generative="pending">
+ <Card>
+ <div className="flex flex-col gap-2.5 px-4 py-3.5">
+ <Skeleton className="h-3.5 w-32" />
+ <Skeleton className="h-24 w-full" />
+ </div>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeStats.tsx b/apps/web/src/components/markdown/generative/GenerativeStats.tsx
new file mode 100644
index 000000000..eabfe0f61
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeStats.tsx
@@ -0,0 +1,65 @@
+import type { StatsSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+const SPARK_WIDTH = 100;
+
+const SPARK_HEIGHT = 24;
+
+function Sparkline({ values }: { readonly values: ReadonlyArray<number> }) {
+ if (values.length < 2) return null;
+ const min = Math.min(...values);
+ const range = Math.max(...values) - min || 1;
+
+ const path = values
+ .map((value, index) => {
+ const x = (index / (values.length - 1)) * SPARK_WIDTH;
+ const y = SPARK_HEIGHT - 2 - ((value - min) / range) * (SPARK_HEIGHT - 4);
+
+ return `${index === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`;
+ })
+ .join(" ");
+
+ return (
+ <svg
+ className="h-6 w-full overflow-visible"
+ viewBox={`0 0 ${SPARK_WIDTH} ${SPARK_HEIGHT}`}
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ data-series={0}
+ >
+ <path
+ className="gen-area"
+ d={`${path} L${SPARK_WIDTH},${SPARK_HEIGHT} L0,${SPARK_HEIGHT} Z`}
+ />
+ <path className="gen-line" d={path} />
+ </svg>
+ );
+}
+
+export function GenerativeStats({ spec }: { readonly spec: StatsSpec }) {
+ return (
+ <GenerativeFrame kind="stats" title={spec.title}>
+ <div className="grid grid-cols-2 gap-x-5 gap-y-4 sm:grid-cols-3">
+ {spec.stats.map((stat) => (
+ <div key={stat.label} className="flex min-w-0 flex-col gap-1">
+ <div className="truncate text-xs text-muted-foreground">{stat.label}</div>
+ <div className="flex items-baseline gap-2">
+ <span className="text-xl font-semibold tracking-tight text-foreground tabular-nums">
+ {stat.value}
+ </span>
+ {stat.delta ? (
+ <span
+ className="gen-tone-text text-xs font-medium tabular-nums"
+ data-tone={stat.tone ?? "neutral"}
+ >
+ {stat.delta}
+ </span>
+ ) : null}
+ </div>
+ {stat.trend ? <Sparkline values={stat.trend} /> : null}
+ </div>
+ ))}
+ </div>
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeTasks.tsx b/apps/web/src/components/markdown/generative/GenerativeTasks.tsx
new file mode 100644
index 000000000..0458c50ef
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeTasks.tsx
@@ -0,0 +1,68 @@
+import { CircleAlertIcon, CircleCheckIcon, CircleDotIcon, CircleIcon } from "lucide-react";
+import type { TasksSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+type TaskState = TasksSpec["items"][number]["state"];
+
+function TaskStateIcon({ state }: { readonly state: TaskState }) {
+ switch (state) {
+ case "done":
+ return <CircleCheckIcon className="size-4 text-success" aria-label="Done" />;
+ case "running":
+ return <CircleDotIcon className="size-4 text-primary" aria-label="In progress" />;
+ case "blocked":
+ return <CircleAlertIcon className="size-4 text-warning" aria-label="Blocked" />;
+ case "todo":
+ return <CircleIcon className="size-4 text-muted-foreground/60" aria-label="Not started" />;
+ }
+}
+
+export function GenerativeTasks({ spec }: { readonly spec: TasksSpec }) {
+ const done = spec.items.filter((item) => item.state === "done").length;
+ const total = spec.items.length;
+
+ return (
+ <GenerativeFrame
+ kind="tasks"
+ title={spec.title}
+ aside={
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {done}/{total}
+ </span>
+ }
+ >
+ <div className="gen-progress-track mb-3 h-1 overflow-hidden rounded-full">
+ <div
+ className="gen-progress-fill h-full w-(--gen-progress) rounded-full"
+ style={{ "--gen-progress": `${total === 0 ? 0 : (done / total) * 100}%` }}
+ />
+ </div>
+ <ul className="m-0 flex list-none flex-col gap-2 p-0">
+ {spec.items.map((item) => (
+ <li key={item.label} className="m-0 flex items-start gap-2.5 p-0">
+ <span className="mt-0.5 shrink-0">
+ <TaskStateIcon state={item.state} />
+ </span>
+ <span
+ className={
+ item.state === "done"
+ ? "min-w-0 flex-1 text-sm text-muted-foreground"
+ : "min-w-0 flex-1 text-sm text-foreground"
+ }
+ >
+ {item.label}
+ </span>
+ {item.note ? (
+ <span
+ className="gen-tone-text shrink-0 text-xs"
+ data-tone={item.state === "blocked" ? "warn" : "neutral"}
+ >
+ {item.note}
+ </span>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/GenerativeTimeline.tsx b/apps/web/src/components/markdown/generative/GenerativeTimeline.tsx
new file mode 100644
index 000000000..739ebb996
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/GenerativeTimeline.tsx
@@ -0,0 +1,34 @@
+import type { TimelineSpec } from "./generativeSchemas";
+import { GenerativeFrame } from "./GenerativeFrame";
+
+export function GenerativeTimeline({ spec }: { readonly spec: TimelineSpec }) {
+ return (
+ <GenerativeFrame kind="timeline" title={spec.title}>
+ <ol className="m-0 flex list-none flex-col p-0">
+ {spec.events.map((event, index) => (
+ <li
+ key={`${event.time}-${event.label}`}
+ className="m-0 flex gap-3 p-0"
+ data-tone={event.tone ?? "neutral"}
+ >
+ <span className="w-12 shrink-0 pt-px text-right font-mono text-xs text-muted-foreground tabular-nums">
+ {event.time}
+ </span>
+ <span className="relative flex w-2.5 shrink-0 justify-center">
+ <span className="gen-tone-dot relative z-10 mt-1.5 size-2 rounded-full ring-3 ring-card" />
+ {index < spec.events.length - 1 ? (
+ <span className="gen-rail absolute top-3 -bottom-1.5 w-px" />
+ ) : null}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col pb-3.5">
+ <span className="text-sm text-foreground">{event.label}</span>
+ {event.detail ? (
+ <span className="text-xs text-muted-foreground">{event.detail}</span>
+ ) : null}
+ </span>
+ </li>
+ ))}
+ </ol>
+ </GenerativeFrame>
+ );
+}
diff --git a/apps/web/src/components/markdown/generative/chatReplyContext.ts b/apps/web/src/components/markdown/generative/chatReplyContext.ts
new file mode 100644
index 000000000..622c7c60a
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/chatReplyContext.ts
@@ -0,0 +1,12 @@
+import { createContext } from "react";
+
+/**
+ * Lets a reply's interactive blocks send a message as the user. Bot and group chats
+ * provide it; elsewhere choice cards fall back to filling the composer.
+ */
+export interface ChatReply {
+ readonly send: (text: string) => Promise<boolean>;
+ readonly disabled: boolean;
+}
+
+export const ChatReplyContext = createContext<ChatReply | null>(null);
diff --git a/apps/web/src/components/markdown/generative/generativeSchemas.test.ts b/apps/web/src/components/markdown/generative/generativeSchemas.test.ts
new file mode 100644
index 000000000..379da63f3
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/generativeSchemas.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vite-plus/test";
+import { layoutFlow } from "./GenerativeFlow";
+import { decodeGenerativeBlock, generativeKindForLanguage } from "./generativeSchemas";
+
+describe("generative blocks", () => {
+ it("maps only akeru- fences to block kinds", () => {
+ expect(generativeKindForLanguage("akeru-chart")).toBe("chart");
+ expect(generativeKindForLanguage("AKERU-Tasks")).toBe("tasks");
+ expect(generativeKindForLanguage("akeru-unknown")).toBeNull();
+ expect(generativeKindForLanguage("json")).toBeNull();
+ });
+
+ it("decodes a valid spec and rejects partial or malformed JSON", () => {
+ const chart = '{"type":"bar","x":["Mon","Tue"],"series":[{"name":"PRs","values":[3,5]}]}';
+
+ expect(decodeGenerativeBlock("chart", chart)?.kind).toBe("chart");
+ expect(decodeGenerativeBlock("chart", chart.slice(0, 30))).toBeNull();
+ expect(decodeGenerativeBlock("chart", '{"type":"pie","x":[],"series":[]}')).toBeNull();
+ });
+
+ it("rejects charts the renderer would misdraw", () => {
+ const series = (values: number[]) => ({ name: "s", values });
+
+ const chart = (spec: { type: string; x: string[]; series: ReturnType<typeof series>[] }) =>
+ decodeGenerativeBlock("chart", JSON.stringify(spec));
+
+ expect(chart({ type: "bar", x: ["Mon", "Tue"], series: [series([-4, 6])] })).toBeNull();
+ expect(chart({ type: "line", x: ["Mon", "Tue"], series: [series([5])] })).toBeNull();
+
+ expect(
+ chart({ type: "line", x: ["Mon"], series: [1, 2, 3, 4, 5].map((n) => series([n])) }),
+ ).toBeNull();
+
+ expect(chart({ type: "line", x: ["Mon"], series: [series([0])] })?.kind).toBe("chart");
+ });
+
+ it("bounds flows and rejects choices that share a label", () => {
+ const nodes = Array.from({ length: 25 }, (_, index) => ({ id: `n${index}`, label: "N" }));
+
+ expect(decodeGenerativeBlock("flow", JSON.stringify({ nodes, edges: [] }))).toBeNull();
+
+ const option = { label: "Same", reply: "one" };
+
+ expect(
+ decodeGenerativeBlock(
+ "choices",
+ JSON.stringify({ question: "Q", options: [option, { ...option, reply: "two" }] }),
+ ),
+ ).toBeNull();
+ });
+
+ it("ranks flow nodes left to right and survives cycles", () => {
+ const flow = decodeGenerativeBlock(
+ "flow",
+ JSON.stringify({
+ nodes: [
+ { id: "a", label: "A" },
+ { id: "b", label: "B" },
+ { id: "c", label: "C" },
+ ],
+ edges: [
+ { from: "a", to: "b" },
+ { from: "b", to: "c" },
+ { from: "c", to: "a" },
+ ],
+ }),
+ );
+
+ expect(flow?.kind).toBe("flow");
+
+ if (flow?.kind !== "flow") return;
+
+ const layout = layoutFlow(flow.spec);
+
+ expect(layout.placed.size).toBe(3);
+ // A cycle never reaches rank 0; the empty column must not turn the layout into NaN.
+ expect(Number.isFinite(layout.height)).toBe(true);
+
+ for (const node of layout.placed.values()) {
+ expect(Number.isFinite(node.x) && Number.isFinite(node.y)).toBe(true);
+ }
+ });
+});
diff --git a/apps/web/src/components/markdown/generative/generativeSchemas.ts b/apps/web/src/components/markdown/generative/generativeSchemas.ts
new file mode 100644
index 000000000..c0ddc07ec
--- /dev/null
+++ b/apps/web/src/components/markdown/generative/generativeSchemas.ts
@@ -0,0 +1,223 @@
+import { Option, Schema } from "effect";
+
+// Bots emit these as JSON inside fenced blocks such as ```akeru-chart. The
+// model only fills data slots; every color, size, and font comes from the theme.
+// Each spec only accepts what its renderer can draw faithfully and cheaply; anything
+// else fails to decode and the reply shows the block as plain code instead.
+
+const Tone = Schema.Literals(["neutral", "good", "warn", "bad"]);
+
+export type GenerativeTone = typeof Tone.Type;
+
+/** Charts plot from a zero baseline, so values below zero have nowhere to go. */
+const ChartValue = Schema.Finite.check(Schema.makeFilter((value) => value >= 0));
+
+const ChartSeries = Schema.Struct({
+ name: Schema.String,
+ values: Schema.Array(ChartValue),
+});
+
+/** The series palette has four steps. */
+const MAX_CHART_SERIES = 4;
+
+const MAX_CHART_POINTS = 60;
+
+export const ChartSpec = Schema.Struct({
+ type: Schema.Literals(["line", "area", "bar"]),
+ title: Schema.optionalKey(Schema.String),
+ subtitle: Schema.optionalKey(Schema.String),
+ unit: Schema.optionalKey(Schema.String),
+ x: Schema.Array(Schema.String).check(Schema.isLengthBetween(1, MAX_CHART_POINTS)),
+ series: Schema.Array(ChartSeries).check(Schema.isLengthBetween(1, MAX_CHART_SERIES)),
+}).check(
+ // A missing point would otherwise draw as zero, and labels and names key the drawing.
+ Schema.makeFilter(
+ (spec) =>
+ spec.series.every((series) => series.values.length === spec.x.length) &&
+ new Set(spec.x).size === spec.x.length &&
+ new Set(spec.series.map((series) => series.name)).size === spec.series.length,
+ ),
+);
+
+export type ChartSpec = typeof ChartSpec.Type;
+
+const StatTile = Schema.Struct({
+ label: Schema.String,
+ value: Schema.String,
+ delta: Schema.optionalKey(Schema.String),
+ tone: Schema.optionalKey(Tone),
+ trend: Schema.optionalKey(Schema.Array(Schema.Finite)),
+});
+
+export const StatsSpec = Schema.Struct({
+ title: Schema.optionalKey(Schema.String),
+ stats: Schema.Array(StatTile).check(Schema.isLengthBetween(1, 6)),
+});
+
+export type StatsSpec = typeof StatsSpec.Type;
+
+const TaskItem = Schema.Struct({
+ label: Schema.String,
+ state: Schema.Literals(["done", "running", "todo", "blocked"]),
+ note: Schema.optionalKey(Schema.String),
+});
+
+export const TasksSpec = Schema.Struct({
+ title: Schema.String,
+ items: Schema.Array(TaskItem).check(Schema.isLengthBetween(1, 30)),
+});
+
+export type TasksSpec = typeof TasksSpec.Type;
+
+const FlowNode = Schema.Struct({
+ id: Schema.String,
+ label: Schema.String,
+ detail: Schema.optionalKey(Schema.String),
+ tone: Schema.optionalKey(Tone),
+});
+
+const FlowEdge = Schema.Struct({
+ from: Schema.String,
+ to: Schema.String,
+ label: Schema.optionalKey(Schema.String),
+ highlight: Schema.optionalKey(Schema.Boolean),
+});
+
+/** Layout walks the graph recursively, so the node count also bounds its depth. */
+export const FlowSpec = Schema.Struct({
+ title: Schema.optionalKey(Schema.String),
+ nodes: Schema.Array(FlowNode).check(Schema.isLengthBetween(1, 24)),
+ edges: Schema.Array(FlowEdge).check(Schema.isMaxLength(48)),
+});
+
+export type FlowSpec = typeof FlowSpec.Type;
+
+const ChoiceOption = Schema.Struct({
+ label: Schema.String,
+ detail: Schema.optionalKey(Schema.String),
+ reply: Schema.String,
+ recommended: Schema.optionalKey(Schema.Boolean),
+});
+
+export const ChoicesSpec = Schema.Struct({
+ question: Schema.String,
+ options: Schema.Array(ChoiceOption)
+ .check(Schema.isLengthBetween(1, 6))
+ // A choice is identified by its label.
+ .check(
+ Schema.makeFilter(
+ (options) => new Set(options.map((option) => option.label)).size === options.length,
+ ),
+ ),
+});
+
+export type ChoicesSpec = typeof ChoicesSpec.Type;
+
+const TimelineEvent = Schema.Struct({
+ time: Schema.String,
+ label: Schema.String,
+ detail: Schema.optionalKey(Schema.String),
+ tone: Schema.optionalKey(Tone),
+});
+
+export const TimelineSpec = Schema.Struct({
+ title: Schema.optionalKey(Schema.String),
+ events: Schema.Array(TimelineEvent).check(Schema.isLengthBetween(1, 30)),
+});
+
+export type TimelineSpec = typeof TimelineSpec.Type;
+
+export type GenerativeBlockSpec =
+ | { readonly kind: "chart"; readonly spec: ChartSpec }
+ | { readonly kind: "stats"; readonly spec: StatsSpec }
+ | { readonly kind: "tasks"; readonly spec: TasksSpec }
+ | { readonly kind: "flow"; readonly spec: FlowSpec }
+ | { readonly kind: "choices"; readonly spec: ChoicesSpec }
+ | { readonly kind: "timeline"; readonly spec: TimelineSpec };
+
+const decoders = {
+ chart: Schema.decodeUnknownOption(Schema.fromJsonString(ChartSpec)),
+ stats: Schema.decodeUnknownOption(Schema.fromJsonString(StatsSpec)),
+ tasks: Schema.decodeUnknownOption(Schema.fromJsonString(TasksSpec)),
+ flow: Schema.decodeUnknownOption(Schema.fromJsonString(FlowSpec)),
+ choices: Schema.decodeUnknownOption(Schema.fromJsonString(ChoicesSpec)),
+ timeline: Schema.decodeUnknownOption(Schema.fromJsonString(TimelineSpec)),
+} as const;
+
+type GenerativeKind = keyof typeof decoders;
+
+const GENERATIVE_KINDS: ReadonlyArray<GenerativeKind> = [
+ "chart",
+ "stats",
+ "tasks",
+ "flow",
+ "choices",
+ "timeline",
+];
+
+const FENCE_PREFIX = "akeru-";
+
+export function generativeKindForLanguage(language: string): GenerativeKind | null {
+ const normalized = language.toLowerCase();
+
+ if (!normalized.startsWith(FENCE_PREFIX)) return null;
+ const suffix = normalized.slice(FENCE_PREFIX.length);
+
+ return GENERATIVE_KINDS.find((kind) => kind === suffix) ?? null;
+}
+
+export function decodeGenerativeBlock(
+ kind: GenerativeKind,
+ code: string,
+): GenerativeBlockSpec | null {
+ // Each branch keeps the kind and spec paired for the discriminated union.
+ switch (kind) {
+ case "chart":
+ return Option.match(decoders.chart(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ case "stats":
+ return Option.match(decoders.stats(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ case "tasks":
+ return Option.match(decoders.tasks(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ case "flow":
+ return Option.match(decoders.flow(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ case "choices":
+ return Option.match(decoders.choices(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ case "timeline":
+ return Option.match(decoders.timeline(code), {
+ onNone: () => null,
+ onSome: (spec) => ({ kind, spec }),
+ });
+ }
+}
+
+const KIND_LABELS: Record<GenerativeKind, string> = {
+ chart: "Chart",
+ stats: "Stats",
+ tasks: "Tasks",
+ flow: "Diagram",
+ choices: "Options",
+ timeline: "Timeline",
+};
+
+/** One-line stand-in for a block in plain-text previews, such as the roster sidebar. */
+export function generativeBlockSummary(kind: GenerativeKind, code: string): string {
+ const block = decodeGenerativeBlock(kind, code);
+ const heading = block?.kind === "choices" ? block.spec.question : block?.spec.title;
+
+ return heading ? `${KIND_LABELS[kind]}: ${heading}` : KIND_LABELS[kind];
+}
diff --git a/apps/web/src/components/onboarding/desktopOnboardingDraft.ts b/apps/web/src/components/onboarding/desktopOnboardingDraft.ts
index e02d0252f..46535f52c 100644
--- a/apps/web/src/components/onboarding/desktopOnboardingDraft.ts
+++ b/apps/web/src/components/onboarding/desktopOnboardingDraft.ts
@@ -136,7 +136,7 @@ export const DEFAULT_DESKTOP_ONBOARDING_DRAFT: DesktopOnboardingDraft = {
goal: "",
goalPhase: "ask",
name: "",
- avatar: { kind: "blob", shape: "squircle", color: "#8B6FC9" },
+ avatar: { kind: "blob", shape: "squircle", color: "#2E8EFF" },
botId: null,
};
diff --git a/apps/web/src/components/roster/BotChatMessageRows.tsx b/apps/web/src/components/roster/BotChatMessageRows.tsx
index 9746aa2a7..cb02ddabb 100644
--- a/apps/web/src/components/roster/BotChatMessageRows.tsx
+++ b/apps/web/src/components/roster/BotChatMessageRows.tsx
@@ -1,4 +1,5 @@
import type { EnvironmentId, OrchestrationMessage, ServerProviderSkill } from "@akeru/contracts";
+import type { AnsweredUserInputQuestion } from "@akeru/client-runtime/user-input-answers";
import { SmilePlusIcon } from "lucide-react";
import { memo } from "react";
@@ -16,6 +17,7 @@ import {
import { MessageReactions } from "../chat/MessageReactions";
import { PluginSearchResultCard } from "../chat/PluginSearchResultCard";
import { SentMessageText } from "../chat/SentMessageText";
+import { UserInputAnswerCard } from "../chat/UserInputAnswerCard";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { BotAvatarView } from "./BotAvatarView";
@@ -251,6 +253,7 @@ export const UserMessageRow = memo(function UserMessageRow({
skills,
environmentId,
currentPersonId,
+ answered = null,
onReply,
onReactionChange,
}: {
@@ -265,6 +268,8 @@ export const UserMessageRow = memo(function UserMessageRow({
readonly skills: ReadonlyArray<ServerProviderSkill> | undefined;
readonly environmentId: EnvironmentId | null;
readonly currentPersonId: string | null | undefined;
+ /** Set when this message answers a bot's questions; it then reads back as an answer card. */
+ readonly answered?: ReadonlyArray<AnsweredUserInputQuestion> | null;
readonly onReply: MessageReplyHandler;
/** Null while the chat has no linked thread to react in. */
readonly onReactionChange: MessageReactionHandler | null;
@@ -298,28 +303,32 @@ export const UserMessageRow = memo(function UserMessageRow({
) : null}
</div>
<div className="flex max-w-39/50 flex-col items-end">
- <div className="w-full rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">
- {showChannelOrigin && message.channelOrigin ? (
- <div className="mb-1 text-xs font-medium text-muted-foreground">
- {channelOriginLabel(message.channelOrigin, message.authorDisplayName)}
- </div>
- ) : null}
- {message.text ? (
- <SentMessageText
- text={message.text}
- skills={skills}
- replySourceMessageId={replySourceMessageId}
- />
- ) : null}
- {message.attachments?.length ? (
- <div className={message.text ? "mt-2" : undefined}>
- <BotMessageAttachments
- attachments={message.attachments}
- environmentId={environmentId ?? NO_ENVIRONMENT}
+ {answered ? (
+ <UserInputAnswerCard answered={answered} />
+ ) : (
+ <div className="w-full rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">
+ {showChannelOrigin && message.channelOrigin ? (
+ <div className="mb-1 text-xs font-medium text-muted-foreground">
+ {channelOriginLabel(message.channelOrigin, message.authorDisplayName)}
+ </div>
+ ) : null}
+ {message.text ? (
+ <SentMessageText
+ text={message.text}
+ skills={skills}
+ replySourceMessageId={replySourceMessageId}
/>
- </div>
- ) : null}
- </div>
+ ) : null}
+ {message.attachments?.length ? (
+ <div className={message.text ? "mt-2" : undefined}>
+ <BotMessageAttachments
+ attachments={message.attachments}
+ environmentId={environmentId ?? NO_ENVIRONMENT}
+ />
+ </div>
+ ) : null}
+ </div>
+ )}
<MessageReactions
align="end"
reactions={message.reactions ?? []}
diff --git a/apps/web/src/components/roster/BotPromptComposer.tsx b/apps/web/src/components/roster/BotPromptComposer.tsx
index 6c8f594f6..952bfbc3c 100644
--- a/apps/web/src/components/roster/BotPromptComposer.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.tsx
@@ -87,6 +87,7 @@ export function BotPromptComposer({
draftKey,
disabled,
readOnly = false,
+ typeToFocus = true,
mentionBots = EMPTY_MENTION_BOTS,
mentionScope = null,
commandCatalog,
@@ -105,6 +106,8 @@ export function BotPromptComposer({
draftKey?: string;
disabled: boolean;
readOnly?: boolean;
+ /** Off while something else on the page owns printable keys, like an open question's letter shortcuts. */
+ typeToFocus?: boolean;
mentionBots?: ReadonlyArray<MentionBot>;
/** Enables `@browser` and `@chat:` mentions for this chat's environment. */
mentionScope?: BotPromptMentionScope | null;
@@ -274,6 +277,7 @@ export function BotPromptComposer({
const showBusyMeter = busy && !canSubmit;
useBotComposerKeyboard({
readOnly,
+ typeToFocus,
keybindings,
promptInputRef,
persistDraft,
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index 5f73796b2..faffec8fc 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -25,6 +25,7 @@ import { deriveBotActivity } from "./botActivityStatus.logic";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
import { MemoryApprovalPrompt } from "./MemoryApprovalPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
+import { ChatReplyContext } from "../markdown/generative/chatReplyContext";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
import { useBotDetailsOpen } from "./detailsPanelOpen";
@@ -48,12 +49,12 @@ import { useSubscriptionStatuses } from "../settings/ProvidersPanel";
import { BotTurnFailureRow } from "./BotTurnFailureRow";
import { useBotEngineAvailability } from "./useBotEngineAvailability";
import { BotPromptComposer } from "./BotPromptComposer";
+import { useAnsweredUserInputs } from "./useAnsweredUserInputs";
import { useBotPromptMentionScope } from "./BotPromptMentions";
import { buildBotStepMeters } from "@akeru/client-runtime/bot-step-usage";
import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";
import { ProviderUnavailableLine } from "../chat/ProviderUnavailableNotice";
import { ComposerPendingUserInputPanel } from "../chat/ComposerPendingUserInputPanel";
-import { OpenComputerAction } from "../computer/OpenComputerAction";
import { PluginSearchResultCard } from "../chat/PluginSearchResultCard";
import {
buildReplyPrompt,
@@ -239,6 +240,8 @@ export function BotThreadLanding({
[runtime.messages, working],
);
+ const answeredUserInputs = useAnsweredUserInputs(activities, messages);
+
const today = useLocalDay();
const todayLabel = t("Today");
@@ -358,302 +361,319 @@ export function BotThreadLanding({
};
};
+ const chatReply = {
+ disabled:
+ runtime.sending ||
+ runtime.latestTurn?.state === "running" ||
+ runtime.pendingUserInputs.length > 0 ||
+ pendingApproval !== null ||
+ sendBlocked ||
+ !runtime.botReady,
+ send: (text: string) => runtime.send(text, []),
+ };
+
return (
- <SidebarInset
- tone="foreground"
- aria-label={t("{name} chat", { name: bot.name })}
- className="h-dvh min-h-0 overflow-hidden"
- data-testid="bot-thread-landing"
- >
- <div className="flex min-h-0 min-w-0 flex-1">
- <div className="flex min-h-0 min-w-0 flex-1 flex-col">
- <WorkspacePageHeader
- className="border-b border-border"
- detailsPanelOpen={detailsPanelOpen}
- >
- <div className="flex min-w-0 items-center gap-2">
- <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-6" />
- <span className="truncate text-sm font-medium">{bot.name}</span>
- </div>
- <div data-chat-header-actions className="ml-auto flex items-center">
- <BotVoiceCallButton
- bot={bot}
- disabled={runtime.sending || runtime.latestTurn?.state === "running"}
- />
- {available ? (
- <ChatActionsMenu threadRef={runtime.linkedThreadRef} newChat={newChat} />
- ) : null}
- </div>
- </WorkspacePageHeader>
- <BotConversationScrollArea
- followKey={messages.findLast((message) => message.role === "user")?.id}
- >
- {olderRoutineNotes.nextCursor ? (
- <button
- type="button"
- className="mx-auto my-3 block rounded-md px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
- disabled={olderRoutineNotes.isPending}
- onClick={olderRoutineNotes.load}
- >
- {olderRoutineNotes.isPending
- ? t("Loading older routine notes…")
- : olderRoutineNotes.error
- ? t("Retry older routine notes")
- : t("Load older routine notes")}
- </button>
- ) : null}
- {timelineItems.length === 0 ? (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">
- <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-14" />
- <h1 className="text-lg font-medium">{t("Message {name}", { name: bot.name })}</h1>
+ <ChatReplyContext value={chatReply}>
+ <SidebarInset
+ tone="foreground"
+ aria-label={t("{name} chat", { name: bot.name })}
+ className="h-dvh min-h-0 overflow-hidden"
+ data-testid="bot-thread-landing"
+ >
+ <div className="flex min-h-0 min-w-0 flex-1">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <WorkspacePageHeader
+ className="border-b border-border"
+ detailsPanelOpen={detailsPanelOpen}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-6" />
+ <span className="truncate text-sm font-medium">{bot.name}</span>
</div>
- ) : (
- timelineItems.map((item, timelineIndex) => (
- <Fragment key={item.key}>
- {Predicate.isTagged(item, "Receipt") ? (
- <RoutineReceiptRow
- receipt={item.receipt}
- {...(onOpenRoutines ? { onOpenRoutines } : {})}
- />
- ) : Predicate.isTagged(item, "Delegation") ? (
- <DelegationCard
- delegation={item.delegation}
- delegations={delegations}
- childBot={activeBot(item.delegation.childBotId)}
- parentBot={activeBot(item.delegation.parentBotId)}
- />
- ) : (
- (() => {
- const { message, separator, startsGroup } = item.message.entry;
-
- const startsAfterReceipt = Predicate.isTagged(
- timelineItems[timelineIndex - 1] ?? {},
- "Receipt",
- );
-
- const messageIndex = item.index;
-
- return (
- <>
- {separator ? <ConversationSeparator label={separator} /> : null}
- {message.role === "assistant" ? (
- <AssistantMessageRow
- message={message}
- arrived={arrivedMessageIds.has(message.id)}
- author={bot}
- testId="bot-provider-message"
- startsGroup={startsGroup || startsAfterReceipt}
- cwd={runtime.defaultProject?.workspaceRoot}
- threadRef={runtime.linkedThreadRef ?? undefined}
- stepMeter={
- message.turnId === null ? undefined : stepMeters.get(message.turnId)
- }
- pluginResults={
- message.turnId === null
- ? undefined
- : pluginResultsByTurn.get(message.turnId)
- }
- currentPersonId={currentPersonId}
- playback={replyPlayback}
- playbackKey={playbackKey}
- channelApproval={channelApprovalFor(messageIndex)}
- onReply={replyTo}
- onReactionChange={reactionHandler}
- />
- ) : (
- <UserMessageRow
- message={message}
- replySourceMessageId={findReplySourceMessageId(
- messages,
- messageIndex,
- message.text,
- )}
- arrived={arrivedMessageIds.has(message.id)}
- testId="bot-user-message"
- startsGroup={startsGroup || startsAfterReceipt}
- replyLabel="you"
- showChannelOrigin
- skills={engineCatalog?.skills}
- environmentId={environmentId}
- currentPersonId={currentPersonId}
- onReply={replyTo}
- onReactionChange={reactionHandler}
- />
- )}
- </>
- );
- })()
- )}
- </Fragment>
- ))
- )}
- {pendingPluginResults.map(([turnId, results]) => (
- <div className="flex items-start gap-3" key={`${turnId}:plugins`}>
- <BotAvatarView
- avatar={bot.avatar}
- name={bot.name}
- className="mt-0.5 size-7 shrink-0"
+ <div data-chat-header-actions className="ml-auto flex items-center">
+ <BotVoiceCallButton
+ bot={bot}
+ disabled={runtime.sending || runtime.latestTurn?.state === "running"}
/>
- <div className="min-w-0 flex-1 space-y-3">
- <div className="text-sm font-medium">{bot.name}</div>
- {results.map(({ id, result }) => (
- <PluginSearchResultCard key={id} result={result} />
- ))}
- </div>
+ {available ? (
+ <ChatActionsMenu threadRef={runtime.linkedThreadRef} newChat={newChat} />
+ ) : null}
</div>
- ))}
- {runtime.pendingUserInputs.length > 0 ? (
- <div className="flex items-start gap-3">
- <BotAvatarView
- avatar={bot.avatar}
- name={bot.name}
- className="mt-0.5 size-7 shrink-0"
- />
- <div className="min-w-0 flex-1">
- <div className="mb-2 text-sm font-medium">{bot.name}</div>
- <ComposerPendingUserInputPanel
- pendingUserInputs={runtime.pendingUserInputs}
- respondingRequestIds={runtime.respondingRequestIds}
- answers={runtime.pendingUserInputAnswers}
- questionIndex={runtime.pendingUserInputQuestionIndex}
- onToggleOption={runtime.selectPendingUserInputOption}
- onSelectSingleOption={runtime.selectPendingUserInputOption}
- onAdvance={() => {
- void runtime.advancePendingUserInput();
- }}
+ </WorkspacePageHeader>
+ <BotConversationScrollArea
+ followKey={messages.findLast((message) => message.role === "user")?.id}
+ >
+ {olderRoutineNotes.nextCursor ? (
+ <button
+ type="button"
+ className="mx-auto my-3 block rounded-md px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
+ disabled={olderRoutineNotes.isPending}
+ onClick={olderRoutineNotes.load}
+ >
+ {olderRoutineNotes.isPending
+ ? t("Loading older routine notes…")
+ : olderRoutineNotes.error
+ ? t("Retry older routine notes")
+ : t("Load older routine notes")}
+ </button>
+ ) : null}
+ {timelineItems.length === 0 ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">
+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-14" />
+ <h1 className="text-lg font-medium">{t("Message {name}", { name: bot.name })}</h1>
+ </div>
+ ) : (
+ timelineItems.map((item, timelineIndex) => (
+ <Fragment key={item.key}>
+ {Predicate.isTagged(item, "Receipt") ? (
+ <RoutineReceiptRow
+ receipt={item.receipt}
+ {...(onOpenRoutines ? { onOpenRoutines } : {})}
+ />
+ ) : Predicate.isTagged(item, "Delegation") ? (
+ <DelegationCard
+ delegation={item.delegation}
+ delegations={delegations}
+ childBot={activeBot(item.delegation.childBotId)}
+ parentBot={activeBot(item.delegation.parentBotId)}
+ />
+ ) : (
+ (() => {
+ const { message, separator, startsGroup } = item.message.entry;
+
+ const startsAfterReceipt = Predicate.isTagged(
+ timelineItems[timelineIndex - 1] ?? {},
+ "Receipt",
+ );
+
+ const messageIndex = item.index;
+
+ return (
+ <>
+ {separator ? <ConversationSeparator label={separator} /> : null}
+ {message.role === "assistant" ? (
+ <AssistantMessageRow
+ message={message}
+ arrived={arrivedMessageIds.has(message.id)}
+ author={bot}
+ testId="bot-provider-message"
+ startsGroup={startsGroup || startsAfterReceipt}
+ cwd={runtime.defaultProject?.workspaceRoot}
+ threadRef={runtime.linkedThreadRef ?? undefined}
+ stepMeter={
+ message.turnId === null
+ ? undefined
+ : stepMeters.get(message.turnId)
+ }
+ pluginResults={
+ message.turnId === null
+ ? undefined
+ : pluginResultsByTurn.get(message.turnId)
+ }
+ currentPersonId={currentPersonId}
+ playback={replyPlayback}
+ playbackKey={playbackKey}
+ channelApproval={channelApprovalFor(messageIndex)}
+ onReply={replyTo}
+ onReactionChange={reactionHandler}
+ />
+ ) : (
+ <UserMessageRow
+ message={message}
+ replySourceMessageId={findReplySourceMessageId(
+ messages,
+ messageIndex,
+ message.text,
+ )}
+ arrived={arrivedMessageIds.has(message.id)}
+ testId="bot-user-message"
+ startsGroup={startsGroup || startsAfterReceipt}
+ replyLabel="you"
+ showChannelOrigin
+ skills={engineCatalog?.skills}
+ environmentId={environmentId}
+ currentPersonId={currentPersonId}
+ answered={answeredUserInputs.get(message.id) ?? null}
+ onReply={replyTo}
+ onReactionChange={reactionHandler}
+ />
+ )}
+ </>
+ );
+ })()
+ )}
+ </Fragment>
+ ))
+ )}
+ {pendingPluginResults.map(([turnId, results]) => (
+ <div className="flex items-start gap-3" key={`${turnId}:plugins`}>
+ <BotAvatarView
+ avatar={bot.avatar}
+ name={bot.name}
+ className="mt-0.5 size-7 shrink-0"
/>
- <div className="mt-2">
- <OpenComputerAction threadRef={runtime.linkedThreadRef} bot={bot} />
+ <div className="min-w-0 flex-1 space-y-3">
+ <div className="text-sm font-medium">{bot.name}</div>
+ {results.map(({ id, result }) => (
+ <PluginSearchResultCard key={id} result={result} />
+ ))}
</div>
</div>
- </div>
- ) : null}
- {!working && runtime.turnFailure && messages.at(-1)?.role === "user" ? (
- <BotTurnFailureRow
+ ))}
+ {runtime.pendingUserInputs.length > 0 ? (
+ <div className="flex items-start gap-3">
+ <BotAvatarView
+ avatar={bot.avatar}
+ name={bot.name}
+ className="mt-0.5 size-7 shrink-0"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="mb-2 text-sm font-medium">{bot.name}</div>
+ <ComposerPendingUserInputPanel
+ pendingUserInputs={runtime.pendingUserInputs}
+ respondingRequestIds={runtime.respondingRequestIds}
+ answers={runtime.pendingUserInputAnswers}
+ step={runtime.pendingUserInputStep}
+ onStepChange={runtime.setPendingUserInputStep}
+ onSelectOption={runtime.selectPendingUserInputOption}
+ onAnswerWithText={(text) => {
+ void runtime.answerPendingUserInputWithText(text);
+ }}
+ onSubmit={() => {
+ void runtime.submitPendingUserInputAnswers();
+ }}
+ />
+ </div>
+ </div>
+ ) : null}
+ {!working && runtime.turnFailure && messages.at(-1)?.role === "user" ? (
+ <BotTurnFailureRow
+ botName={bot.name}
+ title={presentThreadError(runtime.turnFailure.message, failureContext, t).title}
+ />
+ ) : null}
+ {waitingOnChildren && !working ? (
+ <p className="ml-10 text-xs text-muted-foreground" aria-live="polite">
+ {t("Waiting on delegated work")}
+ </p>
+ ) : null}
+ </BotConversationScrollArea>
+ <BotInboxAlertStack
+ items={inboxItems}
+ onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
+ />
+ <ThreadRuntimeWarningBanner warning={runtimeWarning} />
+ {connectNeeded && subscriptionToConnect ? (
+ <ProviderConnectCard
+ id={engineNoticeId}
+ environmentId={environmentId}
+ provider={subscriptionToConnect}
botName={bot.name}
- title={presentThreadError(runtime.turnFailure.message, failureContext, t).title}
+ className="mt-2"
/>
) : null}
- {waitingOnChildren && !working ? (
- <p className="ml-10 text-xs text-muted-foreground" aria-live="polite">
- {t("Waiting on delegated work")}
- </p>
- ) : null}
- </BotConversationScrollArea>
- <BotInboxAlertStack
- items={inboxItems}
- onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
- />
- <ThreadRuntimeWarningBanner warning={runtimeWarning} />
- {connectNeeded && subscriptionToConnect ? (
- <ProviderConnectCard
- id={engineNoticeId}
- environmentId={environmentId}
- provider={subscriptionToConnect}
- botName={bot.name}
- className="mt-2"
- />
- ) : null}
- <ThreadErrorBanner
- threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? bot.id}`}
- error={
- connectNeeded ||
- inboxItems.some((item) => item.lastFailure === runtime.error) ||
- (sendBlocked && runtime.failure?.unavailability === engineUnavailability?.reason)
- ? null
- : runtime.error
- }
- context={failureContext}
- environmentId={environmentId}
- onOpenUsage={openBotSettings}
- {...(runtime.canResume ? { onResume: () => void runtime.resume() } : {})}
- resuming={runtime.resuming}
- />
- <BotPromptComposer
- mentionScope={mentionScope}
- commandCatalog={engineCatalog}
- botName={bot.name}
- draftKey={bot.id}
- busy={working && pendingApproval === null}
- activitySlot={
- working && !waitingForUserInput && pendingApproval === null ? (
- <BotActivityStatus
- name={bot.name}
- activity={botActivity}
- update={workingUpdate}
- silentRun={silentRun}
- />
- ) : null
- }
- pendingActionSlot={
- pendingApproval ? (
- <BotApprovalPrompt
- approval={pendingApproval}
- pendingCount={approvalState.pendingCount}
- responding={approvalState.responding}
- error={approvalState.responseError}
- onRespond={async (decision) => {
- const answered = await approvalState.respond(
- pendingApproval.requestId,
- decision,
- );
-
- if (answered && decision === "acceptAlways" && bot) {
- await enableAutoReview(bot.id);
- }
-
- return answered;
- }}
- />
- ) : memoryApprovals.length > 0 && runtime.linkedThreadRef ? (
- <MemoryApprovalPrompt
- threadRef={runtime.linkedThreadRef}
- approvals={memoryApprovals}
- currentBotId={bot.id}
- />
- ) : null
- }
- quietSurface={pendingApproval !== null}
- disabled={
- pendingApproval !== null ||
- runtime.respondingRequestIds.length > 0 ||
- voiceCall.activeCall?.botId === bot.id ||
- voiceCall.startingBotId === bot.id ||
- sendBlocked ||
- !runtime.botReady ||
- !runtime.bootstrapped ||
- runtime.defaultProject === null
- }
- replyPreview={replyTarget}
- onCancelReply={() => setReplyTarget(null)}
- sendBlockedDescriptionId={sendBlocked ? engineNoticeId : undefined}
- onSubmit={async (prompt, files) => {
- const sent = await runtime.send(buildReplyPrompt(replyTarget, prompt), files);
-
- if (sent) setReplyTarget(null);
-
- return sent;
- }}
- />
- {connectNeeded ? null : sendBlocked && engineUnavailability ? (
- <ProviderUnavailableLine
- provider={engineUnavailability.provider}
- id={engineNoticeId}
- presentation={engineUnavailability}
+ <ThreadErrorBanner
+ threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? bot.id}`}
+ error={
+ connectNeeded ||
+ inboxItems.some((item) => item.lastFailure === runtime.error) ||
+ (sendBlocked && runtime.failure?.unavailability === engineUnavailability?.reason)
+ ? null
+ : runtime.error
+ }
+ context={failureContext}
environmentId={environmentId}
onOpenUsage={openBotSettings}
+ {...(runtime.canResume ? { onResume: () => void runtime.resume() } : {})}
+ resuming={runtime.resuming}
+ />
+ <BotPromptComposer
+ typeToFocus={!waitingForUserInput}
+ mentionScope={mentionScope}
+ commandCatalog={engineCatalog}
+ botName={bot.name}
+ draftKey={bot.id}
+ busy={working && pendingApproval === null}
+ activitySlot={
+ working && !waitingForUserInput && pendingApproval === null ? (
+ <BotActivityStatus
+ name={bot.name}
+ activity={botActivity}
+ update={workingUpdate}
+ silentRun={silentRun}
+ />
+ ) : null
+ }
+ pendingActionSlot={
+ pendingApproval ? (
+ <BotApprovalPrompt
+ approval={pendingApproval}
+ pendingCount={approvalState.pendingCount}
+ responding={approvalState.responding}
+ error={approvalState.responseError}
+ onRespond={async (decision) => {
+ const answered = await approvalState.respond(
+ pendingApproval.requestId,
+ decision,
+ );
+
+ if (answered && decision === "acceptAlways" && bot) {
+ await enableAutoReview(bot.id);
+ }
+
+ return answered;
+ }}
+ />
+ ) : memoryApprovals.length > 0 && runtime.linkedThreadRef ? (
+ <MemoryApprovalPrompt
+ threadRef={runtime.linkedThreadRef}
+ approvals={memoryApprovals}
+ currentBotId={bot.id}
+ />
+ ) : null
+ }
+ quietSurface={pendingApproval !== null}
+ disabled={
+ pendingApproval !== null ||
+ runtime.respondingRequestIds.length > 0 ||
+ voiceCall.activeCall?.botId === bot.id ||
+ voiceCall.startingBotId === bot.id ||
+ sendBlocked ||
+ !runtime.botReady ||
+ !runtime.bootstrapped ||
+ runtime.defaultProject === null
+ }
+ replyPreview={replyTarget}
+ onCancelReply={() => setReplyTarget(null)}
+ sendBlockedDescriptionId={sendBlocked ? engineNoticeId : undefined}
+ onSubmit={async (prompt, files) => {
+ const sent = await runtime.send(buildReplyPrompt(replyTarget, prompt), files);
+
+ if (sent) setReplyTarget(null);
+
+ return sent;
+ }}
/>
- ) : sendBlocked ? null : !runtime.botReady ? (
- <p className="px-4 pb-3 text-center text-xs text-muted-foreground">
- {t("Connecting bot…")}
- </p>
- ) : runtime.bootstrapped && runtime.defaultProject === null ? (
- <p className="px-4 pb-3 text-center text-xs text-muted-foreground">
- {t("Your workspace is still loading. Try again in a moment.")}
- </p>
- ) : null}
+ {connectNeeded ? null : sendBlocked && engineUnavailability ? (
+ <ProviderUnavailableLine
+ provider={engineUnavailability.provider}
+ id={engineNoticeId}
+ presentation={engineUnavailability}
+ environmentId={environmentId}
+ onOpenUsage={openBotSettings}
+ />
+ ) : sendBlocked ? null : !runtime.botReady ? (
+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">
+ {t("Connecting bot…")}
+ </p>
+ ) : runtime.bootstrapped && runtime.defaultProject === null ? (
+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">
+ {t("Your workspace is still loading. Try again in a moment.")}
+ </p>
+ ) : null}
+ </div>
</div>
- </div>
- </SidebarInset>
+ </SidebarInset>
+ </ChatReplyContext>
);
}
diff --git a/apps/web/src/components/roster/BotUserInputPrompt.test.tsx b/apps/web/src/components/roster/BotUserInputPrompt.test.tsx
index cfdc85ce3..236579881 100644
--- a/apps/web/src/components/roster/BotUserInputPrompt.test.tsx
+++ b/apps/web/src/components/roster/BotUserInputPrompt.test.tsx
@@ -39,10 +39,11 @@ describe("BotUserInputPrompt", () => {
pendingUserInputs={[prompt]}
respondingRequestIds={[]}
answers={{}}
- questionIndex={0}
- onToggleOption={vi.fn()}
- onSelectSingleOption={vi.fn()}
- onAdvance={vi.fn()}
+ step={0}
+ onStepChange={vi.fn()}
+ onSelectOption={vi.fn()}
+ onAnswerWithText={vi.fn()}
+ onSubmit={vi.fn()}
/>,
);
@@ -51,31 +52,38 @@ describe("BotUserInputPrompt", () => {
expect(markup).toContain("Review risky commands");
});
- it("uses one callback for single-select answers", () => {
- const onToggleOption = vi.fn();
- const onSelectSingleOption = vi.fn();
+ it("hands the panel its select, step, and submit callbacks without chrome", () => {
+ const onSelectOption = vi.fn();
+ const onStepChange = vi.fn();
+ const onSubmit = vi.fn();
+ const onAnswerWithText = vi.fn();
const element = BotUserInputPrompt({
pendingUserInputs: [prompt],
respondingRequestIds: [],
answers: {},
- questionIndex: 0,
- onToggleOption,
- onSelectSingleOption,
- onAdvance: vi.fn(),
+ step: 0,
+ onStepChange,
+ onSelectOption,
+ onAnswerWithText,
+ onSubmit,
});
if (!element) throw new TypeError("Expected an unanswered prompt.");
- const panel = (
- element.props.children as ReactElement<{
- onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
- }>[]
- )[0];
+ const panel = element.props.children as ReactElement<{
+ onSelectOption?: (questionId: string, optionLabel: string) => void;
+ onAnswerWithText?: (text: string) => void;
+ onStepChange?: (step: number) => void;
+ onSubmit?: () => void;
+ surface?: string;
+ }>;
- if (!panel) throw new TypeError("Expected a question panel.");
-
- expect(panel.props.onSelectSingleOption).toBe(onSelectSingleOption);
+ expect(panel.props.onSelectOption).toBe(onSelectOption);
+ expect(panel.props.onAnswerWithText).toBe(onAnswerWithText);
+ expect(panel.props.onStepChange).toBe(onStepChange);
+ expect(panel.props.onSubmit).toBe(onSubmit);
+ expect(panel.props.surface).toBe("docked");
});
it("clears itself once the answer is on its way", () => {
@@ -84,10 +92,11 @@ describe("BotUserInputPrompt", () => {
pendingUserInputs: [prompt],
respondingRequestIds: [prompt.requestId],
answers: {},
- questionIndex: 0,
- onToggleOption: vi.fn(),
- onSelectSingleOption: vi.fn(),
- onAdvance: vi.fn(),
+ step: 0,
+ onStepChange: vi.fn(),
+ onSelectOption: vi.fn(),
+ onAnswerWithText: vi.fn(),
+ onSubmit: vi.fn(),
}),
).toBeNull();
expect(
@@ -95,10 +104,11 @@ describe("BotUserInputPrompt", () => {
pendingUserInputs: [],
respondingRequestIds: [],
answers: {},
- questionIndex: 0,
- onToggleOption: vi.fn(),
- onSelectSingleOption: vi.fn(),
- onAdvance: vi.fn(),
+ step: 0,
+ onStepChange: vi.fn(),
+ onSelectOption: vi.fn(),
+ onAnswerWithText: vi.fn(),
+ onSubmit: vi.fn(),
}),
).toBeNull();
});
diff --git a/apps/web/src/components/roster/BotUserInputPrompt.tsx b/apps/web/src/components/roster/BotUserInputPrompt.tsx
index 6a72e293d..9a3736aab 100644
--- a/apps/web/src/components/roster/BotUserInputPrompt.tsx
+++ b/apps/web/src/components/roster/BotUserInputPrompt.tsx
@@ -1,11 +1,9 @@
-import { type ApprovalRequestId, type ScopedThreadRef } from "@akeru/contracts";
+import { type ApprovalRequestId } from "@akeru/contracts";
import { useI18n } from "../../i18n";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingUserInput } from "../../session-logic";
import { ComposerPendingUserInputPanel } from "../chat/ComposerPendingUserInputPanel";
-import { OpenComputerAction } from "../computer/OpenComputerAction";
-import type { Bot } from "./types";
import { cn } from "../../lib/utils";
import {
BOT_COMPOSER_DOCKED_PANEL_CLASS_NAME,
@@ -16,23 +14,20 @@ export function BotUserInputPrompt({
pendingUserInputs,
respondingRequestIds,
answers,
- questionIndex,
- onToggleOption,
- onSelectSingleOption,
- onAdvance,
- threadRef = null,
- askingBot = null,
+ step,
+ onStepChange,
+ onSelectOption,
+ onAnswerWithText,
+ onSubmit,
}: {
readonly pendingUserInputs: PendingUserInput[];
readonly respondingRequestIds: ApprovalRequestId[];
readonly answers: Record<string, PendingUserInputDraftAnswer>;
- readonly questionIndex: number;
- readonly onToggleOption: (questionId: string, optionLabel: string) => void;
- readonly onSelectSingleOption: (questionId: string, optionLabel: string) => void;
- readonly onAdvance: () => void;
- /** The chat's thread and the bot asking, so the prompt can open that bot's computer. */
- readonly threadRef?: ScopedThreadRef | null;
- readonly askingBot?: Pick<Bot, "name" | "sandbox" | "engine"> | null;
+ readonly step: number;
+ readonly onStepChange: (step: number) => void;
+ readonly onSelectOption: (questionId: string, optionLabel: string) => void;
+ readonly onAnswerWithText: (text: string) => void;
+ readonly onSubmit: () => void;
}) {
const { t } = useI18n();
// Once an answer is on its way the question has been dealt with: the composer's working
@@ -48,20 +43,16 @@ export function BotUserInputPrompt({
data-testid="bot-user-input-prompt"
>
<ComposerPendingUserInputPanel
- className="!max-w-none !rounded-none !border-0 !bg-transparent !p-0"
+ surface="docked"
pendingUserInputs={pendingUserInputs}
respondingRequestIds={respondingRequestIds}
answers={answers}
- questionIndex={questionIndex}
- onToggleOption={onToggleOption}
- onSelectSingleOption={onSelectSingleOption}
- onAdvance={onAdvance}
+ step={step}
+ onStepChange={onStepChange}
+ onSelectOption={onSelectOption}
+ onAnswerWithText={onAnswerWithText}
+ onSubmit={onSubmit}
/>
- {askingBot ? (
- <div className="px-3 pb-2">
- <OpenComputerAction threadRef={threadRef} bot={askingBot} />
- </div>
- ) : null}
</section>
);
}
diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsx
index bee5a0910..848bfceb9 100644
--- a/apps/web/src/components/roster/GroupThreadLanding.tsx
+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx
@@ -31,6 +31,7 @@ import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";
import { useOptionalVoiceCall } from "../voice/VoiceCall";
import { threadSilentRun } from "@akeru/client-runtime/silent-run";
import { botActivityUpdate, BotActivityStatus } from "./BotActivityStatus";
+import { ChatReplyContext } from "../markdown/generative/chatReplyContext";
import { deriveBotActivity } from "./botActivityStatus.logic";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
import { MemoryApprovalPrompt } from "./MemoryApprovalPrompt";
@@ -47,6 +48,7 @@ import {
visibleBotChatMessages,
} from "./botConversationPresentation";
import { BotPromptComposer } from "./BotPromptComposer";
+import { useAnsweredUserInputs } from "./useAnsweredUserInputs";
import {
AssistantMessageRow,
type MessageReplyHandler,
@@ -238,6 +240,8 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
[runtime.messages, working],
);
+ const answeredUserInputs = useAnsweredUserInputs(activities, messages);
+
const today = useLocalDay();
const todayLabel = t("Today");
@@ -305,264 +309,293 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
const activeBotById = (id: string) =>
bots.find((candidate) => candidate.id === id && candidate.archivedAt === null) ?? null;
+ const chatReply = {
+ disabled:
+ runtime.sending ||
+ runtime.latestTurn?.state === "running" ||
+ runtime.pendingUserInputs.length > 0 ||
+ pendingApproval !== null ||
+ !runtime.groupReady ||
+ !runtime.providerAvailable,
+ send: (text: string) => runtime.send(text, []),
+ };
+
return (
- <SidebarInset
- tone="foreground"
- aria-label={t("{name} group chat", { name: group.name })}
- className="h-dvh min-h-0 overflow-hidden"
- data-testid="group-thread-landing"
- >
- <div className="flex min-h-0 min-w-0 flex-1 flex-col">
- <WorkspacePageHeader className="border-b border-border" detailsPanelOpen={detailsPanelOpen}>
- <div className="flex min-w-0 items-center gap-2">
- <GroupMemberStack group={group} bots={bots} />
- <span className="truncate text-sm font-medium">{group.name}</span>
- </div>
- <div data-chat-header-actions className="ml-auto flex items-center">
- <ChatActionsMenu threadRef={runtime.linkedThreadRef} />
- </div>
- </WorkspacePageHeader>
- <BotConversationScrollArea
- followKey={messages.findLast((message) => message.role === "user")?.id}
- >
- {timeline.length === 0 ? (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">
- <div className="flex -space-x-3">
- {members.slice(0, 3).map((bot) => (
- <BotAvatarView
- key={bot.id}
- avatar={bot.avatar}
- name={bot.name}
- className="size-14 ring-4 ring-background"
- />
- ))}
- </div>
- <h1 className="text-lg font-medium">
- {boss ? t("Message {name}", { name: group.name }) : t("Group boss unavailable")}
- </h1>
+ <ChatReplyContext value={chatReply}>
+ <SidebarInset
+ tone="foreground"
+ aria-label={t("{name} group chat", { name: group.name })}
+ className="h-dvh min-h-0 overflow-hidden"
+ data-testid="group-thread-landing"
+ >
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <WorkspacePageHeader
+ className="border-b border-border"
+ detailsPanelOpen={detailsPanelOpen}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <GroupMemberStack group={group} bots={bots} />
+ <span className="truncate text-sm font-medium">{group.name}</span>
</div>
- ) : (
- timeline.map((item) => {
- if (Predicate.isTagged(item, "Delegation")) {
- return (
- <DelegationCard
- key={item.key}
- variant="group"
- delegation={item.delegation}
- delegations={delegations}
- childBot={activeBotById(item.delegation.childBotId)}
- parentBot={activeBotById(item.delegation.parentBotId)}
- />
+ <div data-chat-header-actions className="ml-auto flex items-center">
+ <ChatActionsMenu threadRef={runtime.linkedThreadRef} />
+ </div>
+ </WorkspacePageHeader>
+ <BotConversationScrollArea
+ followKey={messages.findLast((message) => message.role === "user")?.id}
+ >
+ {timeline.length === 0 ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">
+ <div className="flex -space-x-3">
+ {members.slice(0, 3).map((bot) => (
+ <BotAvatarView
+ key={bot.id}
+ avatar={bot.avatar}
+ name={bot.name}
+ className="size-14 ring-4 ring-background"
+ />
+ ))}
+ </div>
+ <h1 className="text-lg font-medium">
+ {boss ? t("Message {name}", { name: group.name }) : t("Group boss unavailable")}
+ </h1>
+ </div>
+ ) : (
+ timeline.map((item) => {
+ if (Predicate.isTagged(item, "Delegation")) {
+ return (
+ <DelegationCard
+ key={item.key}
+ variant="group"
+ delegation={item.delegation}
+ delegations={delegations}
+ childBot={activeBotById(item.delegation.childBotId)}
+ parentBot={activeBotById(item.delegation.parentBotId)}
+ />
+ );
+ }
+
+ if (!Predicate.isTagged(item, "Message")) return null;
+ const { message, separator, startsGroup } = item.message.entry;
+
+ if (message.role === "assistant") {
+ const respondingBot = message.respondingBotId
+ ? members.find((bot) => bot.id === message.respondingBotId)
+ : boss;
+
+ return (
+ <Fragment key={message.id}>
+ {separator ? <ConversationSeparator label={separator} /> : null}
+ <AssistantMessageRow
+ message={message}
+ arrived={arrivedMessageIds.has(message.id)}
+ author={respondingBot ?? null}
+ testId="group-provider-message"
+ startsGroup={startsGroup}
+ cwd={runtime.defaultProject?.workspaceRoot}
+ threadRef={runtime.linkedThreadRef ?? undefined}
+ stepMeter={
+ message.turnId === null ? undefined : stepMeters.get(message.turnId)
+ }
+ pluginResults={undefined}
+ currentPersonId={currentPersonId}
+ playback={replyPlayback}
+ playbackKey={playbackKey}
+ channelApproval={null}
+ onReply={replyTo}
+ onReactionChange={updateReaction}
+ />
+ </Fragment>
+ );
+ }
+
+ const current = isCurrentGroupPerson(
+ message.authorPersonId,
+ currentPersonId,
+ peopleIdentity.host?.id,
);
- }
-
- if (!Predicate.isTagged(item, "Message")) return null;
- const { message, separator, startsGroup } = item.message.entry;
-
- if (message.role === "assistant") {
- const respondingBot = message.respondingBotId
- ? members.find((bot) => bot.id === message.respondingBotId)
- : boss;
return (
<Fragment key={message.id}>
{separator ? <ConversationSeparator label={separator} /> : null}
- <AssistantMessageRow
+ <UserMessageRow
message={message}
+ replySourceMessageId={findReplySourceMessageId(
+ messages,
+ item.index,
+ message.text,
+ )}
arrived={arrivedMessageIds.has(message.id)}
- author={respondingBot ?? null}
- testId="group-provider-message"
+ testId="group-user-message"
startsGroup={startsGroup}
- cwd={runtime.defaultProject?.workspaceRoot}
- threadRef={runtime.linkedThreadRef ?? undefined}
- stepMeter={
- message.turnId === null ? undefined : stepMeters.get(message.turnId)
- }
- pluginResults={undefined}
+ replyLabel={current ? "you" : "participant"}
+ showChannelOrigin={false}
+ skills={bossCatalog?.skills}
+ environmentId={environmentId}
currentPersonId={currentPersonId}
- playback={replyPlayback}
- playbackKey={playbackKey}
- channelApproval={null}
+ answered={answeredUserInputs.get(message.id) ?? null}
onReply={replyTo}
onReactionChange={updateReaction}
/>
</Fragment>
);
- }
-
- const current = isCurrentGroupPerson(
- message.authorPersonId,
- currentPersonId,
- peopleIdentity.host?.id,
- );
-
- return (
- <Fragment key={message.id}>
- {separator ? <ConversationSeparator label={separator} /> : null}
- <UserMessageRow
- message={message}
- replySourceMessageId={findReplySourceMessageId(
- messages,
- item.index,
- message.text,
- )}
- arrived={arrivedMessageIds.has(message.id)}
- testId="group-user-message"
- startsGroup={startsGroup}
- replyLabel={current ? "you" : "participant"}
- showChannelOrigin={false}
- skills={bossCatalog?.skills}
- environmentId={environmentId}
- currentPersonId={currentPersonId}
- onReply={replyTo}
- onReactionChange={updateReaction}
- />
- </Fragment>
- );
- })
- )}
- {!working && runtime.turnFailure && messages.at(-1)?.role === "user" ? (
- <BotTurnFailureRow
- botName={activeBot?.name ?? group.name}
- title={presentThreadError(runtime.turnFailure.message, failureContext, t).title}
+ })
+ )}
+ {!working && runtime.turnFailure && messages.at(-1)?.role === "user" ? (
+ <BotTurnFailureRow
+ botName={activeBot?.name ?? group.name}
+ title={presentThreadError(runtime.turnFailure.message, failureContext, t).title}
+ />
+ ) : null}
+ {waitingOnChildren && !working ? (
+ <p className="ml-10 text-xs text-muted-foreground" aria-live="polite">
+ {t("Waiting on delegated work")}
+ </p>
+ ) : null}
+ </BotConversationScrollArea>
+ <BotInboxAlertStack
+ items={inboxItems}
+ onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
+ />
+ <ThreadRuntimeWarningBanner warning={runtimeWarning} />
+ {connectNeeded && connect ? (
+ <ProviderConnectCard
+ id={noProviderNoticeId}
+ environmentId={environmentId}
+ provider={connect.provider}
+ botName={connect.botName}
+ className="mt-2"
/>
) : null}
- {waitingOnChildren && !working ? (
- <p className="ml-10 text-xs text-muted-foreground" aria-live="polite">
- {t("Waiting on delegated work")}
- </p>
- ) : null}
- </BotConversationScrollArea>
- <BotInboxAlertStack
- items={inboxItems}
- onOpenDetails={() => openSettings("advanced", "errors", environmentId)}
- />
- <ThreadRuntimeWarningBanner warning={runtimeWarning} />
- {connectNeeded && connect ? (
- <ProviderConnectCard
- id={noProviderNoticeId}
+ <ThreadErrorBanner
+ threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? group.id}`}
+ error={
+ connectNeeded || inboxItems.some((item) => item.lastFailure === runtime.error)
+ ? null
+ : runtime.error
+ }
+ context={failureContext}
environmentId={environmentId}
- provider={connect.provider}
- botName={connect.botName}
- className="mt-2"
+ {...(runtime.canResume ? { onResume: () => void runtime.resume() } : {})}
+ resuming={runtime.resuming}
/>
- ) : null}
- <ThreadErrorBanner
- threadKey={`${runtime.linkedThreadRef?.environmentId ?? environmentId ?? "unknown"}:${runtime.linkedThreadRef?.threadId ?? group.id}`}
- error={
- connectNeeded || inboxItems.some((item) => item.lastFailure === runtime.error)
- ? null
- : runtime.error
- }
- context={failureContext}
- environmentId={environmentId}
- {...(runtime.canResume ? { onResume: () => void runtime.resume() } : {})}
- resuming={runtime.resuming}
- />
- {boss === null ? (
- <div className="px-4 py-2 text-sm text-muted-foreground" role="status">
- {t("Choose an active group boss in the group sidebar.")}
- </div>
- ) : null}
- <BotPromptComposer
- mentionScope={mentionScope}
- commandCatalog={composerCatalog}
- onAddressedBotChange={setAddressedBotId}
- botName={group.name}
- draftKey={`group:${group.id}`}
- busy={working && pendingApproval === null}
- activitySlot={
- working && activeBot && !waitingForUserInput && pendingApproval === null ? (
- <BotActivityStatus
- name={activeBot.name}
- activity={botActivity}
- update={workingUpdate}
- silentRun={silentRun}
- />
- ) : null
- }
- pendingActionSlot={
- pendingApproval ? (
- <BotApprovalPrompt
- approval={pendingApproval}
- pendingCount={approvalState.pendingCount}
- responding={approvalState.responding}
- error={approvalState.responseError}
- onRespond={async (decision) => {
- const answered = await approvalState.respond(pendingApproval.requestId, decision);
-
- if (answered && decision === "acceptAlways" && boss) {
- await enableAutoReview(boss.id);
- }
-
- return answered;
- }}
- />
- ) : waitingForUserInput ? (
- <BotUserInputPrompt
- pendingUserInputs={runtime.pendingUserInputs}
- respondingRequestIds={runtime.respondingRequestIds}
- answers={runtime.pendingUserInputAnswers}
- questionIndex={runtime.pendingUserInputQuestionIndex}
- onToggleOption={runtime.selectPendingUserInputOption}
- onSelectSingleOption={runtime.selectPendingUserInputOption}
- onAdvance={runtime.advancePendingUserInput}
- threadRef={runtime.linkedThreadRef}
- askingBot={activeBot ?? null}
- />
- ) : memoryApprovals.length > 0 && runtime.linkedThreadRef ? (
- <MemoryApprovalPrompt
- threadRef={runtime.linkedThreadRef}
- approvals={memoryApprovals}
- currentBotId={activeBot?.id ?? null}
- />
- ) : null
- }
- quietSurface={pendingApproval !== null || pendingUserInput !== null}
- {...(waitingForUserInput ? { placeholder: t("Write a custom answer…") } : {})}
- disabled={
- pendingApproval !== null ||
- runtime.respondingRequestIds.length > 0 ||
- !runtime.groupReady ||
- !runtime.bootstrapped ||
- runtime.defaultProject === null ||
- (!waitingForUserInput && !runtime.providerAvailable)
- }
- mentionBots={members.map((bot) => ({
- id: bot.id,
- name: bot.name,
- title: bot.title,
- canTakeWork: botEngineTakesDelegatedWork(bot.engine, respondingEngine.instanceEntries),
- }))}
- replyPreview={replyTarget}
- onCancelReply={() => setReplyTarget(null)}
- sendBlockedDescriptionId={
- runtime.providerAvailable || waitingForUserInput ? undefined : noProviderNoticeId
- }
- onSubmit={async (prompt, files, respondingBotId) => {
- const sent = await runtime.send(
- buildReplyPrompt(replyTarget, prompt),
- files,
- respondingBotId,
- );
-
- if (sent) setReplyTarget(null);
-
- return sent;
- }}
- />
- {!runtime.providerAvailable && !connectNeeded ? (
- <ProviderUnavailableLine
- id={noProviderNoticeId}
- presentation={{
- title: t("No provider is ready for this group"),
- description: t("Connect a provider in Settings > Providers so this group can reply."),
- action: "providers",
+ {boss === null ? (
+ <div className="px-4 py-2 text-sm text-muted-foreground" role="status">
+ {t("Choose an active group boss in the group sidebar.")}
+ </div>
+ ) : null}
+ <BotPromptComposer
+ typeToFocus={!waitingForUserInput}
+ mentionScope={mentionScope}
+ commandCatalog={composerCatalog}
+ onAddressedBotChange={setAddressedBotId}
+ botName={group.name}
+ draftKey={`group:${group.id}`}
+ busy={working && pendingApproval === null}
+ activitySlot={
+ working && activeBot && !waitingForUserInput && pendingApproval === null ? (
+ <BotActivityStatus
+ name={activeBot.name}
+ activity={botActivity}
+ update={workingUpdate}
+ silentRun={silentRun}
+ />
+ ) : null
+ }
+ pendingActionSlot={
+ pendingApproval ? (
+ <BotApprovalPrompt
+ approval={pendingApproval}
+ pendingCount={approvalState.pendingCount}
+ responding={approvalState.responding}
+ error={approvalState.responseError}
+ onRespond={async (decision) => {
+ const answered = await approvalState.respond(
+ pendingApproval.requestId,
+ decision,
+ );
+
+ if (answered && decision === "acceptAlways" && boss) {
+ await enableAutoReview(boss.id);
+ }
+
+ return answered;
+ }}
+ />
+ ) : waitingForUserInput ? (
+ <BotUserInputPrompt
+ pendingUserInputs={runtime.pendingUserInputs}
+ respondingRequestIds={runtime.respondingRequestIds}
+ answers={runtime.pendingUserInputAnswers}
+ step={runtime.pendingUserInputStep}
+ onStepChange={runtime.setPendingUserInputStep}
+ onSelectOption={runtime.selectPendingUserInputOption}
+ onAnswerWithText={(text) => {
+ void runtime.answerPendingUserInputWithText(text);
+ }}
+ onSubmit={() => {
+ void runtime.submitPendingUserInputAnswers();
+ }}
+ />
+ ) : memoryApprovals.length > 0 && runtime.linkedThreadRef ? (
+ <MemoryApprovalPrompt
+ threadRef={runtime.linkedThreadRef}
+ approvals={memoryApprovals}
+ currentBotId={activeBot?.id ?? null}
+ />
+ ) : null
+ }
+ quietSurface={pendingApproval !== null || pendingUserInput !== null}
+ {...(waitingForUserInput ? { placeholder: t("Write a custom answer…") } : {})}
+ disabled={
+ pendingApproval !== null ||
+ runtime.respondingRequestIds.length > 0 ||
+ !runtime.groupReady ||
+ !runtime.bootstrapped ||
+ runtime.defaultProject === null ||
+ (!waitingForUserInput && !runtime.providerAvailable)
+ }
+ mentionBots={members.map((bot) => ({
+ id: bot.id,
+ name: bot.name,
+ title: bot.title,
+ canTakeWork: botEngineTakesDelegatedWork(
+ bot.engine,
+ respondingEngine.instanceEntries,
+ ),
+ }))}
+ replyPreview={replyTarget}
+ onCancelReply={() => setReplyTarget(null)}
+ sendBlockedDescriptionId={
+ runtime.providerAvailable || waitingForUserInput ? undefined : noProviderNoticeId
+ }
+ onSubmit={async (prompt, files, respondingBotId) => {
+ const sent = await runtime.send(
+ buildReplyPrompt(replyTarget, prompt),
+ files,
+ respondingBotId,
+ );
+
+ if (sent) setReplyTarget(null);
+
+ return sent;
}}
- environmentId={environmentId}
/>
- ) : null}
- </div>
- </SidebarInset>
+ {!runtime.providerAvailable && !connectNeeded ? (
+ <ProviderUnavailableLine
+ id={noProviderNoticeId}
+ presentation={{
+ title: t("No provider is ready for this group"),
+ description: t(
+ "Connect a provider in Settings > Providers so this group can reply.",
+ ),
+ action: "providers",
+ }}
+ environmentId={environmentId}
+ />
+ ) : null}
+ </div>
+ </SidebarInset>
+ </ChatReplyContext>
);
}
diff --git a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
index 6482f1af8..4581d20f2 100644
--- a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
+++ b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
@@ -203,9 +203,9 @@ vi.mock("./useBotThreadRuntime", () => ({
respondingRequestIds: [],
pendingUserInputs: mocks.pendingUserInputs,
pendingUserInputAnswers: {},
- pendingUserInputQuestionIndex: 0,
selectPendingUserInputOption: vi.fn(),
- advancePendingUserInput: vi.fn(),
+ answerPendingUserInputWithText: vi.fn(),
+ submitPendingUserInputAnswers: vi.fn(),
messages: mocks.messages,
error: null,
defaultProject: null,
@@ -237,9 +237,9 @@ vi.mock("./useGroupThreadRuntime", () => ({
latestTurn: mocks.latestTurn,
pendingUserInputs: mocks.groupPendingUserInputs,
pendingUserInputAnswers: {},
- pendingUserInputQuestionIndex: 0,
selectPendingUserInputOption: vi.fn(),
- advancePendingUserInput: vi.fn(),
+ answerPendingUserInputWithText: vi.fn(),
+ submitPendingUserInputAnswers: vi.fn(),
send: vi.fn(),
}),
}));
@@ -623,7 +623,8 @@ describe("thread landing delegations", () => {
) as ReactElement<Parameters<typeof BotUserInputPrompt>[0]> | null;
expect(prompt?.props.pendingUserInputs).toEqual(mocks.groupPendingUserInputs);
- expect(prompt?.props.onSelectSingleOption).toBe(prompt?.props.onToggleOption);
+ expect(prompt?.props.onSelectOption).toBeTypeOf("function");
+ expect(prompt?.props.onAnswerWithText).toBeTypeOf("function");
});
it("keeps the active turn's intermediate answer out of the group transcript", () => {
diff --git a/apps/web/src/components/roster/rosterMessagePreview.logic.test.ts b/apps/web/src/components/roster/rosterMessagePreview.logic.test.ts
index 79f71c8ca..d993580c8 100644
--- a/apps/web/src/components/roster/rosterMessagePreview.logic.test.ts
+++ b/apps/web/src/components/roster/rosterMessagePreview.logic.test.ts
@@ -292,3 +292,27 @@ describe("flattenMarkdownPreview", () => {
);
});
});
+
+describe("flattenMarkdownPreview with generative blocks", () => {
+ it("names the block instead of showing its JSON", () => {
+ const markdown = [
+ "Here is the path.",
+ "",
+ "```akeru-flow",
+ '{ "title": "Remote client → session", "nodes": [{ "id": "a", "label": "Client" }], "edges": [] }',
+ "```",
+ ].join("\n");
+
+ expect(flattenMarkdownPreview(markdown)).toBe(
+ "Here is the path. Diagram: Remote client → session",
+ );
+ });
+
+ it("falls back to the kind when the block does not decode", () => {
+ expect(flattenMarkdownPreview('```akeru-chart\n{ "type": \n```')).toBe("Chart");
+ });
+
+ it("keeps ordinary code blocks", () => {
+ expect(flattenMarkdownPreview("```ts\nconst a = 1;\n```")).toBe("const a = 1;");
+ });
+});
diff --git a/apps/web/src/components/roster/rosterMessagePreview.logic.ts b/apps/web/src/components/roster/rosterMessagePreview.logic.ts
index 1b8af9f10..08fb76eed 100644
--- a/apps/web/src/components/roster/rosterMessagePreview.logic.ts
+++ b/apps/web/src/components/roster/rosterMessagePreview.logic.ts
@@ -1,6 +1,10 @@
import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmFromMarkdown } from "mdast-util-gfm";
import { gfm } from "micromark-extension-gfm";
+import {
+ generativeBlockSummary,
+ generativeKindForLanguage,
+} from "../markdown/generative/generativeSchemas";
export interface RosterLastMessage {
text: string;
@@ -260,9 +264,15 @@ function collectPreviewText(node: MarkdownNode, parts: string[]): void {
switch (node.type) {
case "text":
case "inlineCode":
- case "code":
parts.push(node.value);
break;
+ case "code": {
+ // Generative blocks carry JSON; preview them by name instead.
+ const kind = generativeKindForLanguage(node.lang ?? "");
+ parts.push(kind ? ` ${generativeBlockSummary(kind, node.value)} ` : node.value);
+ break;
+ }
+
case "html":
parts.push(visibleHtmlText(node.value));
break;
diff --git a/apps/web/src/components/roster/useAnsweredUserInputs.ts b/apps/web/src/components/roster/useAnsweredUserInputs.ts
new file mode 100644
index 000000000..57a68b580
--- /dev/null
+++ b/apps/web/src/components/roster/useAnsweredUserInputs.ts
@@ -0,0 +1,29 @@
+import type { OrchestrationMessage, OrchestrationThreadActivity } from "@akeru/contracts";
+import {
+ type AnsweredUserInputQuestion,
+ answeredUserInputForMessage,
+ deriveAskedUserInputs,
+} from "@akeru/client-runtime/user-input-answers";
+import { useMemo } from "react";
+
+/** Messages that answer a bot's questions, keyed by message id, so rows can show answer cards. */
+export function useAnsweredUserInputs(
+ activities: ReadonlyArray<OrchestrationThreadActivity>,
+ messages: ReadonlyArray<OrchestrationMessage>,
+): ReadonlyMap<string, ReadonlyArray<AnsweredUserInputQuestion>> {
+ return useMemo(() => {
+ const answeredByMessageId = new Map<string, ReadonlyArray<AnsweredUserInputQuestion>>();
+ const asked = deriveAskedUserInputs(activities);
+
+ if (asked.size === 0) return answeredByMessageId;
+
+ for (const message of messages) {
+ if (message.role !== "user") continue;
+ const answered = answeredUserInputForMessage(message, asked);
+
+ if (answered) answeredByMessageId.set(message.id, answered);
+ }
+
+ return answeredByMessageId;
+ }, [activities, messages]);
+}
diff --git a/apps/web/src/components/roster/useBotComposerKeyboard.ts b/apps/web/src/components/roster/useBotComposerKeyboard.ts
index 0b8e083fb..13865e7b1 100644
--- a/apps/web/src/components/roster/useBotComposerKeyboard.ts
+++ b/apps/web/src/components/roster/useBotComposerKeyboard.ts
@@ -11,12 +11,13 @@ import { shouldFocusBotPromptForKey } from "./botPromptComposer.logic";
*/
export function useBotComposerKeyboard(input: {
readonly readOnly: boolean;
+ readonly typeToFocus: boolean;
readonly keybindings: ResolvedKeybindingsConfig;
readonly promptInputRef: RefObject<HTMLTextAreaElement | null>;
readonly persistDraft: (next: string) => void;
readonly stashCurrentPrompt: () => Promise<void>;
}) {
- const { keybindings, promptInputRef, readOnly, stashCurrentPrompt } = input;
+ const { keybindings, promptInputRef, readOnly, stashCurrentPrompt, typeToFocus } = input;
const persistDraftRef = useRef(input.persistDraft);
persistDraftRef.current = input.persistDraft;
@@ -48,6 +49,7 @@ export function useBotComposerKeyboard(input: {
) !== null;
if (
+ !typeToFocus ||
!shouldFocusBotPromptForKey({
altKey: event.altKey,
ctrlKey: event.ctrlKey,
@@ -69,5 +71,5 @@ export function useBotComposerKeyboard(input: {
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
- }, [keybindings, promptInputRef, readOnly, stashCurrentPrompt]);
+ }, [keybindings, promptInputRef, readOnly, stashCurrentPrompt, typeToFocus]);
}
diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.ts
index df30558bf..1963d1c4b 100644
--- a/apps/web/src/components/roster/useBotThreadRuntime.ts
+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts
@@ -229,11 +229,13 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
const {
pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
+ pendingUserInputStep,
+ setPendingUserInputStep,
respondingRequestIds,
answerPendingUserInputWithPrompt,
+ answerPendingUserInputWithText,
selectPendingUserInputOption,
- advancePendingUserInput,
+ submitPendingUserInputAnswers,
} = useThreadPendingUserInput({ linkedThreadRef, pendingUserInputs, onFailure: setError });
const [resuming, setResuming] = useState(false);
@@ -653,12 +655,14 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
messages,
pendingUserInputs,
pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
+ pendingUserInputStep,
+ setPendingUserInputStep,
respondingRequestIds,
resume,
resuming,
+ answerPendingUserInputWithText,
selectPendingUserInputOption,
- advancePendingUserInput,
+ submitPendingUserInputAnswers,
canStartNewChat,
send,
sendVoiceMessage,
diff --git a/apps/web/src/components/roster/useGroupThreadRuntime.ts b/apps/web/src/components/roster/useGroupThreadRuntime.ts
index 366a431fd..eb6ec4dee 100644
--- a/apps/web/src/components/roster/useGroupThreadRuntime.ts
+++ b/apps/web/src/components/roster/useGroupThreadRuntime.ts
@@ -163,11 +163,13 @@ export function useGroupThreadRuntime(groupId: string) {
const {
pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
+ pendingUserInputStep,
+ setPendingUserInputStep,
respondingRequestIds,
answerPendingUserInputWithPrompt,
+ answerPendingUserInputWithText,
selectPendingUserInputOption,
- advancePendingUserInput,
+ submitPendingUserInputAnswers,
} = useThreadPendingUserInput({ linkedThreadRef, pendingUserInputs, onFailure: setError });
const [resuming, setResuming] = useState(false);
@@ -442,13 +444,15 @@ export function useGroupThreadRuntime(groupId: string) {
messages,
pendingUserInputs,
pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
+ pendingUserInputStep,
+ setPendingUserInputStep,
respondingRequestIds,
respondingBotId: rememberedThread?.respondingBotId ?? group?.bossBotId ?? null,
resume,
resuming,
+ answerPendingUserInputWithText,
selectPendingUserInputOption,
- advancePendingUserInput,
+ submitPendingUserInputAnswers,
send,
sending,
};
diff --git a/apps/web/src/components/roster/useThreadPendingUserInput.ts b/apps/web/src/components/roster/useThreadPendingUserInput.ts
index 0bbfb73e5..b269047b5 100644
--- a/apps/web/src/components/roster/useThreadPendingUserInput.ts
+++ b/apps/web/src/components/roster/useThreadPendingUserInput.ts
@@ -3,10 +3,10 @@ import type { ApprovalRequestId, ScopedThreadRef } from "@akeru/contracts";
import { useCallback, useEffect, useRef, useState } from "react";
import {
- applyPendingUserInputSingleSelect,
+ applyPendingUserInputOptionSelection,
buildPendingUserInputAnswers,
type PendingUserInputDraftAnswer,
- togglePendingUserInputOptionSelection,
+ pendingUserInputStepAfterAnswer,
} from "../../pendingUserInput";
import type { PendingUserInput } from "../../session-logic";
import { threadEnvironment } from "../../state/threads";
@@ -14,9 +14,10 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { type BotThreadFailure, commandFailure } from "./threadRuntimeWarning.logic";
/**
- * Answers the oldest open question in a bot or group chat. Draft answers and the question
- * index reset whenever a different question comes up, and a request id stays marked as
- * responding from the moment its answer is sent until the question leaves the thread.
+ * Answers the oldest open question in a bot or group chat, one question (step) at a time.
+ * Draft answers and the step reset whenever a different prompt comes up, and a request id
+ * stays marked as responding from the moment its answer is sent until the prompt leaves
+ * the thread.
*/
export function useThreadPendingUserInput(input: {
readonly linkedThreadRef: ScopedThreadRef | null;
@@ -31,13 +32,21 @@ export function useThreadPendingUserInput(input: {
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const respondingRequestIdsRef = useRef(new Set<ApprovalRequestId>());
- const singleSelectInFlightRef = useRef<string | null>(null);
const [pendingUserInputAnswers, setPendingUserInputAnswers] = useState<
Record<string, PendingUserInputDraftAnswer>
>({});
- const [pendingUserInputQuestionIndex, setPendingUserInputQuestionIndex] = useState(0);
+ // Picks build on the latest draft, not the one from the last render, so two clicks
+ // handled before React re-renders both count.
+ const answersRef = useRef(pendingUserInputAnswers);
+
+ const setAnswers = useCallback((next: Record<string, PendingUserInputDraftAnswer>) => {
+ answersRef.current = next;
+ setPendingUserInputAnswers(next);
+ }, []);
+
+ const [pendingUserInputStep, setPendingUserInputStep] = useState(0);
const submitPendingUserInput = useCallback(
async (
@@ -69,47 +78,54 @@ export function useThreadPendingUserInput(input: {
);
/**
- * Takes a typed prompt as the custom answer to the current question. Resolves true when
- * it moved on to the next question or sent the answers.
+ * Takes a typed prompt as the custom answer to the current step, then moves on like a
+ * pick would, sending from the last step once every question is answered. Resolves true
+ * when the text was used.
*/
const answerPendingUserInputWithPrompt = useCallback(
async (pendingUserInput: PendingUserInput, prompt: string): Promise<boolean> => {
if (respondingRequestIds.includes(pendingUserInput.requestId)) return false;
- const question = pendingUserInput.questions[pendingUserInputQuestionIndex];
+
+ const { questions } = pendingUserInput;
+ const step = Math.min(pendingUserInputStep, questions.length - 1);
+ const question = questions[step];
if (!question || !prompt.trim()) return false;
const nextAnswers = {
- ...pendingUserInputAnswers,
+ ...answersRef.current,
[question.id]: { customAnswer: prompt.trim() },
};
- setPendingUserInputAnswers(nextAnswers);
+ setAnswers(nextAnswers);
+ const nextStep = pendingUserInputStepAfterAnswer(questions, nextAnswers, step);
- if (pendingUserInputQuestionIndex < pendingUserInput.questions.length - 1) {
- setPendingUserInputQuestionIndex((index) => index + 1);
+ if (nextStep !== null) {
+ setPendingUserInputStep(nextStep);
return true;
}
- const answers = buildPendingUserInputAnswers(pendingUserInput.questions, nextAnswers);
+ const answers = buildPendingUserInputAnswers(questions, nextAnswers);
+
+ return answers ? submitPendingUserInput(pendingUserInput.requestId, answers) : true;
+ },
+ [pendingUserInputStep, respondingRequestIds, setAnswers, submitPendingUserInput],
+ );
- if (!answers) return false;
+ /** Answers the question on screen with text typed into the card's own-answer row. */
+ const answerPendingUserInputWithText = useCallback(
+ (text: string) => {
+ const pending = pendingUserInputs[0];
- return submitPendingUserInput(pendingUserInput.requestId, answers);
+ return pending ? answerPendingUserInputWithPrompt(pending, text) : Promise.resolve(false);
},
- [
- pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
- respondingRequestIds,
- submitPendingUserInput,
- ],
+ [answerPendingUserInputWithPrompt, pendingUserInputs],
);
useEffect(() => {
- setPendingUserInputAnswers({});
- setPendingUserInputQuestionIndex(0);
- singleSelectInFlightRef.current = null;
+ setAnswers({});
+ setPendingUserInputStep(0);
const pendingIds = new Set(pendingUserInputs.map((pending) => pending.requestId));
for (const requestId of respondingRequestIdsRef.current) {
@@ -122,87 +138,44 @@ export function useThreadPendingUserInput(input: {
const selectPendingUserInputOption = useCallback(
(questionId: string, optionLabel: string) => {
const pending = pendingUserInputs[0];
- const question = pending?.questions.find((entry) => entry.id === questionId);
-
- if (!pending || !question) return;
-
- if (!question.multiSelect) {
- const selectionKey = `${pending.requestId}:${questionId}`;
-
- if (singleSelectInFlightRef.current === selectionKey) return;
- const selection = applyPendingUserInputSingleSelect(
- pending.questions,
- pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
- questionId,
- optionLabel,
- );
+ if (!pending || respondingRequestIdsRef.current.has(pending.requestId)) return;
- if (!selection) return;
- singleSelectInFlightRef.current = selectionKey;
- setPendingUserInputAnswers(selection.draftAnswers);
-
- if (!selection.answers) {
- setPendingUserInputQuestionIndex(selection.questionIndex);
-
- return;
- }
-
- void submitPendingUserInput(pending.requestId, selection.answers).then((submitted) => {
- if (!submitted) singleSelectInFlightRef.current = null;
- });
+ const selection = applyPendingUserInputOptionSelection(
+ pending.questions,
+ answersRef.current,
+ questionId,
+ optionLabel,
+ );
- return;
- }
+ if (!selection) return;
+ setAnswers(selection.draftAnswers);
+ setPendingUserInputStep(selection.nextStep);
- setPendingUserInputAnswers((current) => ({
- ...current,
- [questionId]: togglePendingUserInputOptionSelection(
- question,
- current[questionId],
- optionLabel,
- ),
- }));
+ if (selection.answers) void submitPendingUserInput(pending.requestId, selection.answers);
},
- [
- pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
- pendingUserInputs,
- submitPendingUserInput,
- ],
+ [pendingUserInputs, setAnswers, submitPendingUserInput],
);
- const advancePendingUserInput = useCallback(async () => {
+ const submitPendingUserInputAnswers = useCallback(async () => {
const pending = pendingUserInputs[0];
- if (!pending || !linkedThreadRef || respondingRequestIds.includes(pending.requestId)) return;
+ if (!pending) return;
- if (pendingUserInputQuestionIndex < pending.questions.length - 1) {
- setPendingUserInputQuestionIndex((index) => index + 1);
-
- return;
- }
-
- const answers = buildPendingUserInputAnswers(pending.questions, pendingUserInputAnswers);
+ const answers = buildPendingUserInputAnswers(pending.questions, answersRef.current);
if (!answers) return;
await submitPendingUserInput(pending.requestId, answers);
- }, [
- linkedThreadRef,
- pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
- pendingUserInputs,
- respondingRequestIds,
- submitPendingUserInput,
- ]);
+ }, [pendingUserInputs, submitPendingUserInput]);
return {
pendingUserInputAnswers,
- pendingUserInputQuestionIndex,
+ pendingUserInputStep,
+ setPendingUserInputStep,
respondingRequestIds,
answerPendingUserInputWithPrompt,
+ answerPendingUserInputWithText,
selectPendingUserInputOption,
- advancePendingUserInput,
+ submitPendingUserInputAnswers,
};
}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 86e39c084..3048fc404 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -313,6 +313,8 @@
@import "./styles/markdown.css";
+@import "./styles/generative-ui.css";
+
/* Prompt-stash save acknowledgement: the new count fades up from just below
its resting position, once, then stops. One-shot and event-driven (React
remounts the element by key on each stash) — no continuous animation. */
diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts
index ff12bd69e..78c13e35b 100644
--- a/apps/web/src/pendingUserInput.test.ts
+++ b/apps/web/src/pendingUserInput.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vite-plus/test";
import {
- applyPendingUserInputSingleSelect,
+ pendingUserInputKeyAction,
+ applyPendingUserInputOptionSelection,
buildPendingUserInputAnswers,
countAnsweredPendingUserInputQuestions,
- derivePendingUserInputProgress,
findFirstUnansweredPendingUserInputQuestionIndex,
resolvePendingUserInputAnswer,
setPendingUserInputCustomAnswer,
@@ -105,13 +105,14 @@ describe("togglePendingUserInputOptionSelection", () => {
});
});
-describe("applyPendingUserInputSingleSelect", () => {
- it("builds the final answer from the clicked option without waiting for state", () => {
+describe("applyPendingUserInputOptionSelection", () => {
+ const second = { ...singleSelectQuestion, id: "second" };
+
+ it("sends a lone single-select question on click", () => {
expect(
- applyPendingUserInputSingleSelect(
+ applyPendingUserInputOptionSelection(
[singleSelectQuestion],
{},
- 0,
"scope",
"Orchestration-first",
),
@@ -119,22 +120,65 @@ describe("applyPendingUserInputSingleSelect", () => {
draftAnswers: {
scope: { customAnswer: "", selectedOptionLabels: ["Orchestration-first"] },
},
- questionIndex: 0,
answers: { scope: "Orchestration-first" },
+ nextStep: 0,
});
});
- it("advances a multi-question prompt without submitting it early", () => {
- const second = { ...singleSelectQuestion, id: "second" };
+ it("moves to the next step instead of sending, even once every answer is in", () => {
+ const draftAnswers = { second: { selectedOptionLabels: ["Orchestration-first"] } };
+
expect(
- applyPendingUserInputSingleSelect(
+ applyPendingUserInputOptionSelection(
[singleSelectQuestion, second],
- {},
- 0,
+ draftAnswers,
"scope",
"Orchestration-first",
),
- ).toMatchObject({ questionIndex: 1, answers: null });
+ ).toMatchObject({ answers: null, nextStep: 1 });
+ });
+
+ it("sends from the last step once every question is answered", () => {
+ const draftAnswers = { scope: { selectedOptionLabels: ["Orchestration-first"] } };
+
+ expect(
+ applyPendingUserInputOptionSelection(
+ [singleSelectQuestion, second],
+ draftAnswers,
+ "second",
+ "Orchestration-first",
+ ),
+ ).toMatchObject({
+ answers: { scope: "Orchestration-first", second: "Orchestration-first" },
+ });
+ });
+
+ it("returns to the first open step when the last one is answered early", () => {
+ expect(
+ applyPendingUserInputOptionSelection(
+ [singleSelectQuestion, second],
+ {},
+ "second",
+ "Orchestration-first",
+ ),
+ ).toMatchObject({ answers: null, nextStep: 0 });
+ });
+
+ it("keeps a multi-select step open while picks toggle", () => {
+ expect(
+ applyPendingUserInputOptionSelection(
+ [singleSelectQuestion, multiSelectQuestion],
+ {},
+ "areas",
+ multiSelectQuestion.options[0].label,
+ ),
+ ).toMatchObject({ answers: null, nextStep: 1 });
+ });
+
+ it("ignores options the question does not offer", () => {
+ expect(
+ applyPendingUserInputOptionSelection([singleSelectQuestion], {}, "scope", "Nope"),
+ ).toBeNull();
});
});
@@ -238,47 +282,20 @@ describe("pending user input question progress", () => {
}),
).toBe(1);
});
+});
- it("derives the active question and advancement state", () => {
- expect(
- derivePendingUserInputProgress(
- questions,
- {
- scope: {
- selectedOptionLabels: ["Orchestration-first"],
- },
- },
- 0,
- ),
- ).toMatchObject({
- questionIndex: 0,
- activeQuestion: questions[0],
- selectedOptionLabels: ["Orchestration-first"],
- customAnswer: "",
- resolvedAnswer: "Orchestration-first",
- answeredQuestionCount: 1,
- isLastQuestion: false,
- isComplete: false,
- canAdvance: true,
- });
+describe("pendingUserInputKeyAction", () => {
+ it("picks an option by number and starts a typed answer for other characters", () => {
+ expect(pendingUserInputKeyAction("2", 3)).toEqual({ kind: "pick", optionIndex: 1 });
+ expect(pendingUserInputKeyAction("a", 3)).toEqual({ kind: "type" });
+ expect(pendingUserInputKeyAction("H", 3)).toEqual({ kind: "type" });
+ // A number past the last option is part of a typed answer, not a pick.
+ expect(pendingUserInputKeyAction("7", 3)).toEqual({ kind: "type" });
});
- it("treats multi-select questions as answered when they have selected options", () => {
- expect(
- derivePendingUserInputProgress(
- [multiSelectQuestion],
- {
- areas: {
- selectedOptionLabels: ["Server", "Web"],
- },
- },
- 0,
- ),
- ).toMatchObject({
- selectedOptionLabels: ["Server", "Web"],
- resolvedAnswer: ["Server", "Web"],
- canAdvance: true,
- isComplete: true,
- });
+ it("ignores whitespace and named keys", () => {
+ expect(pendingUserInputKeyAction(" ", 3)).toBeNull();
+ expect(pendingUserInputKeyAction("Tab", 3)).toBeNull();
+ expect(pendingUserInputKeyAction("ArrowDown", 3)).toBeNull();
});
});
diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.ts
index 537647645..48a452580 100644
--- a/apps/web/src/pendingUserInput.ts
+++ b/apps/web/src/pendingUserInput.ts
@@ -6,20 +6,6 @@ export interface PendingUserInputDraftAnswer {
customAnswer?: string;
}
-export interface PendingUserInputProgress {
- questionIndex: number;
- activeQuestion: UserInputQuestion | null;
- activeDraft: PendingUserInputDraftAnswer | undefined;
- selectedOptionLabels: string[];
- customAnswer: string;
- resolvedAnswer: string | string[] | null;
- usingCustomAnswer: boolean;
- answeredQuestionCount: number;
- isLastQuestion: boolean;
- isComplete: boolean;
- canAdvance: boolean;
-}
-
function normalizeDraftAnswer(value: string | undefined): string | null {
if (!Predicate.isString(value)) {
return null;
@@ -109,24 +95,45 @@ export function togglePendingUserInputOptionSelection(
};
}
-export interface PendingUserInputSingleSelectResult {
+export interface PendingUserInputSelectionResult {
draftAnswers: Record<string, PendingUserInputDraftAnswer>;
- questionIndex: number;
+ /** Set when the click settles the last step, so the prompt can be sent right away. */
answers: Record<string, string | string[]> | null;
+ /** The step to show after this click. */
+ nextStep: number;
+}
+
+/**
+ * Where the card goes once a step is answered: the next step, or from the last step back to
+ * the first one still open. Returns null when every question is answered on the last step.
+ */
+export function pendingUserInputStepAfterAnswer(
+ questions: ReadonlyArray<UserInputQuestion>,
+ draftAnswers: Record<string, PendingUserInputDraftAnswer>,
+ step: number,
+): number | null {
+ if (step < questions.length - 1) return step + 1;
+
+ if (buildPendingUserInputAnswers(questions, draftAnswers)) return null;
+
+ return findFirstUnansweredPendingUserInputQuestionIndex(questions, draftAnswers);
}
-export function applyPendingUserInputSingleSelect(
+/**
+ * Applies an option click on the current step. A single-choice pick moves to the next step,
+ * and on the last step sends once every question has an answer. Multi-select picks toggle and
+ * wait for Next.
+ */
+export function applyPendingUserInputOptionSelection(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
- questionIndex: number,
questionId: string,
optionLabel: string,
-): PendingUserInputSingleSelectResult | null {
- const question = questions[questionIndex];
+): PendingUserInputSelectionResult | null {
+ const step = questions.findIndex((entry) => entry.id === questionId);
+ const question = questions[step];
- if (!question || question.id !== questionId || question.multiSelect) return null;
-
- if (!question.options.some((option) => option.label === optionLabel)) return null;
+ if (!question || !question.options.some((option) => option.label === optionLabel)) return null;
const nextDraftAnswers = {
...draftAnswers,
@@ -137,15 +144,15 @@ export function applyPendingUserInputSingleSelect(
),
};
- const nextQuestionIndex = Math.min(questionIndex + 1, Math.max(questions.length - 1, 0));
+ if (question.multiSelect)
+ return { draftAnswers: nextDraftAnswers, answers: null, nextStep: step };
+
+ const nextStep = pendingUserInputStepAfterAnswer(questions, nextDraftAnswers, step);
return {
draftAnswers: nextDraftAnswers,
- questionIndex: nextQuestionIndex,
- answers:
- questionIndex === questions.length - 1
- ? buildPendingUserInputAnswers(questions, nextDraftAnswers)
- : null,
+ answers: nextStep === null ? buildPendingUserInputAnswers(questions, nextDraftAnswers) : null,
+ nextStep: nextStep ?? step,
};
}
@@ -188,38 +195,25 @@ export function findFirstUnansweredPendingUserInputQuestionIndex(
return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
}
-export function derivePendingUserInputProgress(
- questions: ReadonlyArray<UserInputQuestion>,
- draftAnswers: Record<string, PendingUserInputDraftAnswer>,
- questionIndex: number,
-): PendingUserInputProgress {
- const normalizedQuestionIndex =
- questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
-
- const activeQuestion = questions[normalizedQuestionIndex] ?? null;
- const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
-
- const resolvedAnswer = activeQuestion
- ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
- : null;
-
- const customAnswer = activeDraft?.customAnswer ?? "";
- const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
-
- const isLastQuestion =
- questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
+export type PendingUserInputKeyAction =
+ | { readonly kind: "pick"; readonly optionIndex: number }
+ | { readonly kind: "type" }
+ | null;
+
+/**
+ * What a plain key press does while a question is on screen. A number picks that option; any
+ * other printable character starts a typed answer, so a sentence typed outside a field never
+ * turns into picks. Whitespace and named keys do nothing here.
+ */
+export function pendingUserInputKeyAction(
+ key: string,
+ optionCount: number,
+): PendingUserInputKeyAction {
+ if (/^[1-9]$/.test(key)) {
+ const optionIndex = Number.parseInt(key, 10) - 1;
+
+ return optionIndex < optionCount ? { kind: "pick", optionIndex } : { kind: "type" };
+ }
- return {
- questionIndex: normalizedQuestionIndex,
- activeQuestion,
- activeDraft,
- selectedOptionLabels: normalizeSelectedOptionLabels(activeDraft?.selectedOptionLabels),
- customAnswer,
- resolvedAnswer,
- usingCustomAnswer: customAnswer.trim().length > 0,
- answeredQuestionCount,
- isLastQuestion,
- isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
- canAdvance: Boolean(resolvedAnswer),
- };
+ return key.length === 1 && key.trim() ? { kind: "type" } : null;
}
diff --git a/apps/web/src/styles/generative-ui.css b/apps/web/src/styles/generative-ui.css
new file mode 100644
index 000000000..5dd55965a
--- /dev/null
+++ b/apps/web/src/styles/generative-ui.css
@@ -0,0 +1,255 @@
+/* Generative chat blocks (```akeru-chart and friends). Series colors derive
+ from theme roles on the block itself, so every app theme restyles them
+ without per-theme values. */
+
+.chat-generative {
+ /* Series step down from the theme accent toward the card, so they work on neutral and tinted themes alike. */
+ --gen-series-1: var(--primary);
+ --gen-series-2: color-mix(in srgb, var(--primary) 62%, var(--card));
+ --gen-series-3: color-mix(in srgb, var(--primary) 38%, var(--card));
+ --gen-series-4: color-mix(in srgb, var(--primary) 20%, var(--card));
+ --gen-grid: color-mix(in srgb, var(--foreground) 7%, transparent);
+ --gen-edge: color-mix(in srgb, var(--foreground) 22%, transparent);
+ --gen-good: var(--success);
+ --gen-warn: var(--warning);
+ --gen-bad: var(--error);
+ --gen-neutral: var(--muted-foreground);
+}
+
+.chat-markdown .chat-generative {
+ margin: 0.85rem 0;
+}
+
+.chat-generative [data-series="0"] {
+ --gen-series: var(--gen-series-1);
+}
+
+.chat-generative [data-series="1"] {
+ --gen-series: var(--gen-series-2);
+}
+
+.chat-generative [data-series="2"] {
+ --gen-series: var(--gen-series-3);
+}
+
+.chat-generative [data-series="3"] {
+ --gen-series: var(--gen-series-4);
+}
+
+.chat-generative [data-tone="good"] {
+ --gen-tone: var(--gen-good);
+}
+
+.chat-generative [data-tone="warn"] {
+ --gen-tone: var(--gen-warn);
+}
+
+.chat-generative [data-tone="bad"] {
+ --gen-tone: var(--gen-bad);
+}
+
+.chat-generative [data-tone="neutral"] {
+ --gen-tone: var(--gen-neutral);
+}
+
+.gen-swatch {
+ background: var(--gen-series);
+}
+
+.gen-tone-text {
+ color: var(--gen-tone);
+}
+
+.gen-tone-dot {
+ background: var(--gen-tone);
+}
+
+.gen-tone-soft {
+ color: var(--gen-tone);
+ background: color-mix(in srgb, var(--gen-tone) 11%, transparent);
+}
+
+.gen-line {
+ fill: none;
+ stroke: var(--gen-series);
+ stroke-width: 2;
+ stroke-linejoin: round;
+ stroke-linecap: round;
+ vector-effect: non-scaling-stroke;
+}
+
+/* Lighter series also change dash pattern, since neutral themes separate them by lightness alone. */
+.chat-generative [data-series="1"] > .gen-line {
+ stroke-dasharray: 6 4;
+}
+
+.chat-generative [data-series="2"] > .gen-line {
+ stroke-dasharray: 2 4;
+}
+
+.chat-generative [data-series="3"] > .gen-line {
+ stroke-dasharray: 8 3 2 3;
+}
+
+.gen-area {
+ fill: var(--gen-series);
+ opacity: 0.12;
+}
+
+.gen-gridline {
+ stroke: var(--gen-grid);
+ stroke-width: 1;
+ vector-effect: non-scaling-stroke;
+}
+
+.gen-bar {
+ background: var(--gen-series);
+ border-radius: 3px 3px 1px 1px;
+}
+
+.gen-crosshair {
+ background: var(--gen-edge);
+}
+
+.gen-edge {
+ fill: none;
+ stroke: var(--gen-edge);
+ stroke-width: 1.25;
+}
+
+[data-highlight="true"] > .gen-edge {
+ stroke: var(--primary);
+ stroke-width: 1.75;
+}
+
+.gen-edge-head {
+ fill: var(--gen-edge);
+}
+
+[data-highlight="true"] > .gen-edge-head {
+ fill: var(--primary);
+}
+
+.gen-flow-node[data-highlight="true"] {
+ border-color: color-mix(in srgb, var(--primary) 45%, var(--border));
+ background: color-mix(in srgb, var(--primary) 6%, var(--card));
+}
+
+.gen-progress-track {
+ background: color-mix(in srgb, var(--foreground) 8%, transparent);
+}
+
+.gen-progress-fill {
+ background: var(--primary);
+}
+
+.gen-rail {
+ background: color-mix(in srgb, var(--foreground) 10%, transparent);
+}
+
+.gen-choice[aria-pressed="true"],
+.gen-choice[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--primary) 55%, var(--border));
+ background: color-mix(in srgb, var(--primary) 7%, var(--card));
+}
+
+/* While the bot can't take a reply, the options step back so they don't look clickable. */
+.gen-choices[data-unavailable="true"] .gen-choice {
+ opacity: 0.55;
+}
+
+/* Once a choice is picked, the others step back, except the row being typed in. */
+.gen-choices[data-answered="true"]
+ .gen-choice:not([aria-pressed="true"], [data-selected="true"], :focus-within) {
+ opacity: 0.55;
+}
+
+/* Small filled check that heads an answered card. */
+.gen-answer-badge {
+ display: inline-grid;
+ place-items: center;
+ width: 0.875rem;
+ height: 0.875rem;
+ border-radius: 999px;
+ background: var(--primary);
+ color: var(--primary-foreground);
+}
+
+/* Selection mark on a choice row: a radio for single-choice questions, a checkbox for multi-select. */
+.gen-mark {
+ display: inline-grid;
+ place-items: center;
+ flex-shrink: 0;
+ width: 1rem;
+ height: 1rem;
+ /* Half-strength ink keeps the empty mark above 3:1 contrast in both modes. */
+ border: 1.5px solid color-mix(in srgb, var(--foreground) 50%, transparent);
+ background: var(--background);
+ color: var(--primary-foreground);
+ transition:
+ background-color 150ms ease-out,
+ border-color 150ms ease-out;
+}
+
+.gen-mark[data-kind="radio"] {
+ border-radius: 999px;
+}
+
+.gen-mark[data-kind="checkbox"] {
+ border-radius: 0.3rem;
+}
+
+.gen-choice:enabled:hover .gen-mark:not([data-checked]) {
+ border-color: color-mix(in srgb, var(--foreground) 72%, transparent);
+}
+
+.gen-mark[data-checked="true"] {
+ border-color: var(--primary);
+ background: var(--primary);
+}
+
+.gen-mark-tick,
+.gen-mark-dot {
+ opacity: 0;
+ transform: scale(0.5);
+ transition:
+ opacity 150ms ease-out,
+ transform 150ms cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+
+.gen-mark-tick {
+ width: 0.7rem;
+ height: 0.7rem;
+}
+
+.gen-mark-dot {
+ width: 0.375rem;
+ height: 0.375rem;
+ border-radius: 999px;
+ background: currentColor;
+}
+
+.gen-mark[data-checked="true"] > .gen-mark-tick,
+.gen-mark[data-checked="true"] > .gen-mark-dot {
+ opacity: 1;
+ transform: scale(1);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .gen-mark-tick,
+ .gen-mark-dot {
+ transform: none;
+ }
+}
+
+.gen-step {
+ background: color-mix(in srgb, var(--foreground) 10%, transparent);
+}
+
+.gen-step[data-state="done"] {
+ background: color-mix(in srgb, var(--primary) 45%, transparent);
+}
+
+.gen-step[data-state="current"] {
+ background: var(--primary);
+}
diff --git a/apps/web/src/styles/theme-tokens.css b/apps/web/src/styles/theme-tokens.css
index 896f92ae3..2a20b846e 100644
--- a/apps/web/src/styles/theme-tokens.css
+++ b/apps/web/src/styles/theme-tokens.css
@@ -46,8 +46,8 @@
--markdown-note-foreground: var(--color-blue-600);
--markdown-tip: var(--color-emerald-500);
--markdown-tip-foreground: var(--color-emerald-600);
- --markdown-important: var(--color-purple-500);
- --markdown-important-foreground: var(--color-purple-600);
+ --markdown-important: var(--color-neutral-500);
+ --markdown-important-foreground: var(--color-neutral-700);
--markdown-warning: var(--color-amber-500);
--markdown-warning-foreground: var(--color-amber-600);
--markdown-caution: var(--color-red-500);
@@ -106,8 +106,8 @@
/* Hover fill for light radio cards; dark mode styles its own hover. */
--option-hover: var(--color-zinc-50);
/* Skill chips and rows. The tint is the same in both modes. */
- --skill: var(--color-fuchsia-500);
- --skill-foreground: var(--color-fuchsia-700);
+ --skill: var(--color-blue-500);
+ --skill-foreground: var(--color-blue-700);
/* Grok mark, near-black on light and near-white on dark. */
--brand-grok: #0f0f0f;
/* Selected and disabled were previously spelled inline at each call site,
@@ -166,7 +166,7 @@
--info-foreground: var(--color-blue-400);
--markdown-note-foreground: var(--color-blue-400);
--markdown-tip-foreground: var(--color-emerald-400);
- --markdown-important-foreground: var(--color-purple-400);
+ --markdown-important-foreground: var(--color-neutral-300);
--markdown-warning-foreground: var(--color-amber-500);
--markdown-caution-foreground: var(--color-red-400);
--telemetry-status-foreground: var(--color-amber-300);
@@ -180,7 +180,7 @@
--telemetry-warning-foreground: var(--color-amber-300);
--telemetry-read-foreground: var(--color-sky-300);
--telemetry-write-foreground: var(--color-amber-300);
- --skill-foreground: var(--color-fuchsia-300);
+ --skill-foreground: var(--color-blue-300);
--brand-grok: #f5f5f5;
--update-foreground: var(--color-blue-400);
--update-surface: color-mix(in srgb, var(--update) 18%, transparent);
diff --git a/apps/web/src/themePalette.built-ins.test.ts b/apps/web/src/themePalette.built-ins.test.ts
index 5683c5120..df81cecfc 100644
--- a/apps/web/src/themePalette.built-ins.test.ts
+++ b/apps/web/src/themePalette.built-ins.test.ts
@@ -77,7 +77,7 @@ describe("built-in palettes", () => {
}
});
- it("keeps the Akeru Paper palette tied to the landing design", () => {
+ it("keeps the Akeru Paper palette neutral and tied to the landing design", () => {
expect(BUILT_IN_THEME_IDS).toContain(AKERU_PAPER_THEME.id);
expect(BUILT_IN_THEMES.map((theme) => theme.id)).toEqual(BUILT_IN_THEME_IDS);
expect(Object.keys(AKERU_PAPER_THEME.colors).sort()).toEqual([...THEME_COLOR_ROLES].sort());
@@ -87,26 +87,32 @@ describe("built-in palettes", () => {
expectThemeColors(AKERU_PAPER_THEME.colors, {
canvas: "#fafaf9",
text: "#1f1e1d",
- accent: "#8b6fc9",
- focus: "#8b6fc9",
- update: "#8b6fc9",
- messageAction: "#8b6fc9",
- terminalCursor: "#8b6fc9",
- messageSurface: "#f0eaf8",
+ accent: "#1f1e1d",
+ focus: "#73716e",
+ update: "#1f1e1d",
+ messageAction: "#1f1e1d",
+ messageSurface: "#ededec",
codeBackground: "#f4f4f3",
sidebar: "#f3f2f1",
});
expectThemeColors(AKERU_PAPER_THEME.variants!.dark!, {
canvas: "#050505",
- text: "#f4f4f5",
- accent: "#8b6fc9",
- focus: "#8b6fc9",
- update: "#8b6fc9",
- messageAction: "#8b6fc9",
- messageSurface: "#3f3f46",
+ text: "#f4f4f4",
+ accent: "#f4f4f4",
+ focus: "#868686",
+ update: "#f4f4f4",
+ messageAction: "#f4f4f4",
+ messageSurface: "#404040",
codeBackground: "#111111",
sidebar: "#111111",
});
+
+ // The terminal stays dark in both appearances, so its cursor must stand out from it.
+ for (const colors of [AKERU_PAPER_THEME.colors, AKERU_PAPER_THEME.variants!.dark!]) {
+ expect(
+ contrastRatio(colors.terminalCursor, colors.terminalBackground),
+ ).toBeGreaterThanOrEqual(4.5);
+ }
});
effectIt.effect("keeps Akeru Paper dark surfaces flat and opaque", () =>
diff --git a/apps/web/src/themeStyles.test.ts b/apps/web/src/themeStyles.test.ts
index 4405ed500..93b729644 100644
--- a/apps/web/src/themeStyles.test.ts
+++ b/apps/web/src/themeStyles.test.ts
@@ -73,8 +73,8 @@ it.effect("preserves nominal indicator and alert colors in both default appearan
["markdown-note-foreground", "blue-600", "blue-400"],
["markdown-tip", "emerald-500", "emerald-500"],
["markdown-tip-foreground", "emerald-600", "emerald-400"],
- ["markdown-important", "purple-500", "purple-500"],
- ["markdown-important-foreground", "purple-600", "purple-400"],
+ ["markdown-important", "neutral-500", "neutral-500"],
+ ["markdown-important-foreground", "neutral-700", "neutral-300"],
["markdown-warning", "amber-500", "amber-500"],
["markdown-warning-foreground", "amber-600", "amber-500"],
["markdown-caution", "red-500", "red-500"],
diff --git a/docs/user/chats.md b/docs/user/chats.md
index 3790a2bea..36b634bdf 100644
--- a/docs/user/chats.md
+++ b/docs/user/chats.md
@@ -209,6 +209,31 @@ as a plain code block without the tinted lines or counts, and checklists do not
summary. Settings chips open the matching mobile screen, or the main Settings screen when mobile
has no matching screen.
+A reply can also include a chart, a row of stats, a task list, a timeline, a flow diagram, or a set
+of choices. These blocks use your theme's colors in light and dark mode. Selecting a choice sends its
+reply to the bot; when the bot cannot take a message yet, the choices stay visible but disabled. If a
+block arrives malformed, the reply shows it as a plain code block. On mobile, these blocks appear as
+plain code blocks.
+
+## Answer a bot's questions
+
+When a bot needs something from you before it continues, its questions appear in a card in the chat,
+one question at a time. In a group chat, the card sits just above the message box. A bar at the top shows how many there are and which one you are on.
+
+- A round mark means you pick one answer. Selecting it moves to the next question, and on the last
+ question it sends your answers.
+- A square mark means you can pick several. Select each one that applies, then select **Next**, or
+ **Submit** on the last question.
+- To answer in your own words, type in **Type your own answer** at the bottom of the card and press
+ Enter. A reply typed in the message box answers the question on screen the same way.
+- **Back** returns to an earlier question with your answers kept.
+
+With a keyboard, number keys pick the options in order and Enter moves on. Typing anything else
+starts your own answer.
+
+After you send, the chat shows a summary of each question with what you picked. An answer you typed
+yourself is marked with a pencil.
+
## When a bot goes quiet
A provider that stops sending output does not stall the chat silently. See
diff --git a/docs/user/computer.md b/docs/user/computer.md
index b3c62d6c4..159295714 100644
--- a/docs/user/computer.md
+++ b/docs/user/computer.md
@@ -5,11 +5,8 @@ live, take control to click and type for the bot, then hand control back.
## Open the computer
-Open the computer from either place. Both show the same screen.
-
-- In a bot chat, open the bot panel and select **Open computer**.
-- When a bot asks you a question, select **Open _bot name_'s computer** under the question. This
- helps when the bot needs you to sign in, solve a check, or confirm something on a page.
+In a bot chat, open the bot panel and select **Open computer**. This helps when the bot needs you to
+sign in, solve a check, or confirm something on a page.
The computer window shows who is in control: the bot, you, someone else, or no one.
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index dab4d21e8..c8fc1ec54 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -40,6 +40,10 @@
"types": "./src/pendingRequests.ts",
"default": "./src/pendingRequests.ts"
},
+ "./user-input-answers": {
+ "types": "./src/userInputAnswers.ts",
+ "default": "./src/userInputAnswers.ts"
+ },
"./markdown-images": {
"types": "./src/markdownImages.ts",
"default": "./src/markdownImages.ts"
diff --git a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
index 64a46f8dc..f21ce214a 100644
--- a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
+++ b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap
@@ -2,7 +2,7 @@
exports[`discovered interface message coverage > covers static calls and finite label sources without translating identifiers 1`] = `
{
- "directMessageCount": 1781,
+ "directMessageCount": 1786,
"expressions": {
"apps/mobile/src/components/DictationControls.tsx": [
"announcements[status]);",
@@ -411,6 +411,7 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/chat/ModelListRow.tsx",
"apps/web/src/components/chat/ModelPickerContent.tsx",
"apps/web/src/components/chat/ModelPickerSidebar.tsx",
+ "apps/web/src/components/chat/PendingUserInputChoices.tsx",
"apps/web/src/components/chat/PluginSearchResultCard.tsx",
"apps/web/src/components/chat/ProviderConnectCard.tsx",
"apps/web/src/components/chat/ProviderModelPicker.tsx",
@@ -423,17 +424,18 @@ exports[`discovered interface message coverage > covers static calls and finite
"apps/web/src/components/chat/ThreadErrorBanner.tsx",
"apps/web/src/components/chat/TraitsMenuContent.tsx",
"apps/web/src/components/chat/TraitsPicker.tsx",
+ "apps/web/src/components/chat/UserInputAnswerCard.tsx",
"apps/web/src/components/chat/chatPaletteActions.ts",
"apps/web/src/components/chat/composerProviderMenuItems.ts",
"apps/web/src/components/chat/traitsPicker.logic.ts",
"apps/web/src/components/computer/ComputerViewerDialog.tsx",
"apps/web/src/components/computer/ComputerViewerPanel.tsx",
- "apps/web/src/components/computer/OpenComputerAction.tsx",
"apps/web/src/components/markdown/MarkdownCodeBlock.tsx",
"apps/web/src/components/markdown/MarkdownFileLink.tsx",
"apps/web/src/components/markdown/MarkdownImages.tsx",
"apps/web/src/components/markdown/MarkdownLists.tsx",
"apps/web/src/components/markdown/MarkdownTable.tsx",
+ "apps/web/src/components/markdown/generative/GenerativeChoices.tsx",
"apps/web/src/components/onboarding/DesktopOnboardingSurface.tsx",
"apps/web/src/components/onboarding/OnboardingGoalStep.tsx",
"apps/web/src/components/onboarding/OnboardingHandoff.tsx",
diff --git a/packages/client-runtime/src/i18n/catalogs/en/common-messages.ts b/packages/client-runtime/src/i18n/catalogs/en/common-messages.ts
index de9916867..826fb6b47 100644
--- a/packages/client-runtime/src/i18n/catalogs/en/common-messages.ts
+++ b/packages/client-runtime/src/i18n/catalogs/en/common-messages.ts
@@ -122,6 +122,12 @@ export const commonMessagesCatalog = {
"Usage unavailable for {name}": "Usage unavailable for {name}",
"Use the computer?": "Use the computer?",
"Write a custom answer…": "Write a custom answer…",
+ "{step} of {total}": "{step} of {total}",
+ "Pick any that apply.": "Pick any that apply.",
+ Recommended: "Recommended",
+ "Type your own answer": "Type your own answer",
+ Answered: "Answered",
+ "Answered {count} questions": "Answered {count} questions",
"{action} {name}": "{action} {name}",
"{label}, elapsed time updating": "{label}, elapsed time updating",
"An optional role, such as research, marketing, or admin.":
@@ -230,7 +236,6 @@ export const commonMessagesCatalog = {
"Click, type, paste, and scroll on the picture. Control lasts up to one minute, then the computer stops.":
"Click, type, paste, and scroll on the picture. Control lasts up to one minute, then the computer stops.",
"{name}'s computer": "{name}'s computer",
- "Open {name}'s computer": "Open {name}'s computer",
"API key saved · {baseUrl}": "API key saved · {baseUrl}",
"Plus, Pro, Business, Enterprise, or Edu": "Plus, Pro, Business, Enterprise, or Edu",
"Rendering diagram…": "Rendering diagram…",
diff --git a/packages/client-runtime/src/i18n/catalogs/zh-CN/common-messages.ts b/packages/client-runtime/src/i18n/catalogs/zh-CN/common-messages.ts
index e172e5454..6a5db9baf 100644
--- a/packages/client-runtime/src/i18n/catalogs/zh-CN/common-messages.ts
+++ b/packages/client-runtime/src/i18n/catalogs/zh-CN/common-messages.ts
@@ -114,6 +114,12 @@ export const commonMessagesCatalog = {
"Usage unavailable for {name}": "{name} 的用量不可用",
"Use the computer?": "使用电脑?",
"Write a custom answer…": "输入自定义回答…",
+ "{step} of {total}": "第 {step} 题,共 {total} 题",
+ "Pick any that apply.": "可多选。",
+ Recommended: "推荐",
+ "Type your own answer": "输入你自己的回答",
+ Answered: "已回答",
+ "Answered {count} questions": "已回答 {count} 个问题",
"{action} {name}": "{action} {name}",
"{label}, elapsed time updating": "{label},已用时间持续更新",
"An optional role, such as research, marketing, or admin.": "可选的角色,例如研究、营销或管理。",
@@ -217,7 +223,6 @@ export const commonMessagesCatalog = {
"Click, type, paste, and scroll on the picture. Control lasts up to one minute, then the computer stops.":
"在画面上点击、输入、粘贴和滚动。控制最长持续一分钟,之后电脑会停止。",
"{name}'s computer": "{name} 的电脑",
- "Open {name}'s computer": "打开 {name} 的电脑",
"API key saved · {baseUrl}": "已保存 API 密钥 · {baseUrl}",
"Plus, Pro, Business, Enterprise, or Edu": "Plus、Pro、Business、Enterprise 或 Edu",
"Rendering diagram…": "正在渲染图表…",
diff --git a/packages/client-runtime/src/pendingRequests.ts b/packages/client-runtime/src/pendingRequests.ts
index 37bc23b22..98e58d2e5 100644
--- a/packages/client-runtime/src/pendingRequests.ts
+++ b/packages/client-runtime/src/pendingRequests.ts
@@ -96,7 +96,8 @@ function parseQuestionArray(value: ReadonlyArray<Schema.Unknown["Type"]>): UserI
return parsed;
}
-const parseQuestions = flow(
+/** Reads a `user-input.requested` payload's questions, dropping malformed ones. */
+export const parseQuestions = flow(
decodeQuestionsArray,
Option.match({ onNone: () => [], onSome: parseQuestionArray }),
);
diff --git a/packages/client-runtime/src/userInputAnswers.test.ts b/packages/client-runtime/src/userInputAnswers.test.ts
new file mode 100644
index 000000000..f52284513
--- /dev/null
+++ b/packages/client-runtime/src/userInputAnswers.test.ts
@@ -0,0 +1,128 @@
+import { EventId, type OrchestrationThreadActivity } from "@akeru/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { answeredUserInputForMessage, deriveAskedUserInputs } from "./userInputAnswers.ts";
+
+const questions = [
+ {
+ id: "audience",
+ header: "Audience",
+ question: "Who is this for?",
+ multiSelect: false,
+ options: [
+ { label: "New developers", description: "First week" },
+ { label: "Existing users", description: "Upgrading" },
+ ],
+ },
+ {
+ id: "features",
+ header: "Features",
+ question: "What should it cover?",
+ multiSelect: true,
+ options: [
+ { label: "Chat blocks", description: "Charts and cards" },
+ { label: "Sign in", description: "No CLIs" },
+ { label: "Channels", description: "Slack and Telegram" },
+ ],
+ },
+];
+
+function activity(
+ kind: string,
+ payload: OrchestrationThreadActivity["payload"],
+): OrchestrationThreadActivity {
+ return {
+ id: EventId.make(`${kind}-activity`),
+ createdAt: "2026-10-02T00:00:00.000Z",
+ kind,
+ summary: kind,
+ tone: "info",
+ payload,
+ turnId: null,
+ };
+}
+
+const requested = activity("user-input.requested", { requestId: "req-1", questions });
+
+const messageId = "user-input:thread-1:req-1";
+
+describe("answeredUserInputForMessage", () => {
+ it("pairs one answer line per question", () => {
+ const asked = deriveAskedUserInputs([requested]);
+
+ const answered = answeredUserInputForMessage(
+ { id: messageId, text: "New developers\nChannels" },
+ asked,
+ );
+
+ expect(answered?.map(({ question, answers }) => [question.id, answers])).toEqual([
+ ["audience", ["New developers"]],
+ ["features", ["Channels"]],
+ ]);
+ });
+
+ it("waits for confirmed answers when lines could belong to more than one question", () => {
+ const asked = deriveAskedUserInputs([requested]);
+
+ // Two multi-select picks, or a typed first answer whose second line is an option label.
+ expect(
+ answeredUserInputForMessage(
+ { id: messageId, text: "New developers\nChat blocks\nChannels" },
+ asked,
+ ),
+ ).toBeNull();
+
+ expect(
+ answeredUserInputForMessage(
+ { id: messageId, text: "Designers\nChat blocks\nChannels" },
+ asked,
+ ),
+ ).toBeNull();
+ });
+
+ it("prefers the answers the provider confirmed", () => {
+ const asked = deriveAskedUserInputs([
+ requested,
+ activity("user-input.resolved", {
+ requestId: "req-1",
+ answers: { audience: "Teams", features: ["Sign in"] },
+ }),
+ ]);
+
+ const answered = answeredUserInputForMessage({ id: messageId, text: "ignored" }, asked);
+
+ expect(answered?.map(({ answers }) => answers)).toEqual([["Teams"], ["Sign in"]]);
+ });
+
+ it("keeps a typed answer for a question", () => {
+ const asked = deriveAskedUserInputs([requested]);
+
+ const answered = answeredUserInputForMessage(
+ { id: messageId, text: "Designers\nSomething custom" },
+ asked,
+ );
+
+ expect(answered?.map(({ answers }) => answers)).toEqual([["Designers"], ["Something custom"]]);
+ });
+
+ it("shows the plain message rather than guess when a typed answer spans lines", () => {
+ const asked = deriveAskedUserInputs([requested]);
+
+ // "Designers\nand PMs" answers the first question; the extra line cannot be placed.
+ expect(
+ answeredUserInputForMessage({ id: messageId, text: "Designers\nand PMs\nChannels" }, asked),
+ ).toBeNull();
+ });
+
+ it("falls back to text when lines do not line up or the message is ordinary", () => {
+ const asked = deriveAskedUserInputs([requested]);
+
+ expect(answeredUserInputForMessage({ id: messageId, text: "Only one" }, asked)).toBeNull();
+ expect(
+ answeredUserInputForMessage({ id: "message-1", text: "New developers" }, asked),
+ ).toBeNull();
+ expect(
+ answeredUserInputForMessage({ id: "user-input:thread-1:req-other", text: "x\ny" }, asked),
+ ).toBeNull();
+ });
+});
diff --git a/packages/client-runtime/src/userInputAnswers.ts b/packages/client-runtime/src/userInputAnswers.ts
new file mode 100644
index 000000000..53ecd97d0
--- /dev/null
+++ b/packages/client-runtime/src/userInputAnswers.ts
@@ -0,0 +1,132 @@
+import type { OrchestrationThreadActivity, UserInputQuestion } from "@akeru/contracts";
+import * as Option from "effect/Option";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+
+import { parseQuestions } from "./pendingRequests.ts";
+
+export interface AnsweredUserInputQuestion {
+ readonly question: UserInputQuestion;
+ readonly answers: ReadonlyArray<string>;
+}
+
+export interface AskedUserInput {
+ readonly questions: ReadonlyArray<UserInputQuestion>;
+ /** Answers the provider confirmed, keyed by question id. Null until it does. */
+ readonly resolvedAnswers: ReadonlyMap<string, ReadonlyArray<string>> | null;
+}
+
+const ANSWER_MESSAGE_PREFIX = "user-input:";
+
+const ResolvedAnswers = Schema.Record(
+ Schema.String,
+ Schema.Union([Schema.String, Schema.Array(Schema.String)]),
+);
+
+const decodeResolvedAnswers = Schema.decodeUnknownOption(ResolvedAnswers);
+
+/** Trims each answer and flattens multi-select picks. */
+function trimResolvedAnswers(answers: typeof ResolvedAnswers.Type): Map<string, string[]> {
+ return new Map(
+ Object.entries(answers).map(([questionId, value]) => [
+ questionId,
+ [value]
+ .flat()
+ .map((entry) => entry.trim())
+ .filter(Boolean),
+ ]),
+ );
+}
+
+/** Every question set a bot asked in this thread, keyed by request id. */
+export function deriveAskedUserInputs(
+ activities: ReadonlyArray<OrchestrationThreadActivity>,
+): ReadonlyMap<string, AskedUserInput> {
+ const asked = new Map<string, AskedUserInput>();
+
+ for (const activity of activities) {
+ const payload = activity.payload;
+
+ if (!Predicate.isObject(payload) || !Predicate.isString(payload.requestId)) continue;
+
+ if (activity.kind === "user-input.requested") {
+ const questions = parseQuestions(payload.questions);
+
+ if (questions.length > 0) asked.set(payload.requestId, { questions, resolvedAnswers: null });
+ } else if (activity.kind === "user-input.resolved") {
+ const existing = asked.get(payload.requestId);
+
+ if (existing) {
+ asked.set(payload.requestId, {
+ ...existing,
+ resolvedAnswers: Option.match(decodeResolvedAnswers(payload.answers), {
+ onNone: () => null,
+ onSome: trimResolvedAnswers,
+ }),
+ });
+ }
+ }
+ }
+
+ return asked;
+}
+
+/**
+ * Pairs a submitted answer with the questions it answers. The server records the answer as a
+ * user message with id `user-input:<threadId>:<requestId>` whose text is every answer on its own
+ * line, so channels and older clients still read it as text. Returns null for any other message,
+ * or when the answers no longer line up with the questions.
+ */
+export function answeredUserInputForMessage(
+ message: { readonly id: string; readonly text: string },
+ asked: ReadonlyMap<string, AskedUserInput>,
+): ReadonlyArray<AnsweredUserInputQuestion> | null {
+ if (!message.id.startsWith(ANSWER_MESSAGE_PREFIX)) return null;
+
+ for (const [requestId, request] of asked) {
+ if (!message.id.endsWith(`:${requestId}`)) continue;
+
+ return (
+ answersFromResolved(request.questions, request.resolvedAnswers) ??
+ answersFromText(request.questions, message.text)
+ );
+ }
+
+ return null;
+}
+
+function answersFromResolved(
+ questions: ReadonlyArray<UserInputQuestion>,
+ resolved: ReadonlyMap<string, ReadonlyArray<string>> | null,
+): AnsweredUserInputQuestion[] | null {
+ if (!resolved) return null;
+ const paired: AnsweredUserInputQuestion[] = [];
+
+ for (const question of questions) {
+ const answers = resolved.get(question.id) ?? [];
+
+ if (answers.length === 0) return null;
+ paired.push({ question, answers });
+ }
+
+ return paired;
+}
+
+/**
+ * Reads one answer line per question. Several multi-select picks or a typed answer that spans
+ * lines cannot be told apart in plain text, so any other line count returns null and the message
+ * stays plain until the provider's confirmed answers arrive.
+ */
+function answersFromText(
+ questions: ReadonlyArray<UserInputQuestion>,
+ text: string,
+): AnsweredUserInputQuestion[] | null {
+ const lines = text
+ .split("\n")
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+ if (lines.length !== questions.length) return null;
+
+ return questions.map((question, index) => ({ question, answers: [lines[index] ?? ""] }));
+}
diff --git a/packages/shared/src/themes/akeru-noir.ts b/packages/shared/src/themes/akeru-noir.ts
index 55628837e..281dd766f 100644
--- a/packages/shared/src/themes/akeru-noir.ts
+++ b/packages/shared/src/themes/akeru-noir.ts
@@ -2,7 +2,7 @@ import { type ThemeDefinition } from "./types.ts";
/**
* The Grok Bot-inspired flagship chassis: neutral near-black surfaces with
- * pill-shaped controls and the Akeru purple reserved for actions and focus.
+ * pill-shaped controls and the text color reserved for actions and focus.
*/
export const AKERU_NOIR_THEME: ThemeDefinition = {
id: "akeru-noir",
@@ -24,9 +24,9 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
textMuted: "oklch(0.55 0.012 285.938)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.87 0.005 286.32)",
- focus: "oklch(0.607447 0.134946 296.512)",
- accent: "oklch(0.607447 0.134946 296.512)",
- accentForeground: "oklch(0.139671 0.024718 296.562)",
+ focus: "oklch(0.55 0.012 285.938)",
+ accent: "oklch(0.21 0.006 285.885)",
+ accentForeground: "oklch(0.99 0.001 286.375)",
secondary: "oklch(0.945 0.003 286.32)",
secondaryForeground: "oklch(0.21 0.006 285.885)",
muted: "oklch(0.955 0.0025 286.32)",
@@ -40,16 +40,16 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
warning: "oklch(0.566615 0.126823 65.303)",
warningForeground: "oklch(0.442827 0.097381 67.7)",
warningSurface: "oklch(0.943016 0.035404 85.408)",
- update: "oklch(0.607447 0.134946 296.512)",
- updateForeground: "oklch(0.449304 0.145439 295.863)",
- updateSurface: "oklch(0.940347 0.022271 302.929)",
+ update: "oklch(0.21 0.006 285.885)",
+ updateForeground: "oklch(0.21 0.006 285.885)",
+ updateSurface: "oklch(0.945 0.003 286.32)",
accentSurface: "oklch(0.945 0.003 286.32)",
accentSurfaceForeground: "oklch(0.21 0.006 285.885)",
messageSurface: "oklch(0.94 0.004 286.32)",
messageForeground: "oklch(0.21 0.006 285.885)",
- messageAction: "oklch(0.607447 0.134946 296.512)",
- messageActionForeground: "oklch(0.139671 0.024718 296.562)",
- messageActionHover: "oklch(0.656453 0.13742 297.344)",
+ messageAction: "oklch(0.21 0.006 285.885)",
+ messageActionForeground: "oklch(0.99 0.001 286.375)",
+ messageActionHover: "oklch(0.3 0.006 285.885)",
codeBackground: "oklch(0.965 0.002 286.32)",
codeForeground: "oklch(0.21 0.006 285.885)",
sidebar: "oklch(0.975 0.0015 286.375)",
@@ -62,8 +62,8 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
sidebarBorder: "oklch(0.92 0.003 286.32)",
terminalBackground: "oklch(0.99 0.001 286.375)",
terminalForeground: "oklch(0.21 0.006 285.885)",
- terminalCursor: "oklch(0.607447 0.134946 296.512)",
- terminalSelection: "oklch(0.912658 0.033973 304.531)",
+ terminalCursor: "oklch(0.21 0.006 285.885)",
+ terminalSelection: "oklch(0.9 0.004 286.32)",
terminalScrollbar: "oklch(0.83 0.004 286.32)",
terminalScrollbarHover: "oklch(0.75 0.005 286.32)",
},
@@ -84,9 +84,9 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
textMuted: "oklch(0.594 0.008 286.067)",
border: "oklch(0.235 0 0)",
input: "oklch(0.3 0 0)",
- focus: "oklch(0.607447 0.134946 296.512)",
- accent: "oklch(0.607447 0.134946 296.512)",
- accentForeground: "oklch(0.14 0.0247 296.562)",
+ focus: "oklch(0.62 0 0)",
+ accent: "oklch(0.97 0.0013 286.375)",
+ accentForeground: "oklch(0.16 0 0)",
secondary: "oklch(0.225 0 0)",
secondaryForeground: "oklch(0.97 0.0013 286.375)",
muted: "oklch(0.19 0 0)",
@@ -100,16 +100,16 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
warning: "oklch(0.758152 0.10943 78.772)",
warningForeground: "oklch(0.855925 0.082896 82.001)",
warningSurface: "oklch(0.309837 0.024833 79.663)",
- update: "oklch(0.607447 0.134946 296.512)",
- updateForeground: "oklch(0.80327 0.077482 299.92)",
- updateSurface: "oklch(0.269917 0.050751 301.875)",
+ update: "oklch(0.97 0.0013 286.375)",
+ updateForeground: "oklch(0.97 0.0013 286.375)",
+ updateSurface: "oklch(0.235 0 0)",
accentSurface: "oklch(0.235 0 0)",
accentSurfaceForeground: "oklch(0.97 0.0013 286.375)",
messageSurface: "oklch(0.25 0 0)",
messageForeground: "oklch(0.97 0.0013 286.375)",
- messageAction: "oklch(0.607447 0.134946 296.512)",
- messageActionForeground: "oklch(0.139671 0.024718 296.562)",
- messageActionHover: "oklch(0.656453 0.13742 297.344)",
+ messageAction: "oklch(0.97 0.0013 286.375)",
+ messageActionForeground: "oklch(0.16 0 0)",
+ messageActionHover: "oklch(0.88 0 0)",
codeBackground: "oklch(0.145 0 0)",
codeForeground: "oklch(0.97 0.0013 286.375)",
sidebar: "oklch(0.135 0 0)",
@@ -122,8 +122,8 @@ export const AKERU_NOIR_THEME: ThemeDefinition = {
sidebarBorder: "oklch(0.215 0 0)",
terminalBackground: "oklch(0.105 0 0)",
terminalForeground: "oklch(0.97 0.0013 286.375)",
- terminalCursor: "oklch(0.607447 0.134946 296.512)",
- terminalSelection: "oklch(0.358238 0.073841 303.758)",
+ terminalCursor: "oklch(0.97 0.0013 286.375)",
+ terminalSelection: "oklch(0.36 0 0)",
terminalScrollbar: "oklch(0.27 0 0)",
terminalScrollbarHover: "oklch(0.4 0 0)",
},
diff --git a/packages/shared/src/themes/akeru-paper.ts b/packages/shared/src/themes/akeru-paper.ts
index 1f429b6bf..00088333a 100644
--- a/packages/shared/src/themes/akeru-paper.ts
+++ b/packages/shared/src/themes/akeru-paper.ts
@@ -20,9 +20,9 @@ export const AKERU_PAPER_THEME: ThemeDefinition = {
textMuted: "oklch(0.505 0.005 70)",
border: "oklch(0.915 0.002 85)",
input: "oklch(0.87 0.003 85)",
- focus: "oklch(0.607447 0.134946 296.512)",
- accent: "oklch(0.607447 0.134946 296.512)",
- accentForeground: "oklch(0.139671 0.024718 296.562)",
+ focus: "oklch(0.55 0.005 70)",
+ accent: "oklch(0.235 0.003 70)",
+ accentForeground: "oklch(0.985 0.0015 85)",
secondary: "oklch(0.953 0.0015 85)",
secondaryForeground: "oklch(0.27 0.004 70)",
muted: "oklch(0.965 0.0012 85)",
@@ -36,16 +36,16 @@ export const AKERU_PAPER_THEME: ThemeDefinition = {
warning: "oklch(0.566615 0.126823 65.303)",
warningForeground: "oklch(0.442827 0.097381 67.7)",
warningSurface: "oklch(0.955 0.03 85)",
- update: "oklch(0.607447 0.134946 296.512)",
- updateForeground: "oklch(0.449304 0.145439 295.863)",
- updateSurface: "oklch(0.940347 0.022271 302.929)",
+ update: "oklch(0.235 0.003 70)",
+ updateForeground: "oklch(0.235 0.003 70)",
+ updateSurface: "oklch(0.95 0.0015 85)",
accentSurface: "oklch(0.95 0.0015 85)",
accentSurfaceForeground: "oklch(0.235 0.003 70)",
- messageSurface: "oklch(0.945777 0.019688 305.262)",
+ messageSurface: "oklch(0.945 0.0015 85)",
messageForeground: "oklch(0.235 0.003 70)",
- messageAction: "oklch(0.607447 0.134946 296.512)",
- messageActionForeground: "oklch(0.139671 0.024718 296.562)",
- messageActionHover: "oklch(0.656453 0.13742 297.344)",
+ messageAction: "oklch(0.235 0.003 70)",
+ messageActionForeground: "oklch(0.985 0.0015 85)",
+ messageActionHover: "oklch(0.33 0.004 70)",
codeBackground: "oklch(0.967 0.0015 85)",
codeForeground: "oklch(0.235 0.003 70)",
sidebar: "oklch(0.962 0.0015 85)",
@@ -58,8 +58,9 @@ export const AKERU_PAPER_THEME: ThemeDefinition = {
sidebarBorder: "oklch(0.915 0.002 85)",
terminalBackground: "oklch(0.249565 0.003571 48.579)",
terminalForeground: "oklch(0.950015 0.011492 84.579)",
- terminalCursor: "oklch(0.607447 0.134946 296.512)",
- terminalSelection: "oklch(0.912658 0.033973 304.531)",
+ // The light theme keeps a dark terminal, so the cursor and selection follow its text.
+ terminalCursor: "oklch(0.950015 0.011492 84.579)",
+ terminalSelection: "oklch(0.4 0.006 70)",
terminalScrollbar: "oklch(0.459577 0.01156 72.528)",
terminalScrollbarHover: "oklch(0.551879 0.013009 71.789)",
},
@@ -68,58 +69,58 @@ export const AKERU_PAPER_THEME: ThemeDefinition = {
canvas: "oklch(0.114918 0 0)",
chrome: "oklch(0.177638 0 0)",
toolbar: "oklch(0.114918 0 0)",
- toolbarForeground: "oklch(0.967434 0.001326 286.375)",
+ toolbarForeground: "oklch(0.967 0 0)",
toolbarBorder: "oklch(0.28908 0 0)",
toolbarControl: "oklch(0.222129 0 0)",
- toolbarControlForeground: "oklch(0.967434 0.001326 286.375)",
+ toolbarControlForeground: "oklch(0.967 0 0)",
toolbarControlHover: "oklch(0.268618 0 0)",
surface: "oklch(0.209036 0 0)",
surfaceRaised: "oklch(0.305191 0 0)",
surfaceOverlay: "oklch(0.177638 0 0)",
- text: "oklch(0.967434 0.001326 286.375)",
- textMuted: "oklch(0.711815 0.012937 286.067)",
+ text: "oklch(0.967 0 0)",
+ textMuted: "oklch(0.712 0 0)",
border: "oklch(0.28908 0 0)",
- input: "oklch(0.370323 0.01188 285.805)",
- focus: "oklch(0.607447 0.134946 296.512)",
- accent: "oklch(0.607447 0.134946 296.512)",
- accentForeground: "oklch(0.139671 0.024718 296.562)",
+ input: "oklch(0.37 0 0)",
+ focus: "oklch(0.62 0 0)",
+ accent: "oklch(0.967 0 0)",
+ accentForeground: "oklch(0.16 0 0)",
secondary: "oklch(0.268618 0 0)",
- secondaryForeground: "oklch(0.967434 0.001326 286.375)",
+ secondaryForeground: "oklch(0.967 0 0)",
muted: "oklch(0.222129 0 0)",
- mutedForeground: "oklch(0.711815 0.012937 286.067)",
- placeholder: "oklch(0.711815 0.012937 286.067)",
- secondaryLabel: "oklch(0.711815 0.012937 286.067)",
- iconMuted: "oklch(0.711815 0.012937 286.067)",
+ mutedForeground: "oklch(0.712 0 0)",
+ placeholder: "oklch(0.712 0 0)",
+ secondaryLabel: "oklch(0.712 0 0)",
+ iconMuted: "oklch(0.712 0 0)",
error: "oklch(0.665241 0.148078 26.77)",
errorForeground: "oklch(0.772758 0.103326 25.58)",
errorSurface: "oklch(0.289862 0.032452 25.297)",
warning: "oklch(0.758152 0.10943 78.772)",
warningForeground: "oklch(0.855925 0.082896 82.001)",
warningSurface: "oklch(0.309837 0.024833 79.663)",
- update: "oklch(0.607447 0.134946 296.512)",
- updateForeground: "oklch(0.80327 0.077482 299.92)",
- updateSurface: "oklch(0.269917 0.050751 301.875)",
+ update: "oklch(0.967 0 0)",
+ updateForeground: "oklch(0.967 0 0)",
+ updateSurface: "oklch(0.268618 0 0)",
accentSurface: "oklch(0.268618 0 0)",
- accentSurfaceForeground: "oklch(0.967434 0.001326 286.375)",
- messageSurface: "oklch(0.370323 0.01188 285.805)",
- messageForeground: "oklch(0.967434 0.001326 286.375)",
- messageAction: "oklch(0.607447 0.134946 296.512)",
- messageActionForeground: "oklch(0.139671 0.024718 296.562)",
- messageActionHover: "oklch(0.656453 0.13742 297.344)",
+ accentSurfaceForeground: "oklch(0.967 0 0)",
+ messageSurface: "oklch(0.37 0 0)",
+ messageForeground: "oklch(0.967 0 0)",
+ messageAction: "oklch(0.967 0 0)",
+ messageActionForeground: "oklch(0.16 0 0)",
+ messageActionHover: "oklch(0.88 0 0)",
codeBackground: "oklch(0.177638 0 0)",
- codeForeground: "oklch(0.967434 0.001326 286.375)",
+ codeForeground: "oklch(0.967 0 0)",
sidebar: "oklch(0.177638 0 0)",
- sidebarForeground: "oklch(0.967434 0.001326 286.375)",
- sidebarMutedForeground: "oklch(0.711815 0.012937 286.067)",
+ sidebarForeground: "oklch(0.967 0 0)",
+ sidebarMutedForeground: "oklch(0.712 0 0)",
sidebarControlSurface: "oklch(0.222129 0 0)",
sidebarRowHover: "oklch(0.243535 0 0)",
sidebarRowActive: "oklch(0.268618 0 0)",
sidebarRowSelected: "oklch(0.28908 0 0)",
sidebarBorder: "oklch(0.28908 0 0)",
terminalBackground: "oklch(0.114918 0 0)",
- terminalForeground: "oklch(0.967434 0.001326 286.375)",
- terminalCursor: "oklch(0.656453 0.13742 297.344)",
- terminalSelection: "oklch(0.358238 0.073841 303.758)",
+ terminalForeground: "oklch(0.967 0 0)",
+ terminalCursor: "oklch(0.967 0 0)",
+ terminalSelection: "oklch(0.36 0 0)",
terminalScrollbar: "oklch(0.321093 0 0)",
terminalScrollbarHover: "oklch(0.4 0 0)",
},