import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { API_V1, CREDENTIALS, checkTenant, QUERY_OPEN_EVENT, signal, UNAUTHORIZED_EVENT } from "../apiContract"; import { queryCitationLabel } from "../customer-grid/queryPreview"; import { retryEmit } from "../shell/targetRoute"; import type { NotificationTarget } from "../alerts/alertsModel"; import { dataAddressHash, databaseEntries, fetchNav, QUERY_ROUTE, routeKeyOf, shapeNav, splitChrome } from "../shell/nav"; import { sheetAddressHash } from "../sheet"; import type { NavEntry, NavResult } from "../shell/nav"; import { persistQueryArtifacts, runQueryTool, type QueryToolArtifacts } from "../automation/automationApi"; import { answerSourceFooter, call as queryRequest, fetchArtifacts, fetchQueries, rateMessage, refusalSentence, type ArtifactIndex, type Result, type QueryCitation, type QueryIndex, type QueryMessage, type SavedQuery, } from "../query/queryApi"; import { artifactFileHref, worklistText } from "../artifacts/worklistApi"; import { worklistFigure } from "../artifacts/WorklistTable"; import SnapshotTable from "../artifacts/SnapshotTable"; // W51-T31 — the ONE Escape arbiter (C8). See the registration in `AssistantMessage`. import { useEscapeClose } from "../ui/useEscapeClose"; import { PingCard } from "./PingCard"; import { NoticeCard } from "./NoticeCard"; import { TypingIndicator } from "./TypingIndicator"; import { canFallback, ChatStreamFailure, streamChat, streamDelta } from "./streamClient"; import { stopTurn, submitChat } from "./turnClient"; import { SuggestionChips } from "./SuggestionChips"; import { takePendingAsk } from "./askPending"; import { MemoryPanel } from "./MemoryPanel"; import { ModuleHomeHead } from "../home/ModuleHomeHead"; import { addressFromHash, interceptOpen, LinkedText, LOAD_FAILED, NOT_AVAILABLE, OpenInPlaceContext, OpenInPlaceHost, useOpenInPlace, } from "./OpenInPlace"; import type { InPlaceModules, InPlaceTarget, OpenInPlaceApi } from "./OpenInPlace"; import type { ReactNode } from "react"; import "./assistant.css"; import "../styles/wave45/agent-operator.css"; // The pop-up's stylesheet loads with its host, never from OpenInPlace.tsx (see the note there). import "../styles/sdlc72/open-in-place.css"; import "../styles/sdlc74/assistant.css"; const useConversationLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect; // S72-T12: the dock reaches these through `AssistantPanel.tsx::loadRenderers`, never a static import. export { SuggestionChips, TypingIndicator }; // One `/nav` read per page session, on the first dock link outside the dock's own databases. // A failed read clears the cache, so the next click retries. let dockGrant: Promise | undefined; export function loadDockGrant(read: () => Promise = fetchNav): Promise { return dockGrant ||= read().then((result) => { if (!result.ok) throw new Error("The database list could not be read."); return shapeNav(splitChrome(result.pages).main, ""); }).catch((error: unknown) => { dockGrant = undefined; throw error; }); } function DockGrantLoading() { return
; } function DockGrantFailed() { return

{LOAD_FAILED}

; } // The Data dock holds the grid scope, and a link carries the nav key. This inverts `shell/dbFrame.tsx::gridScopeFor`. const NAV_KEY_OF_SCOPE: Record = { customer: "customer_data", product: "product_data" }; /** The dock's link host. Its own databases and workbooks open at once. Any other link reads the grant once, then opens. */ export function DockOpenInPlace({ sources, children, modules, readGrant = loadDockGrant }: { sources: NavEntry[]; children?: ReactNode; modules?: InPlaceModules; readGrant?: () => Promise; }) { const [grant, setGrant] = useState(null); const [waiting, setWaiting] = useState<{ target: InPlaceTarget; failed: boolean } | null>(null); const own = sources.map((entry) => ({ ...entry, key: NAV_KEY_OF_SCOPE[entry.key] || entry.key })); // A known target clears any wait, so a stale loader or failure never covers it. const foreign = useCallback((target: InPlaceTarget | null) => { if (!target) { setWaiting(null); return; } setWaiting({ target, failed: false }); readGrant().then((list) => { setGrant(list); setWaiting(null); }, () => setWaiting((current) => current && current.target === target ? { target, failed: true } : current)); }, [readGrant]); let granted = grant ? [...grant, ...own.filter((entry) => !grant.some((row) => row.key === entry.key))] : own; let hostModules: InPlaceModules = { artifact: ArtifactItemView, ...modules }; if (waiting) { // Until the grant arrives the pop-up shows the loader, or one sentence if the read failed. const body = waiting.failed ? DockGrantFailed : DockGrantLoading; hostModules = { ...hostModules, data: body, query: body }; if (waiting.target.kind === "data") granted = [...own, { key: waiting.target.database, label: "", kind: "native", depth: 0 }]; } return {children} ; } function DockLinkScope({ own, ready, onForeign, children }: { own: NavEntry[]; ready: boolean; onForeign: (target: InPlaceTarget | null) => void; children?: ReactNode; }) { const host = useOpenInPlace(); const api = useMemo(() => host && { open: (href: string) => { const target = addressFromHash(href); if (!target) return false; // A workbook and an artifact record read no grant. The record list is the caller's own. const known = target.kind === "sheet" || target.kind === "artifact" || (target.kind === "data" && own.some((entry) => entry.key === target.database)); if (known || ready) onForeign(null); else onForeign(target); return host.open(href); } }, [host, own, ready, onForeign]); return {children}; } export interface AssistantPageProps { granted: NavEntry[]; } /** Routing rides on /query/tool. Its shared result union belongs to another lane, so keep * the routing and refusal extension local and read it through the single cast in ask(). */ type RoutedTo = { database: string; label: string; reason: string; auto: boolean; alternatives: Array<{ database: string; label: string }> }; // W61-T30: the drafting extension stays local while the shared API union belongs to another lane. type SemanticDraft = { database: string; label: string; canApprove: boolean; sentToAdmins: boolean; state: "pending" | "approved"; requestedBy: string; approvedBy?: string | null; approvedAt?: string | null; approvalLine?: string; sentMessage: string; fields: Array<{ field: string; label: string; why: string; role: string; dataType: string; sensitivity: string; sample: { redacted: boolean; values: string[]; sample: string[] } }>; }; type AssistantChatContinuation = { status: "continue_chat"; routedTo: RoutedTo & { database: ""; auto: false }; }; type RoutedQueryResult = (Awaited> | AssistantChatContinuation | { status: "refused"; wording: string; speakable: string; artifacts: null; code?: string; }) & { routedTo?: RoutedTo; draft?: SemanticDraft }; /** C2: the server's code on a thrown request, read without importing the error class. */ function failureCode(error: unknown): string | undefined { const code = (error as { code?: unknown } | null)?.code; return typeof code === "string" ? code : undefined; } type ChatRouting = { governed: RoutedQueryResult; database: string; routed?: RoutedTo }; type ChatBatch = { requests: Map; joined: Set; restored: Set; routingReady: boolean; ready: Promise; resolve: (routing: ChatRouting | null) => void; }; type PendingDelete = { id: string; summary: string; expiresAt: string | number }; type ToolCall = { name: string; args: Record; effect: "read" | "write" | "delete"; ok: boolean; ref: string | null; }; type AgentTurnResult = { reply: string; toolCalls: ToolCall[]; pendingDelete: PendingDelete | null; artifacts: string[]; refused: string | null; }; type AssistantChatMessage = QueryMessage & { // S72-T16: an id, or a C7 record when the turn carries the record itself. toolCalls?: ToolCall[]; pendingDelete?: PendingDelete | null; artifacts?: Array>; pendingResolved?: string; streaming?: boolean; toolStep?: string; }; type ScheduledField = { key: string; label: string; type: string; currency?: string | null }; export type ScheduledResultEnvelope = { version: number; kind: "scheduled_result" | "reminder"; id: string; scheduleId: string; words: string; request: Record; runAt: string; ok: boolean; message?: string; sourceSyncedAt?: string | null; rowCount?: number; fields?: ScheduledField[]; totals?: Array<{ fn: string; field?: string; value: unknown }>; table?: { header: ScheduledField[]; rows: unknown[][]; total: number; unit: "rows" | "groups" }; dataLink?: string; }; export type AssistantLogTurn = { id: string; seq?: number; role: "user" | "assistant" | "system"; door: "app" | "whatsapp" | "wake"; kind: "text" | "ping" | "notice" | "confirm" | "divider"; text: string; at: string; payload?: Partial & Partial> & Partial & { title?: string; body?: string; link?: string | null; source?: string; subject?: string; target?: NotificationTarget | null; governedArtifacts?: QueryToolArtifacts; // A feed notice names its sender as a string. A C6 inbox notice sends an object. sender?: string | { username?: string; name?: string }; // C6 inbox fields. `NoticeCard.readInboxNotice` guards each one. type?: string; request_id?: string; text?: string; actions?: string[]; state?: string; }; }; /** C22: what a `kind: "ping"` turn carries. `PingCard` reads nothing else. */ export type PingPayload = { ticketId: string; checkId: string; title: string; reason: string; action: string; recordLink: string; amount?: number; daysOverdue?: number; assignedBy: string[]; digest?: Array; }; type ConversationPage = { turns: AssistantLogTurn[]; hasMore: boolean }; // Reuse Query's transport so cookies and server error sentences follow the same path. function fetchConversation(before?: string): Promise> { const query = new URLSearchParams({ limit: "50" }); if (before) query.set("before", before); return queryRequest(`/assistant/log?${query.toString()}`, {}, (body: unknown) => body as ConversationPage); } function answerDelete(id: string, decision: "delete" | "keep"): Promise> { return queryRequest("/assistant/confirm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id, decision }), }, (body: unknown) => body as AgentTurnResult | { kept: boolean }); } // The transport's legacy message reader omits agent fields. The log is authoritative for those. function localTurn(message: AssistantChatMessage): AssistantLogTurn { return { id: message.id, role: message.role, door: "app", kind: "text", text: message.content, at: message.createdAt, payload: message }; } function turnMessage(turn: AssistantLogTurn): AssistantChatMessage { return { ...turn.payload, id: turn.payload?.id || turn.id, role: turn.role === "user" ? "user" : "assistant", content: turn.text, createdAt: turn.at } as AssistantChatMessage; } function mergeTurns(older: AssistantLogTurn[], newer: AssistantLogTurn[]): AssistantLogTurn[] { const keys = new Set(newer.map((turn) => turn.payload?.id || turn.id)); const knownStops = new Set(older.filter((turn) => turn.text === "Stopped." && !turn.id.startsWith("stopped_")) .map((turn) => turn.payload?.id || turn.id)); const savedStops = newer.filter((turn) => turn.role !== "user" && turn.text === "Stopped." && !turn.id.startsWith("stopped_") && !knownStops.has(turn.payload?.id || turn.id)).length; const reconciled = new Set(older.filter((turn) => turn.id.startsWith("stopped_")).slice(0, savedStops) .map((turn) => turn.id)); return [...older.filter((turn) => !keys.has(turn.payload?.id || turn.id) && !reconciled.has(turn.id)), ...newer]; } function DeleteConfirmCard({ pending, resolved, onResolved }: { pending: PendingDelete; resolved?: string; onResolved?: (id: string, line: string) => void; }) { const [line, setLine] = useState(""); const [busy, setBusy] = useState(false); const [problem, setProblem] = useState(""); const inFlight = useRef(false); const decide = async (decision: "delete" | "keep") => { if (inFlight.current || resolved || line) return; inFlight.current = true; setBusy(true); setProblem(""); try { const result = await answerDelete(pending.id, decision); if (!result.ok) { setProblem("This choice could not be saved. Try again."); return; } let reply: string; if (decision === "keep") { if (!("kept" in result.value) || !result.value.kept) { setProblem("This choice could not be saved. Try again."); return; } reply = "Kept. Nothing was removed."; } else { const turn = result.value as AgentTurnResult; reply = turn.refused || turn.reply; if (!reply) { setProblem("This choice could not be saved. Try again."); return; } } setLine(reply); onResolved?.(pending.id, reply); } catch { setProblem("This choice could not be saved. Try again."); } finally { inFlight.current = false; setBusy(false); } }; if (resolved || line) return

{resolved || line}

; return

{pending.summary}

{problem ?

{problem}

: null}
; } const WRITE_LABELS: Record = { sheet_create_workbook: "Created a workbook", sheet_update_workbook: "Updated a workbook", sheet_write_cells: "Updated cells", view_upsert: "Saved a view", build_view: "Built a view", }; export function WriteReport({ calls, onPreview }: { calls?: ToolCall[]; onPreview: (id: string) => void }) { const inPlace = useOpenInPlace(); return <>{calls?.filter((call) => call.effect === "write" && call.ok).map((call, position) => { const args = call.args || {}; const viewArgs = args.view && typeof args.view === "object" ? args.view as Record : {}; // The reader recognises what was made by its name; the id is the fallback, never the headline. const target = String(args.title || args.name || viewArgs.name || "") || call.ref || ""; const workbook = call.name.startsWith("sheet_"); // A saved grid View lives in Data under its database; only a built Query answer opens in Query. const gridView = call.name === "view_upsert" && typeof args.database === "string" && Boolean(args.database); const built = call.name === "build_view"; const href = call.ref && (workbook ? sheetAddressHash({ wb: call.ref }) : gridView ? dataAddressHash({ database: String(args.database), view: call.ref }) : built ? `#/${QUERY_ROUTE}?view=${encodeURIComponent(call.ref)}` : ""); return

{WRITE_LABELS[call.name] || call.name} {target ? {target} : null} {href ? { // S72-T14: a mounted host opens every Open here in its pop-up. Without one, only a built view is routed. if (interceptOpen(inPlace, href, event) || !built) return; event.preventDefault(); onPreview(call.ref!); }}>Open : null}

; })}; } export function AssistantGreeting({ loaded, turnCount }: { loaded: boolean; turnCount: number }) { if (!loaded || turnCount) return null; return

ask me anything about your data

; } function scheduledEnvelope(turn: AssistantLogTurn): ScheduledResultEnvelope | null { const payload = turn.payload; if (turn.role !== "assistant" || turn.kind !== "text" || payload?.kind !== "scheduled_result" || !/^sr_[a-f0-9]{32}$/.test(payload.id || "") || typeof payload.words !== "string" || typeof payload.ok !== "boolean") return null; if (payload.ok && (!payload.table || !Array.isArray(payload.table.header) || !Array.isArray(payload.table.rows) || !Array.isArray(payload.totals) || typeof payload.rowCount !== "number" || typeof payload.table.total !== "number")) return null; return payload as ScheduledResultEnvelope; } async function markScheduledRead(id: string): Promise { const result = await queryRequest(`/schedules/results/${encodeURIComponent(id)}/read`, { method: "POST" }, (body: unknown) => body as { id: string; read: boolean }); return result.ok && result.value.read === true && result.value.id === id; } /** A visible request acknowledges its result once, including after a hidden tab becomes visible. */ export function observeScheduledResult(element: HTMLElement, id: string, acknowledge: (id: string) => Promise = markScheduledRead): () => void { if (typeof IntersectionObserver === "undefined") return () => {}; let stopped = false; let pending = false; let read = false; const root = element.closest(".as-stream"); const visible = () => { if (document.visibilityState !== "visible") return false; const box = element.getBoundingClientRect(); const clip = root?.getBoundingClientRect(); return box.width > 0 && box.height > 0 && Math.min(box.bottom, clip?.bottom ?? window.innerHeight, window.innerHeight) > Math.max(box.top, clip?.top ?? 0, 0) && Math.min(box.right, clip?.right ?? window.innerWidth, window.innerWidth) > Math.max(box.left, clip?.left ?? 0, 0); }; const mark = () => { if (stopped || pending || read || !visible()) return; pending = true; void acknowledge(id).then((ok) => { read = ok; if (ok) observer.disconnect(); }) .catch(() => {}).finally(() => { pending = false; }); }; const observer = new IntersectionObserver((entries) => { if (entries.some((entry) => entry.target === element && entry.isIntersecting)) mark(); }, { root, threshold: 0 }); observer.observe(element); document.addEventListener("visibilitychange", mark); return () => { stopped = true; observer.disconnect(); document.removeEventListener("visibilitychange", mark); }; } function scheduledFigure(value: unknown, field?: ScheduledField): string { const formatted = worklistFigure(value, Boolean(field?.currency)); return typeof value === "number" && field?.currency ? `${formatted} ${worklistText(field.currency)}` : formatted; } export function ScheduledResult({ result }: { result: ScheduledResultEnvelope }) { const heading = useRef(null); useEffect(() => { if (heading.current) return observeScheduledResult(heading.current, result.id); }, [result.id]); const table = result.table; const operations: Record = { sum: "Total", avg: "Average", min: "Minimum", max: "Maximum", count: "Count", count_distinct: "Distinct", }; const numeric = (field: ScheduledField) => Boolean(field.currency) || ["number", "money", "currency", "integer", "float", "decimal", "id"].includes(field.type); return

Scheduled

{worklistText(result.words)}

{result.ok && table ? <>

{result.sourceSyncedAt ? <>Last synced{" "} : "Sync time unavailable"}

Records
{worklistFigure(result.rowCount)}
{result.totals?.filter((item) => item.fn !== "count" || item.field).map((item, index) => { const field = result.fields?.find((field) => field.key === item.field); const label = field?.label || item.field || ""; return
{worklistText(`${operations[item.fn] || item.fn} ${label ? label[0].toLowerCase() + label.slice(1) : ""}`.trim())}
{scheduledFigure(item.value, ["sum", "avg", "min", "max"].includes(item.fn) ? field : undefined)}
; })}

{`${Math.min(20, table.rows.length).toLocaleString()} of ${table.total.toLocaleString()} shown`} {table.unit === "groups" ? " (groups)" : null}

{table.header.map((field) => )}{table.rows.slice(0, 20).map((row, index) => {table.header.map((field, column) => )} )}
{worklistText(field.label)}
{scheduledFigure(row[column], field)}
{result.dataLink?.startsWith("#/table?") || result.dataLink?.startsWith("#/data?") ? Open in Table : null} :

{worklistText(result.message || "The saved query could not run.")}

}
; } export function AssistantTurn({ turn, ...props }: { turn: AssistantLogTurn; fresh?: boolean; } & Omit[0], "message">) { if (turn.kind === "divider") return
{turn.text}
; const { fresh, ...messageProps } = props; const scheduled = scheduledEnvelope(turn); return
{scheduled ? null : turn.door === "whatsapp" ?

From WhatsApp

// A ping card carries its own "Wake-up" label; the door marker would say it twice. : turn.door === "wake" && turn.kind !== "ping" ?

Wake-up

: null} {scheduled ? : turn.kind === "ping" ? : turn.kind === "notice" ? : turn.role === "system" ?

: }
; } async function draftRequest(database: string, fields?: string[], question?: string): Promise<{ state?: "pending" | "approved"; draft?: SemanticDraft; approvalLine?: string; sentMessage?: string; }> { const response = await fetch(`${API_V1}/query/semantics/${encodeURIComponent(database)}/${fields ? "approve" : "draft"}`, { credentials: CREDENTIALS, method: fields ? "POST" : "GET", ...(fields ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fields, question }) } : {}), }); if (checkTenant(response)) throw new Error("The workspace changed. Open this chat again."); if (response.status === 401) signal(UNAUTHORIZED_EVENT); if (!response.ok) throw new Error("The field request could not be completed, so please try again."); return response.json(); } // R13 (moved from S68-T45): Time-series is retired, so it has no label here. const KIND_LABEL: Record = { grid: "table", list: "list", chart: "chart", kanban: "board", calendar: "calendar", map: "map", }; /** S72-T16 (C7, R98): the made-file kinds an answer shows as a chip. Any other kind keeps today's answer. */ export const ARTIFACT_KIND_LABEL: Record = { xlsx: "Excel file", image: "Image", snapshot: "Snapshot" }; // The pop-up also names a PDF, because its record carries a file the same way. const ITEM_KIND_LABEL: Record = { ...ARTIFACT_KIND_LABEL, pdf: "PDF file" }; export type ArtifactRecord = { id: string; kind: string; title: string; fileId?: string; mime?: string }; /** A C7 record, or a stored record of today's shape. Null when it has no id or kind. */ export function readArtifactRecord(value: unknown): ArtifactRecord | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const row = value as Record; const text = (key: string) => typeof row[key] === "string" ? (row[key] as string).trim() : ""; const id = text("id"); const kind = text("kind"); if (!id || !kind) return null; // C7 names `file_id`. Today's PDF record keeps its file id in `ref`. const fileId = text("file_id") || text("fileId") || text("ref"); const mime = text("mime"); return { id, kind, title: text("title") || ITEM_KIND_LABEL[kind] || "Artifact", ...(fileId ? { fileId } : {}), ...(mime ? { mime } : {}) }; } /** C7: the in-app link of one artifact record. */ export function artifactItemHash(id: string): string { return `#/artifacts?item=${encodeURIComponent(id)}`; } export type ArtifactReader = () => Promise>; const readArtifactIndex: ArtifactReader = () => fetchArtifacts(); // One shared `/artifacts` read per page session. A failed read clears it, so the next use retries. let artifactRead: Promise> | undefined; let artifactReadGeneration = 0; export function loadArtifactRecords(read: ArtifactReader = readArtifactIndex, fresh = false): Promise> { if (fresh) artifactRead = undefined; if (!artifactRead) artifactReadGeneration += 1; return artifactRead ||= read().then((result) => { if (!result.ok) throw new Error("The artifact list could not be read."); const records = new Map(); for (const item of result.value.items) { const record = readArtifactRecord(item); if (record) records.set(record.id, record); } return records; }).catch((error: unknown) => { artifactRead = undefined; throw error; }); } /** True when an image file can show inline. A record with no mime is trusted by its kind. */ function picturable(record: ArtifactRecord): boolean { return Boolean(record.fileId) && record.kind === "image" && (!record.mime || record.mime.startsWith("image/")); } /** One made file under an answer: the chip opens the pop-up, an image shows inline, Excel offers a download. */ export function ArtifactChip({ record }: { record: ArtifactRecord }) { const inPlace = useOpenInPlace(); const [broken, setBroken] = useState(false); const href = artifactItemHash(record.id); const file = record.fileId ? artifactFileHref(record.fileId) : ""; return
{/* A failed load leaves the chip alone, never a broken image. */} {picturable(record) && !broken ? {record.title} setBroken(true)} /> : null}
; } /** The chips for an answer's artifacts. Ids read the shared list. A message with none reads nothing. */ export function ArtifactChips({ entries, read = readArtifactIndex }: { entries?: unknown[]; read?: ArtifactReader }) { const list = Array.isArray(entries) ? entries : []; const key = list.filter((entry): entry is string => typeof entry === "string" && Boolean(entry)).join("\n"); const [found, setFound] = useState | null>(null); // A list read before this answer existed may miss its new id. That miss reads once more. const seenGeneration = useRef(artifactReadGeneration); useEffect(() => { if (!key) return; let live = true; const wanted = key.split("\n"); loadArtifactRecords(read).then((records) => wanted.every((id) => records.has(id)) || artifactReadGeneration > seenGeneration.current ? records : loadArtifactRecords(read, true)) .then((records) => { if (live) setFound(records); }, () => {}); return () => { live = false; }; }, [key, read]); const records = list.map((entry) => typeof entry === "string" ? found?.get(entry) ?? null : readArtifactRecord(entry)) .filter((record): record is ArtifactRecord => Boolean(record && ARTIFACT_KIND_LABEL[record.kind])); if (!records.length) return null; return
{records.map((record) => )}
; } /** The selected artifact opens as stored content, an image, a download or one refusal. */ export function ArtifactItemView({ id, read = readArtifactIndex }: { id: string; read?: ArtifactReader }) { const [state, setState] = useState<{ record: ArtifactRecord | null } | "loading" | "failed">("loading"); useEffect(() => { let live = true; loadArtifactRecords(read).then((records) => records.has(id) ? records : loadArtifactRecords(read, true)) .then((records) => { if (live) setState({ record: records.get(id) ?? null }); }, () => { if (live) setState("failed"); }); return () => { live = false; }; }, [id, read]); if (state === "loading") return ; if (state === "failed") return ; const record = state.record; if (!record) return

{NOT_AVAILABLE}

; const file = record.fileId ? artifactFileHref(record.fileId) : ""; return

{record.title}

{ITEM_KIND_LABEL[record.kind] ?

{ITEM_KIND_LABEL[record.kind]}

: null} {record.kind === "snapshot" ? : null} {picturable(record) ? {record.title} : null} {(record.kind === "xlsx" || record.kind === "pdf") && file ? Download : null}
; } const PAGE_MODULES: InPlaceModules = { artifact: ArtifactItemView }; /** Route to the exact Query-owned artifact, preserving the public hosted variant. */ export function openBuiltView(qid: string, hosted = false): () => void { if (typeof window === "undefined") return () => {}; if (!hosted && routeKeyOf(window.location.hash) !== QUERY_ROUTE) { window.location.hash = `#/${QUERY_ROUTE}`; } return retryEmit(() => signal(QUERY_OPEN_EVENT, { qid })); } /** * R9's provenance, as a DISCLOSURE. Every clause the ruling requires is present — sources, * fields, filters, aggregation, contributing record count, retrieval time, each a link to the * exact artefact — but shut by default, because a chat that prints its own audit trail under * every sentence is not the "plain look" the owner asked for and is not readable as an answer. */ export function CitationLine({ citation }: { citation: QueryCitation }) { return {queryCitationLabel(citation)}; } /** One glyph, drawn once and turned over for the other. R20 asked for thumbs; these are thumbs. */ function ThumbIcon({ down = false }: { down?: boolean }) { return ( ); } export function AssistantMessage({ message, view, citations, onPreview, onRate, governedArtifacts, confirmation, onConfirmed, }: { message: AssistantChatMessage; view?: SavedQuery; citations: QueryCitation[]; onPreview: (id: string) => void; /** Optional so the message can be rendered outside a live conversation without a rating door. */ onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void; governedArtifacts?: QueryToolArtifacts; confirmation?: string; onConfirmed?: (id: string, line: string) => void; }) { // S72-T14: a mounted host shows a built view in its pop-up. Without one, `onPreview` routes as before. const inPlace = useOpenInPlace(); const openView = (id: string) => { if (!inPlace?.open(`#/${QUERY_ROUTE}?view=${encodeURIComponent(id)}`)) onPreview(id); }; const [openSources, setOpenSources] = useState(false); const [askWhy, setAskWhy] = useState(false); const [why, setWhy] = useState(""); const [slackOpen, setSlackOpen] = useState(false); const [artifacts, setArtifacts] = useState(governedArtifacts || null); const [artifactStatus, setArtifactStatus] = useState(""); const slackRef = useRef(null); // W51-T31 — the Slack correction card calls itself a `role="dialog"`, so it owes a dialog's // dismissal: Escape closes it, through the ONE stack (C8 / DESIGN.md §4). Registered here at // the top level rather than beside the markup, because the markup sits behind a conditional // and the early return for a user message is two lines below. useEscapeClose(slackOpen, () => setSlackOpen(false), { container: () => slackRef.current }); const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id)); if (message.role === "user") { return (

{message.content}

); } if (message.streaming) { return
{message.toolStep ?

{message.toolStep}

: null} {message.content ?

{message.content}

: null}
; } if (message.reason === "query_no_source_matched") { return

{message.pendingResolved ?

{message.pendingResolved}

: message.pendingDelete ? : null}
; } const provenance = message.provenance; const sourceFooter = answerSourceFooter(provenance, matching); const numeric = message.numeric; return (

{message.pendingResolved ?

{message.pendingResolved}

: message.pendingDelete ? : null} {view && artifacts ? (

Query setup

{(["filters", "sorts", "group", "hiddenFields", "source"] as const).map((key) => ( ))}
{artifactStatus ?

{artifactStatus}

: null} {slackOpen ? (

Slack correction

Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.

{(["filters", "sorts", "group"] as const).map((key) => )}

Draft only. No Slack message was sent.

) : null}
) : null} {numeric && numeric.value !== null && numeric.value !== undefined ? (

{numeric.label} {numeric.value.toLocaleString()}

) : null} {view ? ( ) : null} {/* R112: one quiet row, the sources line (only when a permitted citation backs the answer) and the two thumbs. The sentence is the disclosure that opens the citation links. The thumbs are NOT a survey: the server reads a thumbs-down back into the next turn of this thread, so a down asks for one short reason and both are clearable. */} {matching.length || onRate ?
{matching.length ? (
) : null} {onRate ? (
{message.rating === "down" && !askWhy && message.ratingReason ? ( {message.ratingReason} ) : null}
) : null}
: null} {onRate && askWhy && message.rating === "down" ? (
{ event.preventDefault(); setAskWhy(false); onRate(message.id, "down", why.trim()); }}> setWhy(event.currentTarget.value)} />
) : null} {matching.length && openSources ? (
{matching.map((citation) => )}
) : null}
); } function initialIndex(): QueryIndex { return { threads: [], messages: [], views: [], citations: [], models: ["auto"], modelStatus: [], sources: [] }; } /** One persistent conversation, with the composer anchored below its scrollable turns. */ export default function AssistantPage({ granted }: AssistantPageProps) { const [memoryOpen, setMemoryOpen] = useState(false); const [index, setIndex] = useState(initialIndex); const [turns, setTurns] = useState([]); const [hasMore, setHasMore] = useState(false); const [conversationLoaded, setConversationLoaded] = useState(false); const [conversationLoading, setConversationLoading] = useState(true); const [conversationProblem, setConversationProblem] = useState(""); const [confirmations, setConfirmations] = useState>({}); const [freshMessageIds, setFreshMessageIds] = useState([]); const [target, setTarget] = useState(""); const [question, setQuestion] = useState(""); const [busy, setBusy] = useState(false); const [answerStarted, setAnswerStarted] = useState(false); const [stopping, setStopping] = useState(false); const [problem, setProblem] = useState(""); const [loaded, setLoaded] = useState(false); const [artifactByView, setArtifactByView] = useState>({}); const [alignment, setAlignment] = useState; maxSelections: number; routed?: RoutedTo; draft?: SemanticDraft; sent?: boolean; }>(null); const [alignmentFields, setAlignmentFields] = useState([]); const [draftBusy, setDraftBusy] = useState(false); const [draftProblem, setDraftProblem] = useState(""); const [approvalLine, setApprovalLine] = useState(""); const composerRef = useRef(null); const alignmentRef = useRef(null); const requestInFlight = useRef(false); const activeChat = useRef(null); const stopInFlight = useRef(false); const alignmentGeneration = useRef(0); const lastDraftCheck = useRef(0); useEscapeClose(Boolean(alignment), () => { alignmentGeneration.current += 1; setAlignment(null); setAlignmentFields([]); setDraftProblem(""); composerRef.current?.focus(); }, { container: () => alignmentRef.current }); const openCancel = useRef<(() => void) | null>(null); const streamRef = useRef(null); const conversationInFlight = useRef(false); const conversationGeneration = useRef(0); const scrollRestore = useRef<{ height: number; top: number } | null>(null); const scrollToNewest = useRef(false); const followsNewest = useRef(true); const retryBefore = useRef(undefined); const olderPagesLoaded = useRef(false); /** A counter, not a random id: the optimistic message only has to be unique within this page. */ const pending = useRef(0); const databases = useMemo(() => databaseEntries(granted).filter((entry) => entry.kind !== "group"), [granted]); /** * ⭐⭐ INSTRUCTION 12 / R11 — NO SOURCE PICKER AT ALL. Owner: *"the Assistant should always have * access to all database that the user have access to. So it doesn't need the database clicks * under the chat."* The chip row and the sentence explaining why some chips were grey are both * gone; the limit they explained is closed in the read boundary, not narrated to the reader. * `databases` above IS the answer to "what may the assistant read", and the server wall * (`deps.py::assistant_source_status`) remains the authority on every request. */ const viewById = useMemo(() => new Map(index.views.map((view) => [view.id, view])), [index.views]); const reload = useCallback(async () => { const result = await fetchQueries(); setLoaded(true); if (result.ok) setIndex(result.value); }, []); const loadConversation = useCallback(async (before?: string) => { if (conversationInFlight.current) return; conversationInFlight.current = true; const generation = conversationGeneration.current; retryBefore.current = before; setConversationLoading(true); setConversationProblem(""); try { const result = await fetchConversation(before); if (generation !== conversationGeneration.current) return; if (!result.ok) { setConversationProblem("The conversation could not be loaded."); return; } if (before) { const stream = streamRef.current; if (stream) scrollRestore.current = { height: stream.scrollHeight, top: stream.scrollTop }; setTurns((current) => mergeTurns(result.value.turns, current)); olderPagesLoaded.current = true; } else { scrollToNewest.current = followsNewest.current; setTurns((current) => mergeTurns(current, result.value.turns)); } if (before || !olderPagesLoaded.current) setHasMore(result.value.hasMore); setConversationLoaded(true); } catch { if (generation === conversationGeneration.current) setConversationProblem("The conversation could not be loaded."); } finally { if (generation === conversationGeneration.current) { conversationInFlight.current = false; setConversationLoading(false); } } }, []); useEffect(() => { void loadConversation(); return () => { const chat = activeChat.current; activeChat.current = null; chat?.resolve(null); chat?.requests.forEach(({ controller }) => controller.abort()); conversationGeneration.current += 1; conversationInFlight.current = false; }; }, [loadConversation]); // Layout runs before paint: initial opens land at the bottom, prepends retain the read position. useConversationLayoutEffect(() => { const stream = streamRef.current; if (!stream) return; if (scrollRestore.current) { const previous = scrollRestore.current; stream.scrollTop = previous.top + stream.scrollHeight - previous.height; scrollRestore.current = null; } else if (scrollToNewest.current || (busy && followsNewest.current)) { stream.scrollTop = stream.scrollHeight; scrollToNewest.current = false; } }, [turns, busy, conversationLoading]); const onConversationScroll = () => { const stream = streamRef.current; if (stream) { followsNewest.current = stream.scrollHeight - stream.scrollTop - stream.clientHeight < 48; if (!followsNewest.current) scrollToNewest.current = false; } if (streamRef.current && streamRef.current.scrollTop < 200 && hasMore && conversationLoaded && !conversationProblem) void loadConversation(turns[0]?.id); }; useEffect(() => { void reload(); }, [reload]); useEffect(() => () => openCancel.current?.(), []); // Keep source selection within the grant for clarification replays. A fresh question needs // no target: the server preflight decides whether to route Data or continue guarded chat. useEffect(() => { const permitted = databases.map((entry) => entry.key); setTarget((current) => permitted.includes(current) ? current : databases[0]?.key ?? ""); }, [databases]); // A resume token is bound to the database that produced it. Changing the target invalidates the // clarification instead of replaying the token against a different database. useEffect(() => { if (alignment && alignment.database !== target) { setAlignment(null); setAlignmentFields([]); } }, [alignment, target]); useEffect(() => { alignmentGeneration.current += 1; setDraftProblem(""); setApprovalLine(""); }, [target]); /** * ⭐⭐ R16 — ENTER GOES TO THE CHAT, NOT TO A WAIT. Owner: *"Pressing enter goes immediately to * the chat view showing that it is loading; there is a thinking animation."* * * This used to POST and only then touch `index`, so for the whole model call the reader sat on * the opening screen looking at their own unsent sentence with nothing moving. The message is * appended FIRST, which is what flips `empty` and hands the surface to the stream; `busy` then * draws the app's one loading mark under it. * * ⛔ THE INVERSE IS CAPTURED BEFORE THE WRITE. An optimistic append that is not reconciled on * failure leaves a message on screen the server never received, and the next turn replays it to * the model as if it had [[undo-capture-before-the-write]]. The typed text goes back in the * composer too: losing somebody's sentence to a failed request is the second injury. */ const ask = useCallback(async (approvedFields?: string[], override?: { database: string; prompt: string }) => { const replayDraft = !override && alignment?.draft && (approvedFields || alignment.sent); const replay = (approvedFields || replayDraft) && alignment; const text = override?.prompt ?? (replay ? replay.prompt : question.trim()); const selectedTarget = approvedFields && alignment ? alignment.database : target; const database = override?.database ?? (replay ? (approvedFields ? selectedTarget : replay.database) : ""); if (!text || !conversationLoaded || draftBusy || stopInFlight.current || (requestInFlight.current && !activeChat.current)) return; const primary = !activeChat.current; if (primary) { let resolve!: ChatBatch["resolve"]; const ready = new Promise((settle) => { resolve = settle; }); activeChat.current = { requests: new Map(), joined: new Set(), restored: new Set(), routingReady: false, ready, resolve }; setAnswerStarted(false); } const batch = activeChat.current!; requestInFlight.current = true; const controller = new AbortController(); const isCurrent = () => activeChat.current === batch && !controller.signal.aborted; const generation = alignmentGeneration.current; setBusy(true); setProblem(""); setDraftProblem(""); if (!replay) setApprovalLine(""); const pendingId = `pending_${(pending.current += 1)}`; const answerId = `${pendingId}_answer`; batch.requests.set(pendingId, { controller, answerId, text }); const optimistic = { id: pendingId, role: "user", content: text, createdAt: new Date().toISOString(), targetDatabase: database, sources: database ? [database] : [], } as AssistantChatMessage; const withoutPending = (rows: AssistantLogTurn[]) => rows.filter((row) => row.id !== pendingId && row.id !== answerId); const undoOptimistic = () => { const unsent = (primary && !batch.routingReady ? [...batch.requests.entries()] : [[pendingId, { answerId, text }] as const]).filter(([id]) => !batch.restored.has(id)); if (!unsent.length) return; const ids = new Set(unsent.flatMap(([id, row]) => [id, row.answerId])); unsent.forEach(([id]) => batch.restored.add(id)); setTurns((current) => current.filter((turn) => !ids.has(turn.id))); setQuestion((current) => [...unsent.map(([, row]) => row.text), current].filter(Boolean).join("\n")); }; // R108: a refused or failed turn keeps the asked message on screen and says its cause once. // The local copy gives way only when the durable log already holds the same message. const keepAsked = (sentence: string) => { batch.restored.add(pendingId); setTurns((current) => current.filter((turn) => turn.id !== answerId && (turn.id !== pendingId || !current.some((row) => row.role === "user" && !row.id.startsWith("pending_") && row.text === text && row.at >= optimistic.createdAt)))); setProblem(sentence); }; const acknowledgeJoin = () => { batch.joined.add(pendingId); setTurns((current) => current.filter((turn) => turn.id !== answerId && (turn.id !== pendingId || !current.some((row) => row.role === "user" && !row.id.startsWith("pending_") && row.text === text && row.at >= optimistic.createdAt)))); }; setQuestion(""); setFreshMessageIds([pendingId]); scrollToNewest.current = followsNewest.current; setTurns((current) => [...current, localTurn(optimistic)]); try { let governed: RoutedQueryResult; let routed: RoutedTo | undefined; let chosen: string; if (!primary) { const routing = await batch.ready; if (!isCurrent()) return; if (!routing) { undoOptimistic(); return; } governed = routing.governed; chosen = routing.database; routed = routing.routed; } else { try { // One narrow cast for routing and drafts; the shared result union stays in its owning lane. if (replayDraft) { const current = await draftRequest(database); if (!isCurrent()) return; if (generation !== alignmentGeneration.current) { undoOptimistic(); return; } if (current.draft?.approvalLine) setApprovalLine(current.draft.approvalLine); } governed = await runQueryTool({ database, prompt: text, ...(approvedFields && !replayDraft ? { fieldKeys: approvedFields, resumeToken: alignment?.resumeToken } : {}) }) as RoutedQueryResult; if (!isCurrent()) return; if (replayDraft && governed.status === "clarification" && !governed.draft) { // Approval changes the choice set. Only this fresh clarification can authenticate resume. const choices = new Set(governed.alignmentQuestion.choices.map((choice) => choice.field)); const fields = (approvedFields || alignmentFields).filter((field) => choices.has(field)); if (fields.length) { const retry = { database, prompt: text, fieldKeys: fields, resumeToken: governed.resumeToken }; governed = await runQueryTool(retry) as RoutedQueryResult; } } } catch (error) { if (!isCurrent()) return; if (generation !== alignmentGeneration.current) { undoOptimistic(); return; } if (alignment?.draft) { keepAsked(""); setDraftProblem("The field request could not be completed, so please try again."); } else keepAsked(refusalSentence(failureCode(error))); return; } if (!isCurrent()) return; if (generation !== alignmentGeneration.current) { undoOptimistic(); return; } routed = replay && alignment?.routed ? alignment.routed : governed.routedTo; chosen = governed.routedTo?.database ?? database; if (chosen) setTarget(chosen); if (governed.status === "clarification") { undoOptimistic(); const sent = Boolean(replayDraft && alignment?.sent && governed.draft?.state === "pending"); if (!sent) setAlignmentFields([]); setAlignment({ prompt: text, database: chosen, routed, draft: governed.draft, sent, resumeToken: governed.resumeToken, question: governed.alignmentQuestion.question, choices: governed.alignmentQuestion.choices, maxSelections: governed.alignmentQuestion.maxSelections }); return; } setAlignment(null); composerRef.current?.focus(); // C2: a coded refusal says its sentence and stops. An uncoded one still reaches chat's reply. if (governed.status === "refused" && governed.code) { keepAsked(refusalSentence(governed.code)); return; } if (governed.status === "refused") undoOptimistic(); // Queue during routing. Clarification and refusal restore unsent follow-ups to the composer. batch.routingReady = governed.status !== "refused"; batch.resolve(governed.status === "refused" ? null : { governed, database: chosen, routed }); } setTurns((current) => [...current, localTurn({ ...optimistic, id: answerId, role: "assistant", content: "", streaming: true })]); // ⛔ THE TARGET, ALONE. `routes_query.py::_sources` runs EVERY key in this array through the // read scope with no try/except, so one refusal kills the whole request; and the model is only // ever handed the target's snapshot anyway. A wider array buys nothing and breaks the turn. // Automatic refusals go through chat's same routing branch, which saves a plain reply // without trying to read an unavailable database. Successful replies use the chosen target. const chatDatabase = governed.status === "refused" && routed?.auto ? "" : chosen; let result: Awaited>; try { const streamed = await streamChat({ question: text, database: chatDatabase, sources: chosen ? [chosen] : [], model: "auto" }, (event) => { if (!isCurrent()) return; if (event.type === "text_delta" || event.type === "tool_step" || event.type === "paused") { if (event.type === "text_delta" && streamDelta(event.data)) setAnswerStarted(true); setTurns((current) => current.map((turn) => turn.id !== answerId ? turn : event.type === "text_delta" ? { ...turn, text: turn.text + streamDelta(event.data) } : { ...turn, payload: { ...turn.payload, toolStep: event.type === "paused" ? typeof event.data.message === "string" ? event.data.message : "Waiting to resume." : event.data.label || event.data.message || "Working" } })); } }, controller.signal); if (!isCurrent()) return; if (streamed.type !== "done") { acknowledgeJoin(); return; } result = { ok: true, value: streamed.data }; } catch (error) { if (!isCurrent()) return; if (canFallback(error, controller.signal)) { result = await submitChat({ question: text, database: chatDatabase, sources: chosen ? [chosen] : [], model: "auto" }, controller.signal); } else { if (error instanceof ChatStreamFailure && error.admitted) { await loadConversation(); } keepAsked(refusalSentence(failureCode(error))); return; } } if (!isCurrent()) return; if (!result.ok) { keepAsked(refusalSentence(result.code)); return; } if ("status" in result.value && result.value.status === "joined") { acknowledgeJoin(); return; } if (!("message" in result.value)) return; const reply = result.value; setAnswerStarted(true); if (reply.view && governed.status === "answered") { setArtifactByView((current) => ({ ...current, [reply.view!.id]: governed.artifacts })); } setIndex((current) => ({ ...current, views: reply.view ? [reply.view, ...current.views.filter((row) => row.id !== reply.view?.id)] : current.views, citations: [...current.citations, ...reply.citations], })); scrollToNewest.current = followsNewest.current; setFreshMessageIds([reply.userMessage.id]); setTurns((current) => mergeTurns(withoutPending(current), [localTurn(reply.userMessage), localTurn(reply.message)])); // Reconcile optimistic turns with the durable log's ids and agent fields. retryBefore.current = undefined; try { const conversation = await fetchConversation(); if (!isCurrent()) return; if (conversation.ok) { scrollToNewest.current = followsNewest.current; setFreshMessageIds([]); setTurns((current) => mergeTurns(current.filter((turn) => !batch.joined.has(turn.id) || !conversation.value.turns.some((row) => row.role === "user" && row.text === turn.text && row.at >= turn.at)), conversation.value.turns)); } else setConversationProblem("The latest turn details could not be loaded."); } catch { if (isCurrent()) setConversationProblem("The latest turn details could not be loaded."); } } finally { if (primary) batch.resolve(null); batch.requests.delete(pendingId); if (isCurrent() && !batch.requests.size) { activeChat.current = null; requestInFlight.current = false; setBusy(false); } } }, [alignment, alignmentFields, conversationLoaded, draftBusy, question, target, loadConversation]); const stop = async () => { const batch = activeChat.current; if (!batch || stopInFlight.current) return; stopInFlight.current = true; setStopping(true); try { const result = await stopTurn(); if (activeChat.current !== batch) return; if (!result.ok) { setProblem("This turn could not be stopped. Try again."); return; } activeChat.current = null; batch.resolve(null); batch.requests.forEach(({ controller }) => controller.abort()); conversationGeneration.current += 1; conversationInFlight.current = false; setConversationLoading(false); requestInFlight.current = false; setBusy(false); setAnswerStarted(false); setProblem(""); setAlignment(null); setAlignmentFields([]); const answers = new Set([...batch.requests.values()].map(({ answerId }) => answerId)); setTurns((current) => [...current.filter((turn) => !answers.has(turn.id)), { id: `stopped_${(pending.current += 1)}`, role: "system", door: "app", kind: "text", text: "Stopped.", at: new Date().toISOString(), }]); scrollToNewest.current = followsNewest.current; composerRef.current?.focus(); } catch { if (activeChat.current === batch) setProblem("This turn could not be stopped. Try again."); } finally { stopInFlight.current = false; setStopping(false); } }; useEffect(() => { if (!conversationLoaded || busy || requestInFlight.current) return; const prompt = takePendingAsk(); if (prompt) void ask(undefined, { database: "", prompt }); }, [ask, busy, conversationLoaded]); const submitDraft = async () => { if (!alignment?.draft || !alignmentFields.length || busy || draftBusy || requestInFlight.current) return; const chosenFields = [...alignmentFields]; const generation = alignmentGeneration.current; requestInFlight.current = true; setDraftBusy(true); setDraftProblem(""); try { const result = await draftRequest(alignment.database, chosenFields, alignment.prompt); if (generation !== alignmentGeneration.current) return; if (result.state === "approved") { setApprovalLine(result.approvalLine || ""); requestInFlight.current = false; await ask(chosenFields); } else if (result.state === "pending") { lastDraftCheck.current = Date.now(); setAlignment((current) => current ? { ...current, sent: true } : null); } else { setDraftProblem("The field request could not be completed, so please try again."); } } catch { if (generation === alignmentGeneration.current) setDraftProblem("The field request could not be completed, so please try again."); } finally { requestInFlight.current = false; setDraftBusy(false); } }; useEffect(() => { if (!alignment?.draft || !alignment.sent) return; const recheck = () => { if (busy || draftBusy || requestInFlight.current || Date.now() - lastDraftCheck.current < 10000) return; lastDraftCheck.current = Date.now(); void ask(); }; window.addEventListener("focus", recheck); return () => window.removeEventListener("focus", recheck); }, [alignment, ask, busy, draftBusy]); /** * The rating goes to the server and the SERVER'S copy comes back, rather than the page patching * its own guess: the reason is normalised and cleared there, and a rating that only looked * applied is exactly the shape this module keeps being bitten by. */ const rate = useCallback(async (id: string, rating: "up" | "down" | null, reason?: string) => { const result = await rateMessage(id, rating, reason); if (!result.ok) { setProblem(result.message); return; } setTurns((current) => current.map((turn) => (turn.payload?.id || turn.id) === id ? { ...turn, payload: { ...turn.payload, ...result.value } } : turn)); }, []); const preview = useCallback((qid: string) => { openCancel.current?.(); openCancel.current = openBuiltView(qid); }, []); const empty = turns.length === 0; const thinking = busy && !answerStarted; const composer = (
{approvalLine ?

{approvalLine}

: null} {alignment ?

{alignment.draft ? "Database fields" : "Clarify"}

{alignment.sent ? alignment.draft?.sentMessage : alignment.question}

{alignment.choices.filter((choice) => !alignment.sent || alignmentFields.includes(choice.field)).map((choice) => { const on = alignmentFields.includes(choice.field); const drafted = alignment.draft?.fields.find((field) => field.field === choice.field); const redacted = drafted && (drafted.sample.redacted || ["sensitive", "restricted"].includes(drafted.sensitivity)); return ; })}
{draftProblem ?

{draftProblem}

: null} {alignment.sent ? : }
: null}