Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Inbox panel: a tab, three-line rows, and a line answered where it is read
milind-soni32ce49f1bead
diff --git a/docs/verification/inbox.md b/docs/verification/inbox.mdindex a9c5963b9b..3c48ad5e86 100644--- a/docs/verification/inbox.md+++ b/docs/verification/inbox.md@@ -15,10 +15,22 @@ left behind reaches the owner labelled, with its news kept away.pnpm exec vitest run server/place-inbox.e2e.test.ts```+## The panel++`src/components/inbox/InboxReading.dom.test.ts` drives the panel as a tab: its count and close, three-line rows with a+question's choices and the recommended one marked, the search, a line read in full with "n of m" and its steps, the bot's+words before it drawn as the chat's Markdown, and a question answered with its choice cards, a number key and a note through+`/api/threads/<id>/respond`, after which the next line opens, or the list when none is left. A password or a sign-in is keyed+by its own card kind and answered with the chat's own card for it.++```sh+pnpm exec vitest run src/components/inbox/InboxReading.dom.test.ts src/components/inbox/InboxPanel.dom.test.ts src/components/inbox/InboxEverywhere.dom.test.ts+```+## The rail, in a real build`scripts/verify-place-inbox-rail.mjs` runs the packaged app, production main process and all, on a GitHub macOS runner-(`.github/workflows/inbox-rail-check.yml`, by hand or by a push to `ci/inbox-rail-check`). It refuses to run anywhere else,+(the `inbox-rail-check.yml` workflow, which lives only on the `ci/inbox-rail-check` branch and runs on a push there or by hand). It refuses to run anywhere else,because it edits `/etc/hosts` and trusts a throwaway certificate. A synthetic Admin and synthetic Clouds answer at their realaddresses over real TLS, and a bot on the synthetic Claude CLI asks a real question on the real local server.diff --git a/shared/inbox.ts b/shared/inbox.tsindex 99987f3e1d..b19501385c 100644--- a/shared/inbox.ts+++ b/shared/inbox.ts@@ -1,4 +1,4 @@-import type { OptionCardData } from "./wire.ts";+import type { OptionCardData, SecretRequestCardData, SignInRequestCardData } from "./wire.ts";/** On a Team Cloud, a line in a person's inbox: their own conversation with their own Chief of Staff (their own MausBot* when they crowned none), where everything addressed to them arrives. It says who it is from and where it came from,@@ -58,6 +58,10 @@ export interface InboxRow {answers?: InboxItem["answers"];/** An ask's card as the inbox holds it: answering it answers the card where it was asked. */card?: OptionCardData;+ /** A password the bot asked for, answered with the chat's own card for it. */+ secret?: SecretRequestCardData;+ /** A sign-in the bot asked the person to do, answered with the chat's own card for it. */+ signIn?: SignInRequestCardData;}/** A person's inbox: where its lines live (none yet before the first arrives), and the line the inbox's card in thatdiff --git a/src/components/AskCard.tsx b/src/components/AskCard.tsxindex 6c270c7cbe..6fad19f8a6 100644--- a/src/components/AskCard.tsx+++ b/src/components/AskCard.tsx@@ -273,7 +273,7 @@ const ASK_SHAPE =/** A card's answers: at least 36px tall, 44 on a touch screen, and a label that wraps rather than being cut. */export const ASK_BUTTON_SHAPE ="inline-flex min-h-9 shrink-0 items-center justify-center gap-1.5 rounded-full px-4 py-1.5 text-center text-[14px] font-medium leading-5 transition-colors [&>svg]:shrink-0 disabled:cursor-not-allowed pointer-coarse:min-h-11";-const ASK_ICON_SHAPE = "inline-flex size-8 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed pointer-coarse:size-9";+export const ASK_ICON_SHAPE = "inline-flex size-8 shrink-0 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed pointer-coarse:size-9";const ASK_LOOK = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus disabled:opacity-40";const ASK_CONTROL = `${ASK_SHAPE} ${ASK_LOOK}`;const ASK_PRIMARY_LOOK = `${ASK_LOOK} ui-button-primary bg-accent text-accent-ink hover:brightness-110`;diff --git a/src/components/inbox/InboxAnswer.tsx b/src/components/inbox/InboxAnswer.tsxnew file mode 100644index 0000000000..3865fecbe9--- /dev/null+++ b/src/components/inbox/InboxAnswer.tsx@@ -0,0 +1,113 @@+// The "You" part of a line read in the inbox: how it is answered, chosen by the kind of card it carries. Each kind answers+// with what the chat already answers it with, through the same route, so one answer settles it on every surface. A new+// kind of card adds its kind in inbox-answer.ts and one entry here.+import { useState, type ReactNode } from "react";+import { Check, ExternalLink } from "lucide-react";+import type { InboxRow, InboxView } from "../../../shared/inbox";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import type { Bot, Message } from "@/state/store";+import { replyToInboxRow, settleInboxRow } from "@/state/inbox";+import { ASK_QUIET_ANSWER, AskReply } from "../AskCard";+import { ELEVATED_CARD } from "../elevated";+import { pendingApprovals, PendingApprovalActions, PendingApprovalPanel } from "../PendingApproval";+import { QuestionCard } from "../QuestionCard";+import { SecretRequestCard } from "../SecretRequestCard";+import { SignInRequestCard } from "../SignInRequestCard";+import { singleQuestion, type InboxAnswerKind } from "./inbox-answer";+import { InboxQuestionAnswer } from "./InboxQuestionAnswer";+import { answerThread } from "./inbox-view";+import { useInboxActions } from "./use-inbox-actions";++/** The line as the chat shows it, so an ask answers here with the very card it asks with in the chat. */+export const asMessage = (row: InboxRow): Message => ({+ id: row.id, role: "bot", kind: row.secret ? "secret" : row.signIn ? "signin" : "options", text: row.text, at: row.at,+ ...(row.card ? { card: row.card } : {}), ...(row.secret ? { secret: row.secret } : {}), ...(row.signIn ? { signIn: row.signIn } : {}),+} as Message);++interface AnswerProps { view: InboxView; row: InboxRow; threadId: string | null; asker?: Bot }++function QuestionAnswer({ view, row, threadId, asker }: AnswerProps) {+ const { answer } = useInboxActions(view);+ const question = singleQuestion(row);+ if (!threadId) return null;+ // A set of several questions keeps the chat's own card, with a tab for each.+ if (!question) return <QuestionCard threadId={threadId} asker={asker} message={asMessage(row)} />;+ return <InboxQuestionAnswer row={row} question={question} asker={asker}+ onAnswer={(response, failed) => { answer(row, response, failed); settleInboxRow(row); }} />;+}++function ApprovalAnswer({ row, threadId, asker }: AnswerProps) {+ const approval = threadId ? pendingApprovals([asMessage(row)])[0] : undefined;+ if (!approval || !threadId) return null;+ return (+ <div className={cn("rounded-[24px]", ELEVATED_CARD)}>+ <PendingApprovalPanel pending={approval} count={1} index={0} botName={asker?.name ?? row.from.name} asker={asker}+ actions={<PendingApprovalActions part="primary" tag="inbox" pending={approval} threadId={threadId} bot={asker} onCancelTurn={() => {}} />} />+ </div>+ );+}++function ReviewAnswer({ view, row }: AnswerProps) {+ const { openInChat } = useInboxActions(view);+ return (+ <div className="space-y-2">+ <p className="text-[13px] text-ink-secondary">{t("inbox.reviewInChat")}</p>+ <button type="button" onClick={() => openInChat(row)} className={ASK_QUIET_ANSWER}><ExternalLink size={15} aria-hidden="true" />{t("inbox.action.openInChat")}</button>+ </div>+ );+}++function SecretAnswer({ row, threadId, asker }: AnswerProps) {+ const botId = row.from.botId;+ return botId && threadId ? <SecretRequestCard botId={botId} color={asker?.color} threadId={threadId} message={asMessage(row)} /> : null;+}++function SignInAnswer({ row, threadId, asker }: AnswerProps) {+ const botId = row.from.botId;+ return botId && threadId ? <SignInRequestCard botId={botId} botName={asker?.name ?? row.from.name} color={asker?.color} threadId={threadId} message={asMessage(row)} /> : null;+}++function DoneButton({ view, row }: AnswerProps) {+ const { run } = useInboxActions(view);+ if (row.tab !== "info") return null;+ return <button type="button" data-inbox-action="done" onClick={() => run(row, "done")} className={ASK_QUIET_ANSWER}><Check size={15} aria-hidden="true" />{t("common.done")}</button>;+}++function ReplyAnswer(props: AnswerProps) {+ const { view, row, asker } = props;+ const [reply, setReply] = useState("");+ const [sending, setSending] = useState(false);+ const send = async (text: string) => {+ if (sending) return;+ setSending(true);+ try {+ await replyToInboxRow(view, row, text);+ setReply("");+ } finally {+ setSending(false);+ }+ };+ return (+ <div className="space-y-2">+ <AskReply label={t("inbox.reply.placeholder")} placeholder={t("inbox.reply.placeholder")} color={asker?.color} value={reply} onChange={setReply}+ onSend={(text) => void send(text)} sending={sending} multiline />+ <DoneButton {...props} />+ </div>+ );+}++const ANSWERS: Record<InboxAnswerKind, (props: AnswerProps) => ReactNode> = {+ question: QuestionAnswer,+ approval: ApprovalAnswer,+ review: ReviewAnswer,+ secret: SecretAnswer,+ signIn: SignInAnswer,+ reply: ReplyAnswer,+ none: DoneButton,+};++export function InboxAnswer({ kind, view, row, asker }: { kind: InboxAnswerKind; view: InboxView; row: InboxRow; asker?: Bot }) {+ const Answer = ANSWERS[kind];+ return <div data-inbox-answer-kind={kind}><Answer view={view} row={row} threadId={answerThread(view, row)} asker={asker} /></div>;+}diff --git a/src/components/inbox/InboxCard.tsx b/src/components/inbox/InboxCard.tsxindex 1adabb2c4f..5358fc9934 100644--- a/src/components/inbox/InboxCard.tsx+++ b/src/components/inbox/InboxCard.tsx@@ -12,7 +12,7 @@ import { pendingApprovals, PendingApprovalActions } from "../PendingApproval";import { ASK_QUIET_ANSWER, ASK_QUIET_BUTTON, AskChoices, AskError } from "../AskCard";import { ELEVATED_CARD } from "../elevated";import { InboxRowItem } from "./InboxRow";-import { asMessage } from "./InboxReading";+import { asMessage } from "./InboxAnswer";import { askOf, CARD_ROWS, choiceResponse, choicesOf, rowsIn, tabCounts } from "./inbox-view";import { accessRequestWords } from "../bot-access/access-card";import { useInboxActions } from "./use-inbox-actions";diff --git a/src/components/inbox/InboxEverywhere.dom.test.ts b/src/components/inbox/InboxEverywhere.dom.test.tsindex 3a59c13c35..91cbcaf3db 100644--- a/src/components/inbox/InboxEverywhere.dom.test.ts+++ b/src/components/inbox/InboxEverywhere.dom.test.ts@@ -192,8 +192,9 @@ describe("a place's inbox in the panel", () => {await panel([question]);await act(async () => { readInboxLine("card-q"); });await mount(createElement(InboxPanel));- const choice = [...document.querySelectorAll<HTMLElement>("[data-inbox-reading] button")].find((button) => button.textContent === "Pricing")!;- await act(async () => { choice.click(); });+ await click('[data-inbox-reading] [data-inbox-option="Pricing"]');+ expect(dispatch, "a tick alone sends nothing").not.toHaveBeenCalled();+ await click("[data-inbox-reading] [data-inbox-send]");expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "eli-launch", requestId: "req-q", behavior: "answer", message: "Pricing" }));});@@ -208,7 +209,7 @@ describe("a place's inbox in the panel", () => {box.dispatchEvent(new Event("input", { bubbles: true }));});await act(async () => { box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })); });- const send = [...document.querySelectorAll<HTMLElement>("[data-inbox-reading] footer button")].find((button) => /send/i.test(button.getAttribute("aria-label") ?? button.textContent ?? ""));+ const send = [...document.querySelectorAll<HTMLElement>("[data-inbox-reading] form button")].find((button) => /send/i.test(button.getAttribute("aria-label") ?? button.textContent ?? ""));if (!server.calls.some((call) => call.path === path)) await act(async () => { send?.click(); });expect(server.calls.find((call) => call.path === path), path).toMatchObject({ method: "POST", body: { text: "Thanks", threadId, replyToId: id } });}diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsxindex 09e33756c5..0b98ff2d3d 100644--- a/src/components/inbox/InboxPanel.tsx+++ b/src/components/inbox/InboxPanel.tsx@@ -1,24 +1,30 @@-// The person's whole inbox in the right panel as one list, newest first, a dot on what waits on them,-// each line a dense row that reads in full in the panel. At phone width it is a sheet over the chat.-import { useEffect, useState, type KeyboardEvent } from "react";+// The person's whole inbox in the right panel, as a tab with its count: one list, newest first, a dot on what waits on them,+// a search over it, and each line read in full in the same place. A line answered there gives way to the next one, and to+// the list when none is left. At phone width it is a sheet over the chat.+import { useEffect, useRef, useState, type KeyboardEvent } from "react";import { createPortal } from "react-dom";-import { X } from "lucide-react";+import { Inbox, Maximize2, Minimize2, Search, X } from "lucide-react";import type { InboxRow } from "../../../shared/inbox";+import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";-import { closeInbox, readInboxLine, readInboxRow, useInboxPanel, useInboxView } from "@/state/inbox";+import { closeInbox, readInboxLine, readInboxRow, useInboxPanel, useInboxView, widenInbox } from "@/state/inbox";import { InboxActive } from "./InboxActive";import { InboxReading } from "./InboxReading";import { InboxRowItem } from "./InboxRow";-import { listedRows } from "./inbox-view";+import { matchesSearch, nextAfter } from "./inbox-answer";+import { listedRows, waitingCount } from "./inbox-view";import { useInboxActions } from "./use-inbox-actions";+const BAR_BUTTON = "flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink pointer-coarse:size-9";+export function InboxPanel() {const view = useInboxView();const panel = useInboxPanel();const phone = useMediaQuery(PHONE_LAYOUT);const { run } = useInboxActions(view);const [now, setNow] = useState(() => Date.now());+ const [query, setQuery] = useState("");useEffect(() => {const timer = setInterval(() => setNow(Date.now()), 30_000);return () => clearInterval(timer);@@ -31,26 +37,74 @@ export function InboxPanel() {};const reading = panel.reading ? view?.rows.find((row) => row.id === panel.reading) : undefined;const open = (row: InboxRow) => { readInboxRow(row); readInboxLine(row.id); };- const rows = listedRows(view);+ const rows = listedRows(view).filter((row) => matchesSearch(row, query));+ const ids = rows.map((row) => row.id);+ const at = reading ? ids.indexOf(reading.id) : -1;++ // The list as it stood while the line was in it, so the step after an answer goes to the line that was below it.+ const order = useRef<string[]>([]);+ if (at >= 0) order.current = ids;+ const waited = useRef<string | null>(null);+ useEffect(() => {+ if (!reading) { waited.current = null; return; }+ if (reading.tab !== "done") { waited.current = reading.id; return; }+ if (waited.current !== reading.id) return;+ waited.current = null;+ const next = nextAfter(order.current.filter((id) => id === reading.id || ids.includes(id)), reading.id);+ const row = next ? view?.rows.find((one) => one.id === next) : undefined;+ if (row) readInboxRow(row);+ readInboxLine(row ? row.id : null);+ // Only the line read and whether it settled move it on; the list itself is read through the ref.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [reading?.id, reading?.tab]);++ const step = (by: -1 | 1) => {+ const row = rows[at + by];+ if (row) open(row);+ };+ const count = waitingCount(view);const body = (<>- <div className="flex items-center gap-1.5 border-b border-hairline/40 px-3.5 py-2.5">- <h2 className="flex-1 text-[14px] font-semibold text-ink">{t("inbox.panel.title")}</h2>- <button type="button" onClick={closeInbox} aria-label={t("common.close")} title={t("common.close")}- className="flex size-[26px] shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink">- <X size={14} />- </button>- </div>- {reading && view ? <InboxReading view={view} row={reading} now={now} /> : (- <div className="min-h-0 flex-1 overflow-y-auto">- <div role="list" data-inbox-list aria-label={t("inbox.panel.title")}>- {rows.length === 0- ? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t("inbox.empty")}</p>- : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}- </div>- <InboxActive view={view} />+ <div className="flex items-center gap-1 px-2 pb-1 pt-2">+ <div data-inbox-tab-chip className="flex h-8 min-w-0 max-w-[15rem] flex-1 items-center gap-2 rounded-lg bg-raised ps-2.5 pe-1 text-[13px]">+ <Inbox size={15} aria-hidden="true" className="shrink-0 text-ink-secondary" />+ <span className="min-w-0 truncate font-medium text-ink">{t("inbox.panel.title")}</span>+ {count > 0 && <span data-inbox-tab-count className="shrink-0 tabular-nums text-ink-tertiary">{count}</span>}+ <span className="flex-1" />+ <button type="button" onClick={closeInbox} aria-label={t("inbox.action.closePanel")} title={t("inbox.action.closePanel")} className={cn(BAR_BUTTON, "size-6")}>+ <X size={14} aria-hidden="true" />+ </button></div>- )}+ <span className="flex-1" />+ {!phone && (+ <button type="button" onClick={() => widenInbox(!panel.wide)} aria-pressed={Boolean(panel.wide)} aria-label={t(panel.wide ? "inbox.action.narrow" : "inbox.action.widen")}+ title={t(panel.wide ? "inbox.action.narrow" : "inbox.action.widen")} className={BAR_BUTTON}>+ {panel.wide ? <Minimize2 size={14} aria-hidden="true" /> : <Maximize2 size={14} aria-hidden="true" />}+ </button>+ )}+ </div>+ <div className="mx-1.5 mb-1.5 flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-hairline/40 bg-app/40">+ {reading && view ? (+ <InboxReading view={view} row={reading} now={now} position={at >= 0 ? { index: at, count: rows.length } : null} onStep={step} />+ ) : (+ <>+ <h2 className="border-b border-hairline/40 px-3.5 py-2.5 text-[13px] font-medium text-ink">{t("inbox.panel.title")}</h2>+ <div className="min-h-0 flex-1 overflow-y-auto">+ <label className="m-2.5 flex h-8 items-center gap-2 rounded-lg bg-ink/[0.045] px-2.5 ring-[0.5px] ring-ink/[0.12] focus-within:ring-ink/30">+ <Search size={14} aria-hidden="true" className="shrink-0 text-ink-tertiary" />+ <input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("inbox.search")} aria-label={t("inbox.search")}+ className="min-w-0 flex-1 bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-tertiary [&::-webkit-search-cancel-button]:hidden" />+ </label>+ <div role="list" data-inbox-list aria-label={t("inbox.panel.title")} className="space-y-0.5 px-1.5 pb-1.5">+ {rows.length === 0+ ? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t(query.trim() && listedRows(view).length ? "inbox.noMatch" : "inbox.empty")}</p>+ : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}+ </div>+ {!query.trim() && <InboxActive view={view} />}+ </div>+ </>+ )}+ </div></>);if (phone) {@@ -65,8 +119,9 @@ export function InboxPanel() {);}return (- <aside aria-label={t("inbox.panel.title")} data-inbox-panel="side" onKeyDown={onKeyDown}- className="animate-panel-in motion-reduce:animate-none flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-hairline/40 bg-panel max-md:absolute max-md:inset-y-0 max-md:right-0 max-md:z-30">+ <aside aria-label={t("inbox.panel.title")} data-inbox-panel="side" data-wide={panel.wide ? "" : undefined} onKeyDown={onKeyDown}+ className={cn("animate-panel-in motion-reduce:animate-none flex h-full max-w-full shrink-0 flex-col border-l border-hairline/40 bg-panel max-md:absolute max-md:inset-y-0 max-md:right-0 max-md:z-30",+ panel.wide ? "w-[min(640px,60vw)]" : "w-[380px]")}>{body}</aside>);diff --git a/src/components/inbox/InboxQuestionAnswer.tsx b/src/components/inbox/InboxQuestionAnswer.tsxnew file mode 100644index 0000000000..3993d4d536--- /dev/null+++ b/src/components/inbox/InboxQuestionAnswer.tsx@@ -0,0 +1,132 @@+// A question read in the inbox, answered there: its choices as cards to tick, each with what it means and the bot's+// recommendation marked, a note of the person's own, and send. Number keys tick a choice, × closes it unanswered. The+// answer goes where it was asked, through the same route as the chat's card, so it settles there and everywhere.+import { useEffect, useState } from "react";+import { ArrowUp, Check, LoaderCircle, X } from "lucide-react";+import { formatQuestionAnswers, MAX_CUSTOM_ANSWER, type AskQuestion } from "../../../shared/ask-question";+import type { InboxRow } from "../../../shared/inbox";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import type { CardResponse } from "@/lib/card-answer";+import { askPrimary, ASK_ICON_SHAPE, AskError, type Asker } from "../AskCard";+import { cardAnswerFor } from "../bot-access/access-card";+import { recommendedOf } from "./inbox-answer";+import { closeResponse } from "./inbox-view";++/** Most choices a number key reaches. */+const KEYED_CHOICES = 9;++/** What sending the ticked choices and the note answers: the chat card's own words for a provider's question set, the+ * choice as offered for a card's own, and the note after it. */+export function questionResponse(row: InboxRow, question: AskQuestion, picked: readonly string[], note: string): CardResponse | null {+ const words = note.trim();+ if (!picked.length && !words) return null;+ if (row.card?.questionRequest) {+ const message = formatQuestionAnswers([question], [[...picked, ...(words ? [words] : [])]]);+ return message ? { behavior: "answer", message } : null;+ }+ const chosen = picked.map((label) => cardAnswerFor(row.card, label)).join(", ");+ return { behavior: "answer", message: chosen && words ? `${chosen}\n\n${words}` : chosen || words };+}++const editable = (target: EventTarget | null) => target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName));++export function InboxQuestionAnswer({ row, question, asker, onAnswer }: {+ row: InboxRow;+ question: AskQuestion;+ asker?: Asker;+ /** Sends the answer; `failed` runs when it didn't reach the card. */+ onAnswer(response: CardResponse, failed: () => void): void;+}) {+ const [picked, setPicked] = useState<string[]>([]);+ const [note, setNote] = useState("");+ const [sending, setSending] = useState(false);+ const [failed, setFailed] = useState(false);+ const multi = question.multiSelect === true;+ const freeText = question.custom !== false;+ const response = questionResponse(row, question, picked, note);++ const toggle = (label: string) => {+ if (sending) return;+ setPicked((now) => (now.includes(label) ? now.filter((one) => one !== label) : multi ? [...now, label] : [label]));+ };+ const send = (answer: CardResponse | null = response) => {+ if (!answer || sending) return;+ setFailed(false);+ setSending(true);+ onAnswer(answer, () => { setSending(false); setFailed(true); });+ };++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || editable(event.target)) return;+ const index = Number(event.key) - 1;+ const option = Number.isInteger(index) && index >= 0 && index < KEYED_CHOICES ? question.options[index] : undefined;+ if (!option) return;+ event.preventDefault();+ toggle(option.label);+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ });++ return (+ <div data-inbox-answer="question" className="rounded-2xl bg-ink/[0.03] p-2 ring-[0.5px] ring-ink/[0.12]">+ {question.options.length > 0 && (+ <div className="flex items-start gap-1">+ <div role="group" aria-label={question.question} className="min-w-0 flex-1 space-y-1.5">+ {question.options.map((option, index) => {+ const { label, recommended } = recommendedOf(option.label);+ const on = picked.includes(option.label);+ return (+ <button key={option.label} type="button" role={multi ? "checkbox" : "radio"} aria-checked={on} data-inbox-option={label} disabled={sending}+ onClick={() => toggle(option.label)}+ className={cn("flex w-full items-start gap-2.5 rounded-xl px-3 py-2.5 text-start transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus disabled:opacity-60",+ on ? "bg-ink/[0.10]" : "bg-ink/[0.045] hover:bg-ink/[0.075]")}>+ <span aria-hidden="true" className={cn("mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-[5px] border",+ on ? "border-ink bg-ink text-app" : "border-ink/35")}>+ {on && <Check size={11} strokeWidth={3} />}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] font-medium leading-5 text-ink">{label}</span>+ {recommended && (+ <span data-inbox-recommended className="mt-0.5 inline-flex items-center gap-1 rounded-md bg-ink/[0.07] px-1.5 py-px text-[11px] font-medium text-ink-secondary">+ <span aria-hidden="true" className="size-1.5 rounded-full bg-warning" />{t("inbox.recommended")}+ </span>+ )}+ {option.description && <span className="mt-0.5 block text-[12px] leading-[18px] text-ink-secondary">{option.description}</span>}+ </span>+ {index < KEYED_CHOICES && <span aria-hidden="true" className="shrink-0 text-[11px] tabular-nums text-ink-tertiary">{index + 1}</span>}+ </button>+ );+ })}+ </div>+ <button type="button" data-inbox-action="close" onClick={() => send(closeResponse(row))} disabled={sending}+ aria-label={t("inbox.action.closeQuestion")} title={t("inbox.action.closeQuestion")}+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-ink/[0.07] hover:text-ink">+ <X size={15} aria-hidden="true" />+ </button>+ </div>+ )}+ <form className="mt-1 flex items-end gap-2 px-1.5" onSubmit={(event) => { event.preventDefault(); send(); }}>+ {freeText ? (+ <textarea dir="auto" rows={1} value={note} maxLength={MAX_CUSTOM_ANSWER} disabled={sending}+ aria-label={question.options.length ? t("inbox.note") : question.question}+ placeholder={question.options.length ? t("inbox.note") : t("question.answerPlaceholder")}+ onChange={(event) => setNote(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;+ event.preventDefault();+ send();+ }}+ className="block max-h-32 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-ink outline-none placeholder:text-ink-tertiary [field-sizing:content]" />+ ) : <span className="flex-1" />}+ <button type="submit" data-inbox-send disabled={!response || sending} aria-label={t("chat.send")} title={t("chat.send")} aria-busy={sending || undefined}+ {...askPrimary(asker?.color, ASK_ICON_SHAPE)}>+ {sending ? <LoaderCircle size={16} aria-hidden="true" className="motion-safe:animate-spin" /> : <ArrowUp size={16} strokeWidth={2.4} aria-hidden="true" />}+ </button>+ </form>+ {failed && <AskError>{t("ask.error")}</AskError>}+ </div>+ );+}diff --git a/src/components/inbox/InboxReading.dom.test.ts b/src/components/inbox/InboxReading.dom.test.tsnew file mode 100644index 0000000000..cdf9fdbb79--- /dev/null+++ b/src/components/inbox/InboxReading.dom.test.ts@@ -0,0 +1,198 @@+// @vitest-environment happy-dom+// The inbox panel as a tab: a searchable list of three-line rows, and a line read in full with the bot's words in context,+// answered there (a question's choices as cards, a note, send), which then gives way to the next line.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const server = vi.hoisted(() => ({ calls: [] as Array<{ path: string; method: string; body?: unknown }>, context: [] as unknown[] }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));+vi.mock("../../state/api", () => ({+ api: vi.fn(async (path: string, init?: RequestInit) => {+ server.calls.push({ path, method: init?.method ?? "GET", ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });+ if (/^\/api\/threads\/[\w-]+\/messages\?/.test(path)) return { messages: server.context };+ return null;+ }),+}));++import { initialState, StoreContext, type AppState } from "@/state/store";+import { closeInbox, currentInboxPanel, currentInbox, openInbox, readInboxLine, setInboxView } from "@/state/inbox";+import type { InboxRow, InboxView } from "../../../shared/inbox";+import { InboxPanel } from "./InboxPanel";+import { answerKindOf, choicesLine, headlineOf, nextAfter, recommendedOf } from "./inbox-answer";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const AT = Date.now() - 60_000;+const hoster: InboxRow = {+ id: "q1", kind: "ask", tab: "needs-you", unread: true, at: AT, from: { name: "Planner", botId: "planner" },+ origin: { botId: "planner", threadId: "plan-thread", title: "Self-hosting setup", messageId: "q1" }, text: "Who is the self-hoster?",+ card: {+ title: "A question", subtitle: "Who is the self-hoster?", options: [], requestId: "req-q1", requestType: "question",+ questionRequest: { version: 1, questions: [{ question: "Who is the self-hoster?", header: "Q1: who is the self-hoster", options: [+ { label: "Small team (Recommended)", description: "One workspace on their own cloud or VPS" },+ { label: "Enterprise", description: "On-prem or private VPC" },+ { label: "Solo developer", description: "One box or a laptop" },+ ] }] },+ },+};+const why: InboxRow = {+ id: "q2", kind: "ask", tab: "needs-you", unread: true, at: AT - 1, from: { name: "Planner", botId: "planner" },+ origin: { botId: "planner", threadId: "plan-other", title: "Self-hosting setup", messageId: "q2" }, text: "Why are we doing it?",+ card: { title: "A question", subtitle: "Why are we doing it?", options: ["Trust and data control", "Open-source adoption"], requestId: "req-q2", requestType: "question" },+};+const news: InboxRow = {+ id: "n1", kind: "result", tab: "info", unread: false, at: AT - 2, from: { name: "Reporter", botId: "reporter" },+ origin: { botId: "reporter", threadId: "rep-daily", title: "Daily digest", messageId: "n1" }, text: "Daily digest: 3 new leads.",+};+const placeView = (rows: InboxRow[]): InboxView => ({ botId: null, threadId: null, rows, anchor: null });++let root: Root;+const dispatch = vi.fn();+const mount = () => act(async () => {+ root.render(createElement(StoreContext.Provider,+ { value: { state: { ...initialState, bots: [] } as AppState, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, createElement(InboxPanel)));+});+const click = (selector: string) => act(async () => { document.querySelector<HTMLElement>(selector)!.click(); });+const type = (element: HTMLInputElement | HTMLTextAreaElement, value: string) => act(async () => {+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), "value")!.set!.call(element, value);+ element.dispatchEvent(new Event("input", { bubbles: true }));+});+const listed = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);++beforeEach(() => {+ root = createRoot(document.body.appendChild(document.createElement("div")));+ server.calls.length = 0;+ server.context = [];+ dispatch.mockClear();+ setInboxView(placeView([hoster, why, news]));+ openInbox();+});+afterEach(() => {+ act(() => root.unmount());+ closeInbox();+ setInboxView(null);+ document.body.innerHTML = "";+});++describe("the inbox's words", () => {+ it("marks the recommended choice, joins the choices and says what a line is about", () => {+ expect(recommendedOf("Small team (Recommended)")).toEqual({ label: "Small team", recommended: true });+ expect(recommendedOf("Enterprise")).toEqual({ label: "Enterprise", recommended: false });+ expect(choicesLine(hoster)).toBe("Small team (recommended) / Enterprise / Solo developer");+ expect(choicesLine(news)).toBeNull();+ expect(headlineOf(hoster)).toBe("Q1: who is the self-hoster");+ expect(headlineOf(why)).toBe("Why are we doing it?");+ expect(answerKindOf(hoster)).toBe("question");+ expect(answerKindOf({ ...news, replies: true, kind: "message" })).toBe("reply");+ expect(answerKindOf({ ...news, tab: "done" })).toBe("none");+ expect(nextAfter(["a", "b", "c"], "b")).toBe("c");+ expect(nextAfter(["a", "b", "c"], "c")).toBe("b");+ expect(nextAfter(["a"], "a")).toBeNull();+ });++ it("keys a password and a sign-in by their own card kind, ahead of anything else the line says", () => {+ const secret: InboxRow = { ...news, kind: "ask", tab: "needs-you", secret: { target: "custom", label: "Stripe key", description: "", placeholder: "", helpUrl: "", requestKey: "k" } as InboxRow["secret"] };+ const signIn: InboxRow = { ...news, kind: "ask", tab: "needs-you", signIn: { url: "https://shop.test", site: "shop.test", place: "browser" } as InboxRow["signIn"] };+ expect(answerKindOf(secret)).toBe("secret");+ expect(answerKindOf(signIn)).toBe("signIn");+ expect(answerKindOf({ ...signIn, signIn: { ...signIn.signIn!, done: true } })).toBe("none");+ expect(headlineOf(signIn)).toBe("Sign in to shop.test");+ });+});++describe("the inbox tab", () => {+ it("is a tab with its count that closes, and lists three-line rows a search filters", async () => {+ await mount();+ const chip = document.querySelector("[data-inbox-tab-chip]")!;+ expect(chip.textContent).toContain("Inbox");+ expect(chip.querySelector("[data-inbox-tab-count]")!.textContent).toBe("2");+ expect(listed()).toEqual(["q1", "q2", "n1"]);+ const first = document.querySelector('[data-inbox-row="q1"]')!;+ expect(first.querySelector("[data-inbox-from]")!.textContent).toBe("Planner");+ expect(first.querySelector("[data-inbox-subject]")!.textContent).toBe("Q1: who is the self-hoster");+ expect(first.querySelector("[data-inbox-choices]")!.textContent).toBe("Small team (recommended) / Enterprise / Solo developer");+ expect(document.querySelector('[data-inbox-row="n1"] [data-inbox-choices]')).toBeNull();+ await type(document.querySelector<HTMLInputElement>('input[type="search"]')!, "digest");+ expect(listed()).toEqual(["n1"]);+ await type(document.querySelector<HTMLInputElement>('input[type="search"]')!, "nothing like it");+ expect(listed()).toEqual([]);+ expect(document.body.textContent).toContain("Nothing in the inbox matches.");+ await click('[aria-label="Close inbox"]');+ expect(currentInboxPanel().open).toBe(false);+ });+});++describe("a line read in full", () => {+ it("shows where it is with steps up and down, the way it came, and the bot's words before it in context", async () => {+ server.context = [+ { id: "m0", role: "user", kind: "text", text: "Set up self-hosting", at: AT - 10 },+ { id: "m1", role: "bot", kind: "text", text: "Grilling round 1. **A small team** first.", at: AT - 5 },+ ];+ await mount();+ await click('[data-inbox-row="q1"] > button');+ expect(document.querySelector("[data-inbox-position]")!.textContent).toBe("1 of 3");+ expect(document.querySelector("nav")!.textContent).toContain("Self-hosting setup");+ expect(document.querySelector("nav")!.textContent).toContain("Q1: who is the self-hoster");+ expect(server.calls).toContainEqual({ path: "/api/threads/plan-thread/messages?limit=8&before=q1", method: "GET" });+ const words = document.querySelector("[data-inbox-words]")!;+ expect(words.textContent).toContain("Grilling round 1.");+ expect(words.querySelector("strong")?.textContent, "drawn as the chat's Markdown").toBe("A small team");+ expect(words.textContent, "what the person said is not the bot's").not.toContain("Set up self-hosting");+ await click('[aria-label="Next"]');+ expect(currentInboxPanel().reading).toBe("q2");+ expect(document.querySelector("[data-inbox-position]")!.textContent).toBe("2 of 3");+ await click('[aria-label="Previous"]');+ expect(currentInboxPanel().reading).toBe("q1");+ await click('[aria-label="Back to the list"]');+ expect(currentInboxPanel().reading).toBeNull();+ });++ it("answers a question with its choices as cards, a number key and a note, where it was asked, then moves to the next line", async () => {+ await mount();+ await click('[data-inbox-row="q1"] > button');+ const options = [...document.querySelectorAll<HTMLElement>("[data-inbox-option]")];+ expect(options.map((option) => option.dataset.inboxOption)).toEqual(["Small team", "Enterprise", "Solo developer"]);+ expect(options[0]!.querySelector("[data-inbox-recommended]")?.textContent).toBe("Recommended");+ expect(options[1]!.textContent).toContain("On-prem or private VPC");+ expect(document.querySelector<HTMLButtonElement>("[data-inbox-send]")!.disabled, "nothing to send yet").toBe(true);+ await act(async () => { document.dispatchEvent(new KeyboardEvent("keydown", { key: "2", bubbles: true })); });+ expect(options[1]!.getAttribute("aria-checked")).toBe("true");+ await type(document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Add a note"]')!, "Mostly agencies");+ await click("[data-inbox-send]");+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "plan-thread", requestId: "req-q1", behavior: "answer" }));+ const sent = dispatch.mock.calls.find(([action]) => action.type === "decideRequest")![0].message as string;+ expect(sent).toContain("Q: Who is the self-hoster?\nA: Enterprise, Mostly agencies");+ expect(currentInbox()!.rows.find((row) => row.id === "q1")!.tab, "it leaves the list at once").toBe("done");+ expect(currentInboxPanel().reading, "the next line opens").toBe("q2");+ expect(document.querySelector('[data-inbox-reading="q2"]')).not.toBeNull();+ });++ it("goes back to the list once the last line waiting is answered, and × closes a question unanswered", async () => {+ setInboxView(placeView([why]));+ await act(async () => { readInboxLine("q2"); });+ await mount();+ await click('[data-inbox-option="Trust and data control"]');+ await click("[data-inbox-send]");+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "plan-other", requestId: "req-q2", behavior: "answer", message: "Trust and data control" }));+ expect(currentInboxPanel().reading).toBeNull();+ expect(document.querySelector("[data-inbox-list]")).not.toBeNull();++ dispatch.mockClear();+ setInboxView(placeView([hoster]));+ await act(async () => { readInboxLine("q1"); });+ await click('[data-inbox-answer="question"] [data-inbox-action="close"]');+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "plan-thread", requestId: "req-q1", behavior: "answer" }));+ expect(currentInboxPanel().reading).toBeNull();+ });++ it("reads news with Done, which moves on to what is left", async () => {+ await act(async () => { readInboxLine("n1"); });+ await mount();+ expect(document.querySelector("[data-inbox-answer-kind]")!.getAttribute("data-inbox-answer-kind")).toBe("none");+ expect(document.querySelector("[data-inbox-words]")!.textContent).toContain("Daily digest: 3 new leads.");+ await click('[data-inbox-reading] [data-inbox-action="done"]');+ expect(server.calls).toContainEqual({ path: "/api/inbox/n1/done", method: "POST" });+ expect(currentInboxPanel().reading, "news was last in the list: the line above it opens").toBe("q2");+ });+});diff --git a/src/components/inbox/InboxReading.tsx b/src/components/inbox/InboxReading.tsxindex 7bc266f2bd..28514df760 100644--- a/src/components/inbox/InboxReading.tsx+++ b/src/components/inbox/InboxReading.tsx@@ -1,24 +1,22 @@-// One line of the inbox read in full inside the panel: who it is from, what about, when and where it came from, all of-// it, then its answer: an ask's own card, the very one it asks with in the chat, or a reply, and the way back to the list.-import { useState } from "react";-import { ArrowLeft, Check, ExternalLink } from "lucide-react";+// One line of the inbox read in full inside the panel. A bar with the way back, where it is in the list with a step up and+// down, and a menu; where it came from and what it is about; the bot's words in context as the chat draws them; then the+// person's part, answered with what its kind of card answers with (InboxAnswer).+import { Check, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, ExternalLink, MoreHorizontal, UserRound, X } from "lucide-react";import type { InboxRow, InboxView } from "../../../shared/inbox";-import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import type { Message } from "@/state/store";-import { readInboxLine, replyToInboxRow } from "@/state/inbox";-import { ASK_QUIET_ANSWER, AskReply } from "../AskCard";-import { ELEVATED_CARD } from "../elevated";+import { readInboxLine } from "@/state/inbox";+import { ChatMarkdown } from "../ChatMarkdown";import { InboxSender } from "../InboxLine";-import { pendingApprovals, PendingApprovalActions, PendingApprovalPanel } from "../PendingApproval";-import { QuestionCard } from "../QuestionCard";+import { SidebarPopoverMenu, type SidebarMenuItem } from "../SidebarPopoverMenu";import { threadUpdatedLabel } from "../SidebarThreadRow";-import { answerThread, askOf, closeResponse, senderLabel, subjectOf, textOf } from "./inbox-view";import { accessRequestWords } from "../bot-access/access-card";+import { InboxAnswer } from "./InboxAnswer";+import { answerKindOf, headlineOf, singleQuestion } from "./inbox-answer";+import { askOf, closeResponse, senderLabel, textOf } from "./inbox-view";+import { useAskContext } from "./use-ask-context";import { useInboxActions } from "./use-inbox-actions";-/** The line as the chat shows it, so an ask answers here with the very card it asks with in the chat. */-export const asMessage = (row: InboxRow): Message => ({ id: row.id, role: "bot", kind: "options", text: row.text, at: row.at, card: row.card } as Message);+const NAV_BUTTON = "flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink disabled:pointer-events-none disabled:opacity-35 pointer-coarse:size-9";function settledLabel(row: InboxRow): string {if (row.kind !== "ask") return t("common.done");@@ -30,80 +28,93 @@ function settledLabel(row: InboxRow): string {return card?.answered === "answer" && !card.dismissed ? t("question.status.answered") : t("question.status.closed");}-export function InboxReading({ view, row, now }: { view: InboxView; row: InboxRow; now: number }) {+/** What the line itself says, drawn after the bot's words before it: a question's question, news as it came. An approval,+ * a password or a sign-in says it on its own card. */+function ownWords(row: InboxRow): string | null {+ if (row.secret || row.signIn) return null;+ if (row.kind !== "ask") return textOf(row);+ if (row.card?.tool) return null;+ const question = singleQuestion(row);+ return question ? accessRequestWords(row.card)?.question ?? question.question : row.card?.questionRequest ? null : row.card?.subtitle || row.text;+}++export function InboxReading({ view, row, now, position, onStep }: {+ view: InboxView;+ row: InboxRow;+ now: number;+ /** Where the line is in the list the person came from; null when it has left it. */+ position: { index: number; count: number } | null;+ onStep(by: -1 | 1): void;+}) {const { answer, openInChat, run, askerOf } = useInboxActions(view);const asker = askerOf(row);- const [reply, setReply] = useState("");- const [sending, setSending] = useState(false);- const ask = askOf(row);- const send = async (text: string) => {- if (sending) return;- setSending(true);- try {- await replyToInboxRow(view, row, text);- setReply("");- } finally {- setSending(false);- }- };- const threadId = answerThread(view, row);- const approval = ask === "approval" && threadId ? pendingApprovals([asMessage(row)])[0] : undefined;- const canReply = !ask && row.tab === "info" && row.replies === true;+ const context = useAskContext(row);+ const kind = answerKindOf(row);+ const headline = headlineOf(row);+ const words = ownWords(row);+ const said = context.filter((message) => message.text?.trim() !== words?.trim());+ const menu: SidebarMenuItem[] = [+ ...(row.origin || view.threadId ? [{ key: "open", label: t("inbox.action.openInChat"), icon: <ExternalLink size={16} />, onSelect: () => openInChat(row) }] : []),+ ...(row.tab === "info" ? [{ key: "done", label: t("common.done"), icon: <Check size={16} />, onSelect: () => run(row, "done") }] : []),+ ...(askOf(row) === "question" ? [{ key: "close", label: t("inbox.action.closeQuestion"), icon: <X size={16} />, onSelect: () => answer(row, closeResponse(row)) }] : []),+ ];+ const place = row.origin?.title || senderLabel(row);return (- <article data-inbox-reading={row.id} aria-label={`${senderLabel(row)} · ${subjectOf(row)}`} className="flex min-h-0 flex-1 flex-col">- <header className="flex items-start gap-2 border-b border-hairline/40 px-3 py-2.5">+ <article data-inbox-reading={row.id} aria-label={`${senderLabel(row)} · ${headline}`} className="flex min-h-0 flex-1 flex-col">+ <header className="flex items-center gap-1 px-2 py-1.5"><button type="button" onClick={() => readInboxLine(null)} aria-label={t("inbox.action.back")} title={t("inbox.action.back")}- className="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink pointer-coarse:size-9">- <ArrowLeft size={15} aria-hidden="true" />+ className="flex h-7 shrink-0 items-center gap-0.5 rounded-md pe-2 ps-1 text-[13px] font-medium text-ink hover:bg-raised pointer-coarse:h-9">+ <ChevronLeft size={16} aria-hidden="true" className="rtl:rotate-180" />{t("inbox.panel.title")}</button>- <span className="mt-0.5 shrink-0" aria-hidden="true"><InboxSender from={row.from} size={28} /></span>- <div className="min-w-0 flex-1">- <div className="flex items-baseline gap-2">- <span className="min-w-0 truncate text-[14px] font-semibold text-ink">{senderLabel(row)}</span>- <span className="ml-auto shrink-0 text-[11px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span>- </div>- <div className="truncate text-[13px] text-ink">{subjectOf(row)}</div>- {(row.origin || row.via) && (- <div className="truncate text-[12px] text-ink-tertiary">- {row.via && t("inbox.via", { name: row.via.name })}{row.via && row.origin && " · "}{row.origin && t("inbox.in", { title: row.origin.title })}- </div>- )}- </div>+ <span className="flex-1" />+ {position && <span data-inbox-position className="px-1 text-[12px] tabular-nums text-ink-tertiary">{t("inbox.position", { index: position.index + 1, count: position.count })}</span>}+ <button type="button" onClick={() => onStep(-1)} disabled={!position || position.index === 0} aria-label={t("inbox.action.previous")} title={t("inbox.action.previous")} className={NAV_BUTTON}>+ <ChevronUp size={16} aria-hidden="true" />+ </button>+ <button type="button" onClick={() => onStep(1)} disabled={!position || position.index >= position.count - 1} aria-label={t("inbox.action.next")} title={t("inbox.action.next")} className={NAV_BUTTON}>+ <ChevronDown size={16} aria-hidden="true" />+ </button>+ {menu.length > 0 && (+ <SidebarPopoverMenu items={menu} ariaLabel={t("inbox.action.more")} placement="below" align="end" triggerClassName="rounded-md" triggerTitle={t("inbox.action.more")}+ renderTrigger={() => <span className={NAV_BUTTON}><MoreHorizontal size={16} aria-hidden="true" /></span>} />+ )}</header>- <div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-3">- {!ask && <p className="whitespace-pre-wrap break-words text-[14px] leading-6 text-ink">{textOf(row)}</p>}+ <nav aria-label={t("inbox.breadcrumb")} className="flex min-w-0 items-center gap-1 border-b border-hairline/40 px-3.5 pb-2 text-[12px] text-ink-tertiary">+ <button type="button" data-inbox-action="open" onClick={() => openInChat(row)} title={t("inbox.action.openInChat")}+ className="min-w-0 max-w-[45%] shrink truncate rounded hover:text-ink hover:underline">{place}</button>+ <ChevronRight size={12} aria-hidden="true" className="shrink-0 rtl:rotate-180" />+ <span className="min-w-0 truncate font-medium text-ink-secondary">{headline}</span>+ </nav>+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-3.5 py-3">+ <section aria-label={senderLabel(row)} className="flex gap-2.5">+ <span className="mt-0.5 shrink-0" aria-hidden="true"><InboxSender from={row.from} size={22} /></span>+ <div className="min-w-0 flex-1">+ <div className="flex items-baseline gap-2">+ <span className="min-w-0 truncate text-[13px] font-semibold text-ink">{senderLabel(row)}</span>+ <span className="shrink-0 text-[11px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span>+ </div>+ {row.via && <div className="truncate text-[12px] text-ink-tertiary">{t("inbox.via", { name: row.via.name })}</div>}+ <div data-inbox-words className="mt-1 space-y-2 text-[14px] leading-6 text-ink">+ {said.map((message) => <ChatMarkdown key={message.id} text={message.text!} />)}+ {words && <ChatMarkdown text={words} />}+ </div>+ </div>+ </section>{row.answers?.map((given) => (<p key={given.at} className="rounded-xl bg-ink/[0.045] px-3 py-2 text-[13px] text-ink-secondary"><span className="block text-[11px] font-medium text-ink-tertiary">{t(given.by === "assistant" ? "inbox.assistantAnswered" : "inbox.youReplied")}</span><span className="whitespace-pre-wrap break-words">{given.text}</span></p>))}- {row.tab === "done" && (- <>- {row.kind === "ask" && <p className="whitespace-pre-wrap break-words text-[14px] leading-6 text-ink">{accessRequestWords(row.card)?.question ?? row.card?.subtitle ?? row.text}</p>}- <p className="flex items-center gap-1.5 text-[13px] text-ink-secondary"><Check size={14} aria-hidden="true" />{settledLabel(row)}</p>- </>- )}- {ask === "question" && threadId && <QuestionCard threadId={threadId} asker={asker} message={asMessage(row)} />}- {approval && threadId && (- <div className={cn("rounded-[24px]", ELEVATED_CARD)}>- <PendingApprovalPanel pending={approval} count={1} index={0} botName={asker?.name ?? row.from.name} asker={asker}- actions={<PendingApprovalActions part="primary" tag="inbox" pending={approval} threadId={threadId} bot={asker} onCancelTurn={() => {}} />} />+ <section data-inbox-you aria-label={t("inbox.you")} className="flex gap-2.5">+ <span aria-hidden="true" className="mt-0.5 flex size-[22px] shrink-0 items-center justify-center rounded-full bg-ink/[0.08] text-ink-secondary"><UserRound size={13} /></span>+ <div className="min-w-0 flex-1 space-y-2">+ <div className="text-[13px] font-semibold text-ink">{t("inbox.you")}</div>+ {row.tab === "done" && <p className="flex items-center gap-1.5 text-[13px] text-ink-secondary"><Check size={14} aria-hidden="true" />{settledLabel(row)}</p>}+ <InboxAnswer kind={kind} view={view} row={row} asker={asker} /></div>- )}- {ask === "review" && <p className="text-[13px] text-ink-secondary">{t("inbox.reviewInChat")}</p>}+ </section></div>- <footer className="space-y-2 border-t border-hairline/40 px-3 py-2.5">- {canReply && (- <AskReply label={t("inbox.reply.placeholder")} placeholder={t("inbox.reply.placeholder")} color={asker?.color} value={reply} onChange={setReply}- onSend={(text) => void send(text)} sending={sending} multiline />- )}- <div className={cn("flex flex-wrap items-center gap-1.5", canReply && "pt-0.5")}>- {ask === "question" && <button type="button" data-inbox-action="close" onClick={() => answer(row, closeResponse(row))} className={ASK_QUIET_ANSWER}>{t("inbox.action.closeQuestion")}</button>}- {row.tab === "info" && <button type="button" data-inbox-action="done" onClick={() => { run(row, "done"); readInboxLine(null); }} className={ASK_QUIET_ANSWER}><Check size={15} aria-hidden="true" />{t("common.done")}</button>}- <button type="button" data-inbox-action="open" onClick={() => openInChat(row)} className={ASK_QUIET_ANSWER}><ExternalLink size={15} aria-hidden="true" />{t("inbox.action.openInChat")}</button>- </div>- </footer></article>);}diff --git a/src/components/inbox/InboxRow.tsx b/src/components/inbox/InboxRow.tsxindex 1dff0c405c..ace7e147bd 100644--- a/src/components/inbox/InboxRow.tsx+++ b/src/components/inbox/InboxRow.tsx@@ -1,13 +1,14 @@-// One line of the person's inbox as a dense row: a dot while it waits on them, the sender's face and who it is from, the-// subject and where it came from, a muted snippet and the time. An unread row is bold on a stronger ground. On hover or keyboard focus the time gives-// way to the row's quick actions.-import { Check, CornerUpLeft, ExternalLink, X, type LucideIcon } from "lucide-react";+// One line of the person's inbox as a dense row: a dot while it waits on them or is unread, the sender's face, who it is+// from and where, the time, what it is about in bold, and for a question its choices on one line, the recommended one+// marked. On hover or keyboard focus the time gives way to the row's quick actions.+import { Check, CornerUpLeft, ExternalLink, Split, X, type LucideIcon } from "lucide-react";import type { InboxRow } from "../../../shared/inbox";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { InboxSender } from "../InboxLine";import { threadUpdatedLabel } from "../SidebarThreadRow";+import { choicesLine, headlineOf, snippetOf } from "./inbox-answer";import { placeOf, quickActions, senderLabel, subjectOf, textOf, type QuickAction } from "./inbox-view";const ACTION_LOOK: Record<QuickAction, { Icon: LucideIcon; label: LocaleKey }> = {@@ -33,15 +34,20 @@ export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {const actions = quickActions(row);const sender = senderLabel(row);const place = placeOf(row);+ const headline = inCard ? "" : headlineOf(row);+ const choices = inCard ? null : choicesLine(row);+ const snippet = inCard || choices ? null : snippetOf(row);+ const unreadish = row.unread || row.tab === "needs-you";return (<div data-inbox-row={row.id} data-tab={row.tab} data-unread={row.unread ? "" : undefined}- className={cn("group relative flex min-w-0 items-center gap-2 border-b border-hairline/20 pr-1.5 focus-within:bg-raised/70 hover:bg-raised/70",- row.unread ? "bg-raised/45" : "bg-transparent", inCard && "border-b-0")}>- <button type="button" onClick={() => onOpen(row)} title={[sender, subject, place].filter(Boolean).join(" · ")}+ className={cn("group relative flex min-w-0 items-center gap-2 pr-1.5 focus-within:bg-raised/70 hover:bg-raised/70",+ inCard ? (row.unread ? "bg-raised/45" : "bg-transparent") : "rounded-lg")}>+ <button type="button" onClick={() => onOpen(row)} title={[sender, inCard ? subject : headline, place].filter(Boolean).join(" · ")}className={cn("flex min-w-0 flex-1 gap-2 pl-2.5 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60", inCard ? "items-center py-1.5" : "items-start py-2",row.unread ? "font-semibold text-ink" : "font-normal text-ink-secondary")}>- {row.tab === "needs-you" && <span data-inbox-waits className={cn("size-1.5 shrink-0 rounded-full bg-warning", !inCard && "mt-[7px]")} role="img" aria-label={t("inbox.waitsOnYou")} />}- <span className="shrink-0" aria-hidden="true"><InboxSender from={row.from} size={20} /></span>+ {row.tab === "needs-you" ? <span data-inbox-waits className={cn("size-1.5 shrink-0 rounded-full", inCard ? "bg-warning" : "mt-[7px] bg-accent")} role="img" aria-label={t("inbox.waitsOnYou")} />+ : !inCard && <span data-inbox-unread-dot={row.unread ? "" : undefined} aria-hidden="true" className={cn("mt-[7px] size-1.5 shrink-0 rounded-full", row.unread ? "bg-accent" : "bg-transparent")} />}+ <span className={cn("shrink-0", !inCard && "mt-px")} aria-hidden="true"><InboxSender from={row.from} size={inCard ? 20 : 18} /></span>{inCard ? (<><span className="w-[7.5rem] shrink-0 truncate">{row.from.name}</span>@@ -52,20 +58,23 @@ export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {<span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span></>) : (- <span className="min-w-0 flex-1">- <span className="flex items-baseline gap-2">- <span data-inbox-from className="min-w-0 flex-1 truncate">{sender}</span>- <span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>- </span>- <span className="block truncate text-[12px] font-normal">- <span>{subject}</span>- {place && <span data-inbox-place className="text-ink-tertiary"> {place}</span>}- <span className="text-ink-tertiary"> · {textOf(row)}</span>+ <span className="min-w-0 flex-1 space-y-px">+ <span className="flex items-baseline gap-1.5">+ <span data-inbox-from className="min-w-0 shrink truncate font-semibold">{sender}</span>+ {place && <span data-inbox-place className="min-w-0 flex-1 truncate text-[12px] font-normal text-ink-tertiary">{place}</span>}+ <span className="ms-auto shrink-0 ps-1 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span></span>+ <span data-inbox-subject className={cn("block truncate text-[13px] font-semibold", unreadish ? "text-ink" : "text-ink-secondary")}>{headline}</span>+ {choices ? (+ <span data-inbox-choices className="flex min-w-0 items-center gap-1.5 text-[12px] font-normal text-ink-secondary">+ <Split size={12} aria-hidden="true" className="shrink-0 rotate-180 text-warning" />+ <span className="min-w-0 truncate">{choices}</span>+ </span>+ ) : snippet && <span className="block truncate text-[12px] font-normal text-ink-tertiary">{snippet}</span>}</span>)}</button>- <span className="absolute right-1.5 top-1/2 hidden -translate-y-1/2 items-center gap-0.5 rounded-md bg-raised group-focus-within:flex group-hover:flex">+ <span className={cn("absolute right-1.5 hidden items-center gap-0.5 rounded-md bg-raised group-focus-within:flex group-hover:flex", inCard ? "top-1/2 -translate-y-1/2" : "top-1.5")}>{actions.map((action) => {const { Icon, label } = ACTION_LOOK[action];return (diff --git a/src/components/inbox/inbox-answer.ts b/src/components/inbox/inbox-answer.tsnew file mode 100644index 0000000000..c525874372--- /dev/null+++ b/src/components/inbox/inbox-answer.ts@@ -0,0 +1,91 @@+// What a line of the inbox is answered with, by the kind of card it carries, and the words its row and reading view show.+// A new kind of card adds a kind here and its answer in InboxAnswer, and every row and reading view picks it up.+import type { AskQuestion } from "../../../shared/ask-question";+import type { InboxRow } from "../../../shared/inbox";+import { t } from "@/lib/i18n";+import { cardQuestions } from "../QuestionCard";+import { accessRequestWords } from "../bot-access/access-card";+import { askOf, senderLabel, subjectOf, textOf } from "./inbox-view";++/** How a line is answered: a question's choices, an approval's Allow and Deny, a proposal reviewed in its chat, a+ * password or a sign-in through the chat's own card for it, a reply to news that waits on one, or nothing but Done. */+export type InboxAnswerKind = "question" | "approval" | "review" | "secret" | "signIn" | "reply" | "none";++const secretOpen = (row: InboxRow) => Boolean(row.secret && !row.secret.provided && !row.secret.dismissed && !row.secret.superseded && !row.secret.stopped);+const signInOpen = (row: InboxRow) => Boolean(row.signIn && !row.signIn.done && !row.signIn.cancelled && !row.signIn.superseded && !row.signIn.stopped && !row.signIn.answeredInChat);++export function answerKindOf(row: InboxRow): InboxAnswerKind {+ if (row.tab === "done") return "none";+ if (secretOpen(row)) return "secret";+ if (signInOpen(row)) return "signIn";+ const ask = askOf(row);+ if (ask) return ask;+ return row.tab === "info" && row.replies === true ? "reply" : "none";+}++const RECOMMENDED = /\s*[([]\s*recommended\s*[)\]]\s*$/i;++/** A choice as offered, with the "(Recommended)" a bot writes after the one it would pick taken off as a mark. */+export function recommendedOf(label: string): { label: string; recommended: boolean } {+ const bare = label.replace(RECOMMENDED, "");+ return bare && bare !== label ? { label: bare, recommended: true } : { label, recommended: false };+}++/** The one question a line asks when it asks just one; a set of several keeps the chat's own card with its tabs. */+export function singleQuestion(row: InboxRow): AskQuestion | null {+ if (!row.card) return null;+ const questions = cardQuestions(row.card);+ return questions.length === 1 ? questions[0]! : null;+}++/** A question's choices on one line: "Small team (recommended) / Enterprise / Solo developer". */+export function choicesLine(row: InboxRow): string | null {+ if (answerKindOf(row) !== "question") return null;+ const question = singleQuestion(row);+ if (!question?.options.length) return null;+ return question.options.map((option) => {+ const { label, recommended } = recommendedOf(option.label);+ return recommended ? `${label} ${t("inbox.recommendedInline")}` : label;+ }).join(" / ");+}++const firstLine = (text: string) => text.split("\n").map((line) => line.replace(/^[#>*\-\s]+/, "").trim()).find(Boolean) ?? "";++/** What a line is about, in a few words: a question's short header or its first line, what an approval asks for, the+ * password or site asked for, else the first line of what it says. */+export function headlineOf(row: InboxRow): string {+ if (row.secret) return row.secret.label;+ if (row.signIn) return t("inbox.headline.signIn", { site: row.signIn.site });+ if (row.kind === "ask") {+ const question = row.card && !row.card.tool ? singleQuestion(row) : null;+ if (question) return question.header ?? firstLine(accessRequestWords(row.card)?.question ?? question.question);+ if (row.card?.questionRequest) return row.card.questionRequest.questions[0]?.header ?? subjectOf(row);+ return firstLine(row.card?.subtitle || row.card?.title || row.text) || subjectOf(row);+ }+ return firstLine(textOf(row)) || subjectOf(row);+}++/** The muted line under the headline when there is more to say and no choices to show. */+export function snippetOf(row: InboxRow): string | null {+ const text = textOf(row).replace(/\s+/g, " ").trim();+ const headline = headlineOf(row);+ if (!text || text === headline) return null;+ return text.startsWith(headline) ? text.slice(headline.length).trim() || null : text;+}++/** The search box keeps a line whose sender, conversation, headline, words or choices hold every word typed. */+export function matchesSearch(row: InboxRow, query: string): boolean {+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);+ if (!words.length) return true;+ const hay = [senderLabel(row), row.origin?.title ?? "", headlineOf(row), textOf(row), choicesLine(row) ?? ""].join(" ").toLowerCase();+ return words.every((word) => hay.includes(word));+}++/** Where the reading view goes once a line is answered: the next line down, else the one above, else back to the list. */+export function nextAfter(ids: readonly string[], id: string): string | null {+ const at = ids.indexOf(id);+ const rest = ids.filter((one) => one !== id);+ if (!rest.length) return null;+ if (at < 0) return rest[0]!;+ return rest[at] ?? rest[at - 1] ?? rest[0]!;+}diff --git a/src/components/inbox/use-ask-context.ts b/src/components/inbox/use-ask-context.tsnew file mode 100644index 0000000000..fc35c0c5a3--- /dev/null+++ b/src/components/inbox/use-ask-context.ts@@ -0,0 +1,36 @@+// What the bot said just before a line of the inbox, read from the conversation it came from, so the line reads in context:+// its words since the person last wrote there. Nothing when that conversation can't be read; the line still reads alone.+import { useEffect, useState } from "react";+import type { InboxRow } from "../../../shared/inbox";+import type { Message } from "@/state/store";+import { api } from "@/state/api";++/** How far back the reading view looks for the bot's words before the line. */+const CONTEXT_PAGE = 8;++/** The bot's own words before the line, since the person last wrote: what a question or a report builds on. */+export function contextBefore(messages: readonly Message[]): Message[] {+ const out: Message[] = [];+ for (let index = messages.length - 1; index >= 0; index--) {+ const one = messages[index]!;+ if (one.role === "user") break;+ if (one.role === "bot" && one.kind === "text" && one.text?.trim()) out.unshift(one);+ }+ return out;+}++export function useAskContext(row: Pick<InboxRow, "id" | "origin">): Message[] {+ const threadId = row.origin?.threadId;+ const messageId = row.origin?.messageId;+ const [context, setContext] = useState<{ key: string; messages: Message[] } | null>(null);+ const key = threadId && messageId ? `${threadId}:${messageId}` : "";+ useEffect(() => {+ if (!key) return;+ let live = true;+ void api<{ messages?: Message[] }>(`/api/threads/${threadId}/messages?limit=${CONTEXT_PAGE}&before=${encodeURIComponent(messageId!)}`, { background: true })+ .then((page) => { if (live) setContext({ key, messages: contextBefore(page?.messages ?? []) }); })+ .catch(() => { if (live) setContext({ key, messages: [] }); });+ return () => { live = false; };+ }, [key, threadId, messageId]);+ return context?.key === key ? context.messages : [];+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 1607b63da8..09e337ccd0 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2062,6 +2062,21 @@"inbox.subject.result": "Routine report","inbox.subject.notice": "Needs a look","inbox.reviewInChat": "Look at this in the chat it came from to answer it.",+ "inbox.search": "Search inbox",+ "inbox.noMatch": "Nothing in the inbox matches.",+ "inbox.position": "{index} of {count}",+ "inbox.breadcrumb": "Where this came from",+ "inbox.action.previous": "Previous",+ "inbox.action.next": "Next",+ "inbox.action.more": "More",+ "inbox.action.closePanel": "Close inbox",+ "inbox.action.widen": "Wider",+ "inbox.action.narrow": "Narrower",+ "inbox.recommended": "Recommended",+ "inbox.recommendedInline": "(recommended)",+ "inbox.note": "Add a note",+ "inbox.you": "You",+ "inbox.headline.signIn": "Sign in to {site}","inbox.youReplied": "You replied","sidebar.people.mention": "Write to {name}","orgChart.mode.departments": "Departments",diff --git a/src/state/inbox.ts b/src/state/inbox.tsindex d6a41ffd17..73196d39aa 100644--- a/src/state/inbox.ts+++ b/src/state/inbox.ts@@ -94,6 +94,9 @@ export function readInboxRow(row: Pick<InboxRow, "id" | "unread">): void {void mark(row.id, "read");}+/** An ask the person just answered here: it leaves the list at once, before the server's next read says so. */+export const settleInboxRow = (row: Pick<InboxRow, "id">): void => patchRow(row.id, { tab: "done", unread: false });+/** The person is done with a line of news: it moves to Done. */export function doneInboxRow(row: Pick<InboxRow, "id">): void {patchRow(row.id, { tab: "done", unread: false });@@ -108,15 +111,17 @@ export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId"void refreshInbox();}-export interface InboxPanelState { open: boolean; reading: string | null }+export interface InboxPanelState { open: boolean; reading: string | null; wide?: boolean }const panel = store<InboxPanelState>({ open: false, reading: null });export const useInboxPanel = (): InboxPanelState => useSyncExternalStore(panel.subscribe, panel.get, panel.get);export const currentInboxPanel = panel.get;/** Opens the inbox in the right panel: its list, or straight on one line. */export function openInbox(at: { reading?: string } = {}): void {- panel.set({ open: true, reading: at.reading ?? null });+ panel.set({ ...panel.get(), open: true, reading: at.reading ?? null });void refreshInbox();}export const closeInbox = (): void => panel.set({ ...panel.get(), open: false, reading: null });export const readInboxLine = (id: string | null): void => panel.set({ ...panel.get(), reading: id });+/** The panel at its usual width or wider, for a long message. */+export const widenInbox = (wide: boolean): void => panel.set({ ...panel.get(), wide });