Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/assistant/AssistantPage.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 75.5 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/assistant/AssistantPage.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/assistant/AssistantPage.tsx
-
curl -L -o AssistantPage.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/assistant/AssistantPage.tsx
75.5 kB
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<NavEntry[]> | undefined;
export function loadDockGrant(read: () => Promise<NavResult> = fetchNav): Promise<NavEntry[]> {
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 <div className="oip-loading"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" /></div>;
}
function DockGrantFailed() {
return <p className="oip-sentence" role="status">{LOAD_FAILED}</p>;
}
// 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<string, string> = { 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<NavEntry[]>;
}) {
const [grant, setGrant] = useState<NavEntry[] | null>(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 <OpenInPlaceHost granted={granted} modules={hostModules}>
<DockLinkScope own={own} ready={grant !== null} onForeign={foreign}>{children}</DockLinkScope>
</OpenInPlaceHost>;
}
function DockLinkScope({ own, ready, onForeign, children }: {
own: NavEntry[]; ready: boolean; onForeign: (target: InPlaceTarget | null) => void; children?: ReactNode;
}) {
const host = useOpenInPlace();
const api = useMemo<OpenInPlaceApi | null>(() => 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 <OpenInPlaceContext.Provider value={api}>{children}</OpenInPlaceContext.Provider>;
}
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<ReturnType<typeof runQueryTool>> | 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<string, { controller: AbortController; answerId: string; text: string }>;
joined: Set<string>;
restored: Set<string>;
routingReady: boolean;
ready: Promise<ChatRouting | null>;
resolve: (routing: ChatRouting | null) => void;
};
type PendingDelete = { id: string; summary: string; expiresAt: string | number };
type ToolCall = {
name: string; args: Record<string, unknown>; 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<string | Record<string, unknown>>;
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<string, unknown>; 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<AssistantChatMessage> & Partial<Omit<PingPayload, "reason">> & Partial<ScheduledResultEnvelope> & {
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<string | { ticketId?: string; id?: string; title?: string; recordLink?: string }>;
};
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<Result<ConversationPage>> {
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<Result<AgentTurnResult | { kept: boolean }>> {
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 <p className="as-confirm-result" role="status">{resolved || line}</p>;
return <section className="as-confirm" aria-label="Confirm deletion">
<p>{pending.summary}</p>
<div className="as-confirm-actions">
<button type="button" className="as-confirm-button as-confirm-delete" disabled={busy}
onClick={() => void decide("delete")}>Delete</button>
<button type="button" className="as-confirm-button" disabled={busy}
onClick={() => void decide("keep")}>Keep</button>
</div>
{problem ? <p className="as-problem" role="status">{problem}</p> : null}
</section>;
}
const WRITE_LABELS: Record<string, string> = {
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<string, unknown> : {};
// 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 <p className="as-write-report" key={`${call.name}-${position}`}>
<span title={call.name}>{WRITE_LABELS[call.name] || call.name}</span>
{target ? <span className="as-write-target">{target}</span> : null}
{href ? <a href={href} onClick={(event) => {
// 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</a> : null}
</p>;
})}</>;
}
export function AssistantGreeting({ loaded, turnCount }: { loaded: boolean; turnCount: number }) {
if (!loaded || turnCount) return null;
return <p className="as-opening-p">ask me anything about your data</p>;
}
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<boolean> {
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<boolean> = 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<HTMLDivElement | null>(null);
useEffect(() => {
if (heading.current) return observeScheduledResult(heading.current, result.id);
}, [result.id]);
const table = result.table;
const operations: Record<string, string> = {
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 <section className="as-scheduled-result" aria-label="Scheduled result" data-result-id={result.id}>
<div className="as-scheduled-head" ref={heading}>
<p className="as-door">Scheduled</p>
<p className="as-message-text">{worklistText(result.words)}</p>
</div>
{result.ok && table ? <>
<p className="as-scheduled-meta">{result.sourceSyncedAt ? <>Last synced{" "}
<time dateTime={result.sourceSyncedAt}>{new Date(result.sourceSyncedAt).toLocaleString()}</time>
</> : "Sync time unavailable"}</p>
<dl className="as-scheduled-totals" aria-label="Scheduled totals">
<div><dt>Records</dt><dd>{worklistFigure(result.rowCount)}</dd></div>
{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 <div key={index}>
<dt>{worklistText(`${operations[item.fn] || item.fn} ${label ? label[0].toLowerCase() + label.slice(1) : ""}`.trim())}</dt>
<dd>{scheduledFigure(item.value, ["sum", "avg", "min", "max"].includes(item.fn) ? field : undefined)}</dd>
</div>;
})}
</dl>
<p className="as-scheduled-count">{`${Math.min(20, table.rows.length).toLocaleString()} of ${table.total.toLocaleString()} shown`}
{table.unit === "groups" ? " (groups)" : null}</p>
<div className="as-scheduled-scroll" tabIndex={0} role="region" aria-label="Scheduled table">
<table className="as-scheduled-table" aria-label="Scheduled rows">
<thead><tr>{table.header.map((field) => <th scope="col" key={field.key}
className={numeric(field) ? "as-scheduled-number" : undefined}>{worklistText(field.label)}</th>)}</tr></thead>
<tbody>{table.rows.slice(0, 20).map((row, index) => <tr key={index}>
{table.header.map((field, column) => <td key={field.key}
className={numeric(field) ? "as-scheduled-number" : undefined}>{scheduledFigure(row[column], field)}</td>)}
</tr>)}</tbody>
</table>
</div>
{result.dataLink?.startsWith("#/table?") || result.dataLink?.startsWith("#/data?")
? <a className="as-scheduled-link" href={result.dataLink}>Open in Table</a> : null}
</> : <p className="as-scheduled-meta" role="status">{worklistText(result.message || "The saved query could not run.")}</p>}
</section>;
}
export function AssistantTurn({ turn, ...props }: {
turn: AssistantLogTurn;
fresh?: boolean;
} & Omit<Parameters<typeof AssistantMessage>[0], "message">) {
if (turn.kind === "divider") return <div className="as-divider">{turn.text}</div>;
const { fresh, ...messageProps } = props;
const scheduled = scheduledEnvelope(turn);
return <div className={`as-turn${fresh ? " is-new" : ""}`}>
{scheduled ? null : turn.door === "whatsapp" ? <p className="as-door">From WhatsApp</p>
// A ping card carries its own "Wake-up" label; the door marker would say it twice.
: turn.door === "wake" && turn.kind !== "ping" ? <p className="as-door">Wake-up</p> : null}
{scheduled ? <ScheduledResult result={scheduled} />
: turn.kind === "ping" ? <PingCard turn={turn} />
: turn.kind === "notice" ? <NoticeCard turn={turn} />
: turn.role === "system" ? <p className="as-message-text"><LinkedText text={turn.text} /></p>
: <AssistantMessage message={turnMessage(turn)} {...messageProps} />}
</div>;
}
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<string, string> = {
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<string, string> = { 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<string, string> = { ...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<string, unknown>;
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<Result<ArtifactIndex>>;
const readArtifactIndex: ArtifactReader = () => fetchArtifacts();
// One shared `/artifacts` read per page session. A failed read clears it, so the next use retries.
let artifactRead: Promise<Map<string, ArtifactRecord>> | undefined;
let artifactReadGeneration = 0;
export function loadArtifactRecords(read: ArtifactReader = readArtifactIndex, fresh = false): Promise<Map<string, ArtifactRecord>> {
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<string, ArtifactRecord>();
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 <div className="as-artifact">
<div className="as-artifact-row">
<a className="as-artifact-open" href={href} onClick={(event) => { interceptOpen(inPlace, href, event); }}>
<span className="as-preview-name">{record.title}</span>
<span className="as-preview-meta">{ARTIFACT_KIND_LABEL[record.kind]}</span>
</a>
{record.kind === "xlsx" && file ? <a className="as-artifact-download" href={file} download>Download</a> : null}
</div>
{/* A failed load leaves the chip alone, never a broken image. */}
{picturable(record) && !broken ? <img className="as-artifact-image" src={file} alt={record.title}
loading="lazy" onError={() => setBroken(true)} /> : null}
</div>;
}
/** 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<Map<string, ArtifactRecord> | 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 <div className="as-artifacts">{records.map((record) => <ArtifactChip key={record.id} record={record} />)}</div>;
}
/** 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 <DockGrantLoading />;
if (state === "failed") return <DockGrantFailed />;
const record = state.record;
if (!record) return <p className="oip-sentence" role="status">{NOT_AVAILABLE}</p>;
const file = record.fileId ? artifactFileHref(record.fileId) : "";
return <section className="oip-artifact" aria-label={record.title}>
<h3 className="oip-artifact-title">{record.title}</h3>
{ITEM_KIND_LABEL[record.kind] ? <p className="oip-artifact-kind">{ITEM_KIND_LABEL[record.kind]}</p> : null}
{record.kind === "snapshot" ? <SnapshotTable id={record.id} /> : null}
{picturable(record) ? <img className="oip-artifact-image" src={file} alt={record.title} /> : null}
{(record.kind === "xlsx" || record.kind === "pdf") && file
? <a className="oip-artifact-download" href={file} download>Download</a> : null}
</section>;
}
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 <a className="as-citation" href={citation.href}>{queryCitationLabel(citation)}</a>;
}
/** One glyph, drawn once and turned over for the other. R20 asked for thumbs; these are thumbs. */
function ThumbIcon({ down = false }: { down?: boolean }) {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13"
{...(down ? { transform: "rotate(180)" } : {})}>
<path d="M5.6 14.2V6.9h1.5l2.2-4.3a1 1 0 0 1 1.8.9l-.7 2.6h2.4a1 1 0 0 1 1 1.3l-1.1 4.6a1.5 1.5 0 0 1-1.5 1.1H5.6z" />
<path d="M5.6 6.9H2.6v7.3h3" />
</svg>
);
}
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<QueryToolArtifacts | null>(governedArtifacts || null);
const [artifactStatus, setArtifactStatus] = useState("");
const slackRef = useRef<HTMLDivElement | null>(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 (
<article className="as-message as-message--user">
<p className="as-bubble">{message.content}</p>
</article>
);
}
if (message.streaming) {
return <article className="as-message as-message--assistant as-answer-pending" aria-live="off">
{message.toolStep ? <p className="as-tool-step">{message.toolStep}</p> : null}
{message.content ? <p className="as-message-text">{message.content}</p> : null}
</article>;
}
if (message.reason === "query_no_source_matched") {
return <article className="as-message as-message--assistant">
<p className="as-message-text"><LinkedText text={message.content} /></p>
<WriteReport calls={message.toolCalls} onPreview={onPreview} />
{message.pendingResolved ? <p className="as-confirm-result" role="status">{message.pendingResolved}</p>
: message.pendingDelete ? <DeleteConfirmCard pending={message.pendingDelete}
resolved={confirmation} onResolved={onConfirmed} /> : null}
</article>;
}
const provenance = message.provenance;
const sourceFooter = answerSourceFooter(provenance, matching);
const numeric = message.numeric;
return (
<article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
<p className="as-message-text"><LinkedText text={message.content} /></p>
<WriteReport calls={message.toolCalls} onPreview={onPreview} />
{message.pendingResolved ? <p className="as-confirm-result" role="status">{message.pendingResolved}</p>
: message.pendingDelete ? <DeleteConfirmCard pending={message.pendingDelete}
resolved={confirmation} onResolved={onConfirmed} /> : null}
{view && artifacts ? (
<section className="w45-contract-card" aria-labelledby={`query-artifacts-${message.id}`}>
<h4 id={`query-artifacts-${message.id}`}>Query setup</h4>
<div className="w45-artifacts">
{(["filters", "sorts", "group", "hiddenFields", "source"] as const).map((key) => (
<label className="w45-artifact" key={key}>
<span>{key === "hiddenFields" ? "Hidden fields" : key[0].toUpperCase() + key.slice(1)}</span>
<input
defaultValue={JSON.stringify(artifacts[key])}
onBlur={(event) => {
try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
catch { setArtifactStatus(`${key} must be valid JSON.`); }
}}
/>
</label>
))}
</div>
<div className="w45-chip-row">
<button type="button" className="w45-quiet" onClick={async () => {
setArtifactStatus("");
try { await persistQueryArtifacts(view.id, view.view, artifacts); setArtifactStatus("Query setup saved"); }
catch (error) { setArtifactStatus(error instanceof Error ? error.message : "Query setup could not be saved."); }
}}>Save Query setup</button>
<button type="button" className="w45-quiet" onClick={() => setSlackOpen(true)}>
Correct in Slack
</button>
<button type="button" className="w45-quiet" onClick={() => openView(view.id)}>
Open in Loopable
</button>
</div>
{artifactStatus ? <p className="w45-safe" role="status">{artifactStatus}</p> : null}
{slackOpen ? (
<div className="w45-contract-card" role="dialog" aria-label="Slack correction"
ref={slackRef}>
<h4>Slack correction</h4>
<p>Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.</p>
{(["filters", "sorts", "group"] as const).map((key) => <label className="w45-artifact" key={key}>
<span>{key[0].toUpperCase() + key.slice(1)}</span>
<input defaultValue={JSON.stringify(artifacts[key])} onBlur={(event) => {
try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
catch { setArtifactStatus(`${key} must be valid JSON.`); }
}} />
</label>)}
<p className="w45-safe">Draft only. No Slack message was sent.</p>
<button type="button" className="w45-quiet" onClick={() => openView(view.id)}>Open in Loopable</button>
<button type="button" className="w45-quiet" onClick={() => setSlackOpen(false)}>
Close
</button>
</div>
) : null}
</section>
) : null}
{numeric && numeric.value !== null && numeric.value !== undefined ? (
<p className="as-numeric">
<span className="as-numeric-label">{numeric.label}</span>
<strong className="as-numeric-value">{numeric.value.toLocaleString()}</strong>
</p>
) : null}
{view ? (
<button type="button" className="as-preview" onClick={() => openView(view.id)}>
<span className="as-preview-name">{view.name}</span>
{/* ⚠ ONE expression, not three text nodes. `Open the {x} in Query` renders under SSR as
`Open the<!-- -->table<!-- --> in Query`, so a check reading the sentence back sees
a string nobody wrote [[ui-invisible-to-assertions]]. */}
<span className="as-preview-meta">{`Open the ${KIND_LABEL[view.kind] ?? view.kind} in Artifacts`}</span>
</button>
) : null}
<ArtifactChips entries={message.artifacts} />
{/* 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 ? <div className="as-answer-foot">
{matching.length ? (
<footer className="as-citation" aria-label="Answer sources">
<button type="button" className="as-sources-btn" aria-expanded={openSources}
onClick={() => setOpenSources(!openSources)}>{sourceFooter}</button>
</footer>
) : null}
{onRate ? (
<div className="as-rate">
<button type="button" aria-label="Helpful" aria-pressed={message.rating === "up"}
className={"as-rate-btn" + (message.rating === "up" ? " is-on" : "")}
onClick={() => { setAskWhy(false); onRate(message.id, message.rating === "up" ? null : "up"); }}>
<ThumbIcon />
</button>
<button type="button" aria-label="Not helpful" aria-pressed={message.rating === "down"}
className={"as-rate-btn" + (message.rating === "down" ? " is-on" : "")}
onClick={() => {
if (message.rating === "down") { setAskWhy(false); onRate(message.id, null); return; }
setAskWhy(true); onRate(message.id, "down");
}}>
<ThumbIcon down />
</button>
{message.rating === "down" && !askWhy && message.ratingReason ? (
<span className="as-rate-why-said">{message.ratingReason}</span>
) : null}
</div>
) : null}
</div> : null}
{onRate && askWhy && message.rating === "down" ? (
<form className="as-rate-why" onSubmit={(event) => {
event.preventDefault(); setAskWhy(false); onRate(message.id, "down", why.trim());
}}>
<input className="as-rate-input" value={why} aria-label="What was wrong"
placeholder="What was wrong? Optional."
onChange={(event) => setWhy(event.currentTarget.value)} />
<button type="submit" className="as-rate-send">Send</button>
</form>
) : null}
{matching.length && openSources ? (
<div className="as-sources-list">
{matching.map((citation) => <CitationLine key={citation.id} citation={citation} />)}
</div>
) : null}
</article>
);
}
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<QueryIndex>(initialIndex);
const [turns, setTurns] = useState<AssistantLogTurn[]>([]);
const [hasMore, setHasMore] = useState(false);
const [conversationLoaded, setConversationLoaded] = useState(false);
const [conversationLoading, setConversationLoading] = useState(true);
const [conversationProblem, setConversationProblem] = useState("");
const [confirmations, setConfirmations] = useState<Record<string, string>>({});
const [freshMessageIds, setFreshMessageIds] = useState<string[]>([]);
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<Record<string, QueryToolArtifacts>>({});
const [alignment, setAlignment] = useState<null | {
prompt: string; database: string; resumeToken: string;
question: string; choices: Array<{ field: string; label: string }>; maxSelections: number;
routed?: RoutedTo;
draft?: SemanticDraft; sent?: boolean;
}>(null);
const [alignmentFields, setAlignmentFields] = useState<string[]>([]);
const [draftBusy, setDraftBusy] = useState(false);
const [draftProblem, setDraftProblem] = useState("");
const [approvalLine, setApprovalLine] = useState("");
const composerRef = useRef<HTMLTextAreaElement | null>(null);
const alignmentRef = useRef<HTMLElement | null>(null);
const requestInFlight = useRef(false);
const activeChat = useRef<ChatBatch | null>(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<HTMLDivElement | null>(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<string | undefined>(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<ChatRouting | null>((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<ReturnType<typeof submitChat>>;
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 = (
<div className="as-composer">
{approvalLine ? <p className="as-draft-state" role="status">{approvalLine}</p> : null}
{alignment ? <section ref={alignmentRef} className={`w45-contract-card${alignment.draft ? " as-draft-card" : ""}`} aria-label="Alignment question">
<h4>{alignment.draft ? "Database fields" : "Clarify"}</h4>
<p className={alignment.sent ? "as-draft-state" : undefined} role={alignment.sent ? "status" : undefined}>
{alignment.sent ? alignment.draft?.sentMessage : alignment.question}
</p>
<div className="w45-chip-row">{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 <button type="button" className={`w45-chip ${on ? "is-on" : "is-off"}${drafted ? " as-draft-field" : ""}`} key={choice.field}
title={drafted?.why} disabled={busy || draftBusy || alignment.sent}
aria-pressed={on} onClick={() => setAlignmentFields((current) => on
? current.filter((field) => field !== choice.field)
: current.length < alignment.maxSelections ? [...current, choice.field] : current)}>
<span>{choice.label}</span>
{drafted ? <>
<span className="as-draft-detail">{drafted.role} · {drafted.dataType}</span>
<span className="as-draft-detail">{redacted ? "Redacted"
: [...drafted.sample.values, ...drafted.sample.sample].slice(0, 3).join(", ") || "No populated values"}</span>
</> : null}
</button>;
})}</div>
{draftProblem ? <p className="as-draft-state" role="status">{draftProblem}</p> : null}
{alignment.sent ? <button type="button" className="w45-quiet" disabled={busy || draftBusy}
onClick={() => { lastDraftCheck.current = Date.now(); void ask(); }}>Check again</button>
: <button type="button" className="w45-quiet" disabled={!alignmentFields.length || busy || draftBusy}
onClick={() => alignment.draft ? void submitDraft() : void ask(alignmentFields)}>
{alignment.draft ? alignment.draft.canApprove ? "Approve and answer" : "Send to administrators"
: "Resume with approved selection"}
</button>}
</section> : null}
<div className="as-field">
<textarea
ref={composerRef}
className="as-prompt"
value={question}
rows={1}
placeholder="Ask the assistant…"
aria-label="Ask the assistant"
onChange={(event) => setQuestion(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); void ask(); }
}}
/>
<div className="as-field-foot">
{/* R112: Memory is one small icon. The word stays as the accessible text, hidden by CSS. */}
<button type="button" className="as-memory-button as-memory-open" aria-expanded={memoryOpen}
aria-haspopup="dialog" aria-label="Memory" title="Memory"
onClick={() => setMemoryOpen((value) => !value)}>Memory</button>
{busy ? <button type="button" className="as-stop" disabled={stopping}
onClick={() => void stop()}>Stop</button> : null}
{/* R116: no model or database picker. The server routes the question and picks the model. */}
<button type="button" className="as-send" aria-label="Send"
disabled={stopping || draftBusy || !conversationLoaded || !question.trim()} onClick={() => void ask()}>
<svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
<path d="M8 13V3.6M4 7.4 8 3.4l4 4" />
</svg>
</button>
</div>
</div>
{/* No source row: the assistant reads every database the caller can reach. What remains is
the one case the reader still has to be told about, which is having none at all. */}
{databases.length === 0 && loaded ? (
<div className="as-chips">
<p className="as-chips-empty">No databases are shared with your account yet.</p>
</div>
) : null}
</div>
);
// ⛔ `aria-label` is "Assistant", not "AI assistant" (W34-T13, corrected at QA 2026-08-17).
// An aria-label IS a label — it is what a screen reader announces this region as — so the rail
// reading Assistant while this said AI assistant left the rename half-done in the one place
// sighted QA never looks.
return (
<OpenInPlaceHost granted={granted} modules={PAGE_MODULES}>
<div className="as-chat" aria-label="Assistant">
<main className="as-conversation">
<div className="as-stream" ref={streamRef} onScroll={onConversationScroll}
aria-busy={conversationLoading}>
<div className="as-column">
{empty && conversationLoaded ? <ModuleHomeHead title="Assistant" module="assistant" /> : null}
<div className={`as-skeleton${conversationLoading ? "" : " as-skeleton--idle"}`}
role={conversationLoading ? "status" : undefined} aria-hidden={!conversationLoading}
aria-label={conversationLoading ? "Loading conversation" : undefined} />
{empty ? <div className="as-opening"><AssistantGreeting loaded={conversationLoaded}
turnCount={turns.length} />
<SuggestionChips granted={granted} loaded={conversationLoaded} turnCount={turns.length}
busy={busy} onAsk={(database, prompt) => void ask(undefined, { database, prompt })} />
</div> : null}
{turns.map((turn) => {
const message = turnMessage(turn);
return <AssistantTurn key={turn.id} turn={turn}
fresh={freshMessageIds.includes(message.id)}
view={message.viewId ? viewById.get(message.viewId) : undefined}
citations={index.citations} onPreview={preview}
governedArtifacts={turn.payload?.governedArtifacts ||
(message.viewId ? artifactByView[message.viewId] : undefined)}
onRate={turn.role === "assistant" && turn.kind === "text" && !message.id.startsWith("pending_")
? rate : undefined}
confirmation={message.pendingDelete ? confirmations[message.pendingDelete.id] : undefined}
onConfirmed={(id, line) => setConfirmations((current) => ({ ...current, [id]: line }))} />;
})}
{thinking ? <TypingIndicator /> : null}
</div>
</div>
<div className="as-dock">
<div className="as-column">
{conversationProblem ? <p className="as-problem" role="status">
{conversationProblem}{" "}
<button type="button" className="as-retry" disabled={conversationLoading}
onClick={() => void loadConversation(retryBefore.current)}>Try again</button>
</p> : null}
{problem ? <p className="as-problem" role="status">{problem}</p> : null}
{composer}
</div>
</div>
</main>
{memoryOpen ? <MemoryPanel open={memoryOpen} onClose={() => setMemoryOpen(false)} granted={granted} /> : null}
</div>
</OpenInPlaceHost>
);
}
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<NavEntry[]> | undefined;
export function loadDockGrant(read: () => Promise<NavResult> = fetchNav): Promise<NavEntry[]> {
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 <div className="oip-loading"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" /></div>;
}
function DockGrantFailed() {
return <p className="oip-sentence" role="status">{LOAD_FAILED}</p>;
}
// 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<string, string> = { 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<NavEntry[]>;
}) {
const [grant, setGrant] = useState<NavEntry[] | null>(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 <OpenInPlaceHost granted={granted} modules={hostModules}>
<DockLinkScope own={own} ready={grant !== null} onForeign={foreign}>{children}</DockLinkScope>
</OpenInPlaceHost>;
}
function DockLinkScope({ own, ready, onForeign, children }: {
own: NavEntry[]; ready: boolean; onForeign: (target: InPlaceTarget | null) => void; children?: ReactNode;
}) {
const host = useOpenInPlace();
const api = useMemo<OpenInPlaceApi | null>(() => 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.