import { useEffect, useRef, useState } from "react"; import type { ReactNode } from "react"; import { useEscapeClose } from "../ui/useEscapeClose"; import { TOAST_EVENT } from "../apiContract"; import { useOverlayLayer } from "../customer-grid/OverlaySurface"; import { FolderMark } from "../customer-grid/icons"; import { DbIcon } from "../shell/dbFrame"; import { ASSISTANT_ROUTE } from "../shell/nav"; import type { NavEntry } from "../shell/nav"; /** * ⭐⭐ W35-T47 (R4, contract C2) — ONE STAR, AND THE BEHAVIOUR IS BORROWED WHOLE. * * `useStarred` is B's: the read, the optimistic flip, the reconcile, the toast on refusal, the * generation guard against two writes racing. R4 makes star and "mark important" ONE idea, so a * second client for it here would be the drift that ruling exists to prevent. * * ⛔ THE BUTTON'S MARKUP IS INLINE AND THAT IS NOT LAZINESS — IMPORTING `StarButton` BREAKS A's * GATE. `StarredPage.tsx` imports `shell/Brand`, which reads `import.meta.env.BASE_URL`, and * `verify_wiring.py` COMPILES AND RUNS `query/_test/queryRender.test.tsx` under node as CommonJS: * `import.meta` is ESM-only syntax, node flips the emitted module to ESM, and the run dies with * `ReferenceError: exports is not defined in ES module scope`. Reproduced here first, which is the * only reason it is not a red `web_wiring` in somebody else's lane. * ⚠ SO WHAT IS COPIED IS EIGHT LINES OF MARKUP, using B's own `.st-star` classes and the shared * `StarIcon`, and `query.css` restyles nothing except placement. Posted to B as `NOTE C-16`: if * `StarButton` moves into `starredApi`, this becomes an import. */ import { StarIcon } from "../ui/icons"; import { useStarred } from "../starred/starredApi"; import { duplicateQuery, exportQueryHref, renameQuery, revertQuery, saveQueryToDatabase } from "./queryApi"; import type { SavedQuery } from "./queryApi"; /** * ⭐⭐ W35-T22 (owner item 3) — THE STYLESHEET BELONGS TO THE MODULE THAT RENDERS THE CLASSES, AND * THAT IS THE WHOLE FIX. Owner, verbatim: *"When I click 'Query' toggle, before it loads, it shows * a really ugly outdated format, fix it."* * * â›” MEASURED, not guessed, on a production build. `query.css` was imported ONLY by `QueryPage`, * which the Assistant loads with `lazy()`. Vite splits an async chunk's CSS into its own file, so * all 44 `.qy-rail*` rules landed in `QueryPage-*.css` and the boot stylesheet carried ZERO of * them. But this module — which renders every one of those classes — is imported STATICALLY by * `AssistantPage`, and the rail it exports sits OUTSIDE the `` boundary the workspace is * behind. So flipping the toggle committed the rail in the same frame while its stylesheet was * still one network round trip away: browser-default buttons, default `

` margins, a blue * underlined link. That is the "outdated format". * * âš  It is NOT the Suspense fallback (a bare spinner) and NOT the empty state, the two candidates * the wave listed. Capture of both states: `AutoWiki/waves/wave35/proto/T22-query-flash/`. * * âš  KEEP THE TWIN IMPORT IN `QueryPage.tsx`. Vite emits one stylesheet either way, and the * standalone `#/query` host reaches the page without passing through here. */ import "./query.css"; /** Which label of which row is being typed into. One at a time, by construction. */ function useRefusalToast() { const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); const sequence = useRef(0); const delivered = useRef(0); useEffect(() => { if (!messages.length) return; const through = messages[messages.length - 1].id; for (const message of messages) { if (message.id <= delivered.current) continue; delivered.current = message.id; const text = message.text; window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); } setMessages((current) => current.filter((message) => message.id > through)); }, [messages]); return (text: string) => { if (!text) return; const message = { id: ++sequence.current, text }; setMessages((current) => [...current, message]); }; } interface Editing { id: string; field: "name" | "description"; value: string; } function QueryActionMenu({ anchor, onClose, children }: { anchor: { top: number; right: number } | null; onClose: () => void; children: ReactNode; }) { const panelRef = useRef(null); useOverlayLayer({ panelRef, onDismiss: onClose }); return

{children}
; } /** * â›” THE MENU IS `position: fixed`, AND THAT IS NOT A STYLE PREFERENCE. Its natural home, * `.qy-rail-scroll`, is `overflow-y: auto`, which clips BOTH axes: an absolutely positioned menu * on a row near the bottom of the list renders cut off or not at all, so the reader clicks and * nothing appears. It fails worst on the rows most likely to be used, the ones you scrolled to. * Fixed positioning takes it out of the scroll box entirely, which costs one measurement. * * âš  `MENU_H` is an estimate used ONLY to decide whether to flip upward near the viewport floor. It * does not size anything, so being a little wrong shifts the menu rather than breaking it. */ const MENU_H = 190; function menuAnchor(button: HTMLElement): { top: number; right: number } { const rect = button.getBoundingClientRect(); const below = rect.bottom + 4; return { top: below + MENU_H > window.innerHeight ? Math.max(8, rect.top - MENU_H - 4) : below, right: Math.max(8, window.innerWidth - rect.right), }; } /** Query has no top-right view dropdown: the rail below IS the navigation (owner item 3). */ export function QueryEmpty({ loaded, unnamed = 0 }: { loaded: boolean; unnamed?: number }) { return (
{!loaded ? : unnamed > 0 ? ( <>

Your views could not be opened

The source database is no longer in your current permission scope. Nothing was changed.

) : ( <>

No Query views yet

Ask the assistant for a table or chart. It creates the Query view immediately.

Open the AI assistant )}
); } /** The kind glyph a Query row wears — the same vocabulary the grid's own view rail uses. */ const KIND_MARK: Record = { grid: "Table", list: "List", chart: "Chart", kanban: "Board", calendar: "Calendar", map: "Map", }; export interface QueryGroup { database: string; label: string; icon?: NavEntry["icon"]; views: SavedQuery[]; } /** * âš  GROUPED IN THE ORDER THE DATABASES ARE GRANTED, not by artefact age. The rail is a list of * DATABASES first (owner: "each View correspond to the relevant database"), so a new answer about * Customers must not move the Customers heading — it appears under it. Within a database the * newest is first, which is the order the server already sends. * * ⭐ R14 GAVE THIS LIST A SECOND HOST, which is why the loop is a function and lives HERE rather * than inside `QueryPage`. The merged Assistant surface renders the same rail in its own left * panel; two hosts computing "which views belong to which database" from two copies of one loop * is one question with two normalizers, and the copy that drifts is the one nobody is looking at. * It sits beside `QueryGroup`, the type it builds, and in a module that does NOT import the grid * — a static import from `QueryPage.tsx` would pull `CustomerGrid` into the chat bundle and undo * the lazy boundary the Assistant keeps around it. * * A view whose source database is not in `entries` is dropped: the caller's grant is the wall. */ export function queryGroups(views: SavedQuery[], entries: NavEntry[]): QueryGroup[] { const byDatabase = new Map(); for (const view of views) { const list = byDatabase.get(view.source.database); if (list) list.push(view); else byDatabase.set(view.source.database, [view]); } const out: QueryGroup[] = []; for (const entry of entries) { const list = byDatabase.get(entry.key); if (!list || entry.kind === "group") continue; out.push({ database: entry.key, label: list[0].source.label || entry.label, ...(entry.icon ? { icon: entry.icon } : {}), views: list, }); } return out; } /** * ⭐⭐ OWNER ITEM 3 (2026-08-15) — GROUPED BY SOURCE DATABASE, WHICH IS THE WHOLE INSTRUCTION. * Verbatim: *"these AI generated query should live under the query module. And that each View * correspond to the relevant database. So we need to remove that dumb dropdown that suddenly * appears at the top right of the Database when the AI does query. That's not how we should do * the navigation."* * * â›” THE DROPDOWN WAS NOT THE DEFECT — THE ABSENCE OF NAVIGATION WAS. Deleting it (which the * previous pass did) left Query with no way to move between artefacts at all: the page picked * `known[0]` and every other view the assistant had ever built was unreachable. A surface with * one implicit selection is not "no dropdown", it is no navigation, and the owner asked for the * navigation to be done differently rather than removed. * * âš  AND THIS IS WHERE A DATABASE PUTS ITS VIEWS. `dbFrame.tsx` carries the owner's earlier * sentence — *"the query module should exactly BE looking like the database module, COMPLETELY, * with all the views etc."* — so the rail sits in the slot `CustomerGrid`'s own `ViewSidebar` * occupies on every other database, at the same `--lp-rail-w`. It is a separate component only * because THIS list spans several databases and the grid's rail, by construction, cannot: the * grid is mounted at one scope. */ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: { groups: QueryGroup[]; activeId: string; onSelect: (id: string) => void; onDelete: (id: string) => void; /** * ⭐ The rail OWNS the rename/duplicate calls and hands the host the resulting artefact to * upsert. Two hosts render this list (the standalone page and the merged Assistant surface), so * putting the calls in the hosts would be one question with two implementations, and the copy * that drifts is the one nobody is looking at. */ onChanged?: (view: SavedQuery) => void; }) { // Two-click delete, in the row. A modal for "remove one of my own saved answers" is heavier // than the act; a single click with no confirm loses work to a mis-click on a hover control. const [confirming, setConfirming] = useState(""); const [menuFor, setMenuFor] = useState(""); const [anchor, setAnchor] = useState<{ top: number; right: number } | null>(null); const [editing, setEditing] = useState(null); const menuOpenerRef = useRef(null); const editingFinishedRef = useRef(false); const editingSequence = useRef(0); useEscapeClose(editing !== null, () => { editingSequence.current += 1; editingFinishedRef.current = true; setEditing(null); menuOpenerRef.current?.focus(); }); const beginEditing = (next: Editing) => { editingSequence.current += 1; editingFinishedRef.current = false; setMenuFor(""); setEditing(next); }; // âš  TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured // differently; sharing one slot painted "Saved as ..." in the refusal red. const [notice, setNotice] = useState(""); const refuse = useRefusalToast(); /** * ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans * every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The * hook fires in an effect and reports `phase`, so the control simply is not drawn until the * answer arrives — a star toggled from a list nobody has read would be a guess at its own * current value. */ const stars = useStarred(); const starred = new Set(stars.starred.queries); const said = (message: string) => setNotice(message); const failed = (text: string) => { setNotice(""); refuse(text); }; const commit = async () => { if (!editing || editingFinishedRef.current) return; editingFinishedRef.current = true; const current = editing; const sequence = editingSequence.current; setEditing(null); const result = await renameQuery(current.id, current.field === "name" ? { name: current.value } : { description: current.value }); if (!result.ok) { if (sequence === editingSequence.current) { editingFinishedRef.current = false; setEditing((next) => next ?? current); } failed(result.message); return; } said(""); onChanged?.(result.value); }; /** * âš  THE REPLY IS SHOWN WHETHER OR NOT ANYTHING WAS DROPPED, and the dropped half is the useful * one: a database view carries no aggregation, so "sum of deal value" lands as the rows and not * the sum. Saying so beats a view that looks complete and answers a different question. */ const saveToDatabase = async (view: SavedQuery) => { const result = await saveQueryToDatabase(view.id); if (!result.ok) { failed(result.message); return; } said(result.value.dropped.length ? `Saved as "${result.value.name}". Not carried over: ${result.value.dropped.join(", ")}.` : `Saved as "${result.value.name}" in this database's own views.`); }; /** * ⭐⭐ W35-T25 · CONTRACT C4 (R3) — "Revert to AI original", and the sentence comes FIRST. * * ⛔ THE CONFIRM SAYS WHAT REVERT DOES **NOT** DO, BEFORE IT ACTS, AND R3 REQUIRES THAT WORDING * RATHER THAN SUGGESTING IT. A Query view is live since R2, so a cell somebody changed through * it is a real write to a real record in the source database. Putting the filters back cannot * walk that back, and a reader who assumed otherwise has been told the opposite of the truth at * the one moment they could still have chosen differently. * * ⚠ `window.confirm`, deliberately, and this is the one place in this module that uses it. Every * other destructive door here is a two-click in the row, which works because those are cheap and * reversible (a rename, a delete of one saved answer). This one is neither: it discards work with * no undo, and a two-click cannot carry a sentence. */ const revert = async (view: SavedQuery) => { setMenuFor(""); const ok = window.confirm( `Revert "${view.name}" to the version the assistant built?\n\n` + "This restores the filters, sorting, grouping, visible columns and column widths.\n\n" + "It does NOT undo any record you changed in the source database. Those edits stay."); if (!ok) return; const result = await revertQuery(view.id); if (!result.ok) { failed(result.message); return; } said(`"${result.value.name}" is back to the assistant's version.`); onChanged?.(result.value); }; const duplicate = async (id: string) => { const result = await duplicateQuery(id); // âš  The refusal is the useful half: MAX_ARTIFACTS names its cause and the remedy, and a copy // that silently did not happen is the failure mode this whole module is written against. if (!result.ok) { failed(result.message); return; } said(""); onChanged?.(result.value); onSelect(result.value.id); }; return ( ); } /* * ⛔⛔ `QueryProvenance` IS DELETED (W35-T21, owner item 4 / R2), AND WHAT WENT WITH IT MATTERS. * Owner, verbatim: *"there is a 'Source' button under Query as well. The end user doesn't need to * see this so delete it."* R2 retires the snapshot framing with it, because the two were one * control: the button read "Sources" and the row beside it read the snapshot version. * * âš  THE CITATIONS DID NOT GO. They still reach the grid through `bindingFor(active, citations)` * in `QueryPage`, and they are still RENDERED for a reader in the surface that owns the claim — * the chat, where `AssistantPage::CitationLine` prints one clickable line per citation under the * answer that used it. What R2 removed is a second provenance surface above a grid, not the * auditability R9 asked for. `verify_grid_ux.py::query_preview_shape` asserts exactly that pair: * no provenance chrome on this page, citations still bound. */