// --------------------------------------------------------------------------- // shell/Shell.tsx — the STANDALONE React shell (wave-4 scaffold; EXIT wave 1 // gives it a real door and a real nav). // // WHAT THIS IS. The successor-shaped outer frame the 2026-07-23 decision named // ("React over a thin API — the same contract the OM-6 MCP server exposes"). // It STRANGLES, it does not replace: exactly one surface is native today — the // Customer table, the component tree the Streamlit embed already ships — and // every other surface is an honest link into the current application. A page // moves here when its data contract is served by the API, never before; the // nav never pretends otherwise. // // WHAT CHANGED IN EXIT WAVE 1 (X5 + X6): // · The door is per-user (`core/users` accounts over X2/X3), not a shared // HTTP Basic password. SHELL.md's ladder step-1 "SANDBOX user key until // real auth lands" is SUPERSEDED — there are real sessions from day one. // · The nav is SERVER-FILTERED and registry-driven (`GET /api/v1/nav`), not a // static array hand-mirroring core/registry.py. What a user sees is what // `may_open` granted them. // · There is NO client-side nav fallback and no hard-coded surface. An // undeclared surface is denied — including by omission from the payload. // // WHAT THIS IS NOT. Not Next.js — recorded decision: one component tree, one // build system (the same Vite workspace whose OTHER config builds the embed // bundle), no SSR/SEO need behind a login gate. The shell frame is the cheap, // swappable part; the components are the asset. Revisit at the white-label // trigger (OM-7), where multi-tenant routing might earn Next. // // Routing is a ~20-line hash router on purpose: a handful of routes do not earn // a dependency the embed bundle would have to keep excluded. // --------------------------------------------------------------------------- import { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; /* S72-T05 (R111): every sidebar row draws from `@phosphor-icons/react`, imported PER ICON (the package root pulls the whole set into dev). Outline `regular` at rest, `fill` on the active row. */ import { AppWindow } from "@phosphor-icons/react/dist/csr/AppWindow"; import { ArrowUUpLeft } from "@phosphor-icons/react/dist/csr/ArrowUUpLeft"; import { Bell } from "@phosphor-icons/react/dist/csr/Bell"; import { Brain } from "@phosphor-icons/react/dist/csr/Brain"; import { Cards } from "@phosphor-icons/react/dist/csr/Cards"; import { CaretDown } from "@phosphor-icons/react/dist/csr/CaretDown"; import { CircleDashed } from "@phosphor-icons/react/dist/csr/CircleDashed"; import { Clock } from "@phosphor-icons/react/dist/csr/Clock"; import { Database } from "@phosphor-icons/react/dist/csr/Database"; import { Eye } from "@phosphor-icons/react/dist/csr/Eye"; import { House } from "@phosphor-icons/react/dist/csr/House"; import PanelToggleIcon from "./PanelToggleIcon"; import { Plug } from "@phosphor-icons/react/dist/csr/Plug"; import { Table } from "@phosphor-icons/react/dist/csr/Table"; import { ArtifactsGlyph } from "./icons"; import { OverlayScroll } from "../ui/OverlayScroll"; // ⭐ W53-T35 / C4 — the shell's own sheet, imported here the way `NavExtras.tsx` imports // `navExtras.css`. It carries the one rule that keeps the DATABASE mark out of the folder // fill (`styles/wave45/data-applications.css` paints every `.cg-folder-mark path` brand // purple, which is right for a folder and is owner instruction 26's complaint for a // database). It is scoped by two classes, so it wins on specificity and does not rest on // import order — the sheet it overrides ships in a lazy chunk. import "./shell.css"; import "../styles/sdlc73/shell.css"; // S85-T157: the member view indicator's rules. The grid also imports this sheet, and its two grid // rules hold on specificity, so loading it with the shell changes no grid cascade. import "../styles/wave46/chrome.css"; import { clearViewAs, exitViewAs, viewAsActive, viewAsMode, viewAsRefusal } from "../settings/viewAs"; /* ⛔ `import { createPortal } from "react-dom";` STOOD HERE AND IS DELETED (W41-T32). The database flyout was this file's ONLY portal — checked by the compiler, not by reading: `tsc -b` named it (TS6133) the moment the panel went, which is the unused-locals check doing the remembering exactly as `PlusMark`'s tombstone further down predicted it would. ⚠ AND `npx tsc --noEmit` DID NOT CATCH IT — only `npm run build`'s `tsc -b` did. The two are not the same check here; a lane that runs the first and skips the second gets a false green on every symbol it orphans. */ import type { ComponentType, MouseEvent as ReactMouseEvent, ReactNode, RefObject } from "react"; /** * ⭐ WAVE-27 item 34 (I5) — ROUTE-LEVEL CODE SPLITTING. * * Six surfaces that are already mounted CONDITIONALLY (an automation route, the settings modal, * the connectors page, home, the template picker, the alerts pane) become their own chunks. The * shell downloads them when a person actually opens one — which for most sessions is never, and * for every session is not the first paint. * * ⚠ EVERY ONE OF THESE WAS ALREADY BEHIND A CONDITION IN THE JSX, and that is what makes the * split real rather than cosmetic: a `lazy` whose mount renders unconditionally downloads on the * first paint anyway and buys a Suspense boundary for nothing. `CustomerGrid` is lazy too: * only routes that mount a grid need its component chunk. The shell's synchronous cache and * scope helpers remain eager because invalidation and alert scope reads must precede navigation * and session changes. * * ⚠ `SettingsModal` is a NAMED export, so its loader maps to `{ default }`. A default-import * `lazy()` over a named export fails at RUNTIME, on click, and only for that one surface. */ const AutomationSurface = lazy(() => import("../automation/AutomationSurface")); // ⭐⭐ WAVE 37 · T48 — `lazy`, like the twelve surfaces below it. This was the ONE eager import // left in the shell, and it is the biggest module in the tree. See `App.tsx` for the measurement. // ⚠ IT JOINS `Lazily`, NOT A BARE `Suspense`: the shared wrapper carries the ErrorBoundary, so a // chunk that fails to load names the surface it was for instead of blanking the frame. const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid")); const TemplateApplicationPage = lazy(() => import("../customer-grid/viewModes") .then((m) => ({ default: m.TemplateApplicationPage }))); import { APP_OPEN_TIMEOUT_MS, AppReason } from "../apps/AppReason"; import { clearCustomersCache, currentSurfaceScope, refreshCustomersCache } from "../customer-grid/apiBridge"; import { OverlayProvider } from "../customer-grid/OverlaySurface"; import { appPathHash, dataPathHash, readDataPath } from "../customer-grid/dataPath"; import type { DataDatabase } from "../customer-grid/dataPath"; import "../styles/wave55/apps.css"; // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows, // so it no longer has to tell the grid that it did. import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract"; import { armDeadline } from "../net/deadline"; // Envelope dashboards are conditional routes; their renderer is not needed to paint the shell. // Locked production build: entry 422.44 -> 393.41 kB (422,447 -> 393,416 bytes on disk). // The mount keeps PageSurface's heading and spinner visible while its chunk loads. const PageSurface = lazy(() => import("../pages/PageSurface").then((m) => ({ default: m.PageSurface }))); const SettingsModal = lazy(() => import("../settings/SettingsModal").then((m) => ({ default: m.SettingsModal }))); import type { SettingsSection } from "../settings/SettingsModal"; import { NOTIFICATIONS_SETTINGS_EVENT } from "../settings/settingsApi"; import { connectorSetupRoute, retiredSettingsRoute } from "../settings/permsModel"; import { ITEM_DELETED_EVENT, sameDeletedItem } from "../starred/starredApi"; import type { DeletedItem } from "../starred/starredApi"; import { Brand } from "./Brand"; import { ErrorBoundary } from "./ErrorBoundary"; import { ToastStack } from "./ToastStack"; import LoginPage from "./LoginPage"; import FreezeNotice, { useFreezeNotice } from "./FreezeNotice"; import { APP_ROUTE, ARTIFACTS_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, DATA_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INTELLIGENCE_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, NAV_ATTEMPTS, NAV_MALFORMED_STATUS, NAV_RETRY_DELAYS_MS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, agentAddressHash, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, hasVisibleRailSlot, postOpened, dataAddressHash, readAgentAddress, readDataAddress, reportNavTimeout, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, shapeNav, splitChrome } from "./nav"; import { parseApplicationTemplates, readApplicationPageAddress, resolveLegacyApplicationPage } from "./nav"; import type { LegacyApplicationPage } from "./nav"; import type { ApplicationTemplate, NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent } from "./nav"; // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one. // ⛔ W53-T35 — `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears the library `Database` // (S72-T05, R111), and `dbFrame.tsx` keeps // exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only // `gridScopeFor` is read from this module now. import { gridScopeFor } from "./dbFrame"; // W51-T31 — the shell's overlays join the ONE Escape stack (C8 / DESIGN.md §4). Every // registration below is gated on that overlay's OWN open flag, never on `true`: the arbiter // preventDefaults and stops propagation on a claimed Escape, and Escape is also the browser's // cancel-this-drag key for the rail's folder drag-and-drop. import { useEscapeClose } from "../ui/useEscapeClose"; import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay"; import { BodyPortal } from "../customer-grid/OverlaySurface"; import { OPEN_APP_TEMPLATE_EVENT } from "../sheet/templates/templatesApi"; import { AppMark } from "../apps/templateMarks"; import type { TemplateModule } from "../sheet/templates/templatesApi"; /* ⭐ W35-T09 — the assistant's EXISTING door for opening an AI-built view: hash + a retry ladder, returning a canceller. A second emit here would be a second answer. */ import { openBuiltView } from "../assistant/AssistantPage"; const HomePage = lazy(() => import("../home/HomePage")); const SheetGalleryPage = lazy(() => import("../home/HomePage").then((m) => ({ default: m.SheetGalleryPage }))); const AgentsGalleryPage = lazy(() => import("../home/HomePage").then((m) => ({ default: m.AgentsGalleryPage }))); /** S67-T35: automation rows that are a connector's own schedule, never a user's Agent. */ const BACKGROUND_SYNC_SYSTEMS = new Set(["odoo_sync"]); const TemplatePicker = lazy(() => import("../home/TemplatePicker")); const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage")); const CollectionPage = lazy(() => import("../apps/CollectionPage")); const FinanceWorkspace = lazy(() => import("../app/FinanceWorkspace")); // W63-T06 — AI API is chrome, like Connectors and Sheet. It deliberately stays local to the // shell because this lane cannot widen nav.ts's file fence; unknown hash routes already pass // through canonicalRoute unchanged and are mounted by an explicit branch below. const AI_API_ROUTE = "ai-api"; const SIGNED_OUT_EVENT = "aios:signed-out"; function showToast(text: string, tone: "info" | "error" = "info") { window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone } })); } // Capture notice clicks before the lazy surface exists, then forward the original event once. if (typeof window !== "undefined") { window.addEventListener(AUTOMATION_OPEN_EVENT, (event) => { void import("../automation/AutomationSurface") .then(({ receiveAutomationOpen }) => receiveAutomationOpen(event)) .catch(() => { /* The route's ErrorBoundary reports a failed chunk load. */ }); }); } /** * ⭐⭐ WAVE 49 · T01 (owner rulings R1, R2, R30) — THE SHEET MODULE. * * Built on the CONNECTORS pattern, not the `_BUILDERS` page pattern: a route constant, a lazy * page, a rail row. `platform/core/registry.py::REGISTRY` rows are dashboard MODULES, and Data and * Connectors are chrome route constants with no row there — so Sheet gets none either. ⛔ AND IT * MUST NOT: every provisioned tenant carries a restricted `modules` list (`['analyst','automation']` * on all three today) and `/nav` silently OMITS a registry key outside it, so a `registry.py` row * would make Sheet invisible in every tenant on the platform while every gate stayed green. That * is the trap `nav.ts::QUERY_ROUTE` is annotated with by name. * * ⚠ THE ROUTE CONSTANT LIVES IN `../sheet` RATHER THAN IN `./nav` BESIDE ITS SIBLINGS, because * T01's file fence does not include `nav.ts`. Consequence, read rather than assumed: `sheet` is * absent from `nav.ts::CHROME_ROUTES`, whose only runtime consumer is `firstDestination` (the * LANDING question) — and `sheet` is not in `LANDING_PREFERENCE`, so nothing behaves differently. * `#/sheet` is reachable because the hash normaliser below rewrites only `LOGIN_ROUTE` and the * empty hash, and `resolveRoute` answers an unknown key with `undefined`, which lands on this * file's own `route === SHEET_ROUTE` branch. Folding the constant into `CHROME_ROUTES` later is * additive and safe; it is recorded in T01's handoff rather than done behind the fence. */ import { SHEET_ROUTE } from "../sheet"; const SheetPage = lazy(() => import("../sheet/SheetPage")); /* ⭐ WAVE 35 · T06 (contract C6, wiring W2) — the three account surfaces, session B's tree. Lazy like every other page here: none of them is on the path to first paint, and all three are behind a menu the user has to open. Default exports, as B published them — `lazy()` over a NAMED export fails at RUNTIME, on click, and only for that one surface (the note at the top of this file). */ const FeedbackPage = lazy(() => import("../account/FeedbackPage")); const UsagePage = lazy(() => import("../account/UsagePage")); const SubscriptionPage = lazy(() => import("../account/SubscriptionPage")); // WAVE 23 C9 (W23-W2) — SESSION D's public page. A STATIC import, not a lazy one: the wave's own // rule is that a required import fails the build when the file is not there, which is the whole // difference between a mount and an intention (verify_wiring's header). import FormPublic from "../forms/FormPublic"; // ⚠ EAGER, not `lazy()`, and deliberately — same call as `FormPublic` beside it. A published link // is a stranger's FIRST request; a lazy chunk would cost them a second round trip before anything // paints, to save a signed-in user bytes they have already paid for. The page imports nothing // from `customer-grid/**`, so it drags no spreadsheet engine along with it. import PublishedView from "../publish/PublishedView"; import JoinPage from "../signup/JoinPage"; import { deleteModuleFolder, financeNavigation, mergeRecents, moveModuleItems, parseModuleFolderIndex, saveModuleFolder } from "../home/homeModel"; import type { AutomationTile, ModuleFolderIndex } from "../home/homeModel"; import type { ApplicationTile } from "../home/HomePage"; // ⭐ WAVE 24 item 13 (R10, wiring W24-W3) — Home's Automations section. // ⚠ WAVE 26 ITEM 18 (R14): `stateOf` came out of this import with Home's status dot. The old note // here said it was imported rather than re-derived because it is the ONE place "is this running" // is decided — still true, and still why nobody should re-add a local copy; the frame simply has // no reason to ask any more. `listAutomations` brings the credentials and the error shape with // it, so the frame adds a fetch, not a protocol. import { listAutomations, listVoiceAgents } from "../automation/automationApi"; import { CreateNewRow, RowMenu, SchemaDrawer } from "./NavExtras"; /** One revisioned Data index serves both the gallery and the database rail. */ function useDataFolderIndex(owner: string | null, notify: (message: string) => void) { const [state, setState] = useState<{ owner: string | null; index: ModuleFolderIndex | null; error: string }>( { owner: null, index: null, error: "" }); const [saving, setSaving] = useState(false); const [reload, setReload] = useState(0); const current = useRef(state); current.current = state; const activeOwner = useRef(owner); activeOwner.current = owner; const generation = useRef(0); const pending = useRef(false); const read = async (signal: AbortSignal) => { const response = await fetch(`${API_V1}/module-index/data`, { credentials: CREDENTIALS, signal }); const body = await response.json(); const index = response.ok ? parseModuleFolderIndex(body?.index) : null; if (!index) throw new Error("Folders could not be loaded. Reload folders to retry."); return index; }; useEffect(() => { const controller = new AbortController(); const epoch = ++generation.current; pending.current = false; setSaving(false); setState({ owner, index: null, error: "" }); const timer = setTimeout(() => controller.abort(), 20000); if (owner) void read(controller.signal).then((index) => { if (epoch === generation.current) setState({ owner, index, error: "" }); }).catch(() => { if (epoch === generation.current) setState({ owner, index: null, error: "Folders could not be loaded. Reload folders to retry." }); }).finally(() => clearTimeout(timer)); return () => { clearTimeout(timer); generation.current += 1; controller.abort(); }; }, [owner, reload]); const save = useCallback(async (next: ModuleFolderIndex): Promise => { const previous = current.current; if (!owner || previous.owner !== owner || !previous.index || previous.error || pending.current || next.rev !== previous.index.rev) return false; const epoch = generation.current; const active = () => epoch === generation.current && activeOwner.current === owner; pending.current = true; setSaving(true); current.current = { owner, index: next, error: "" }; setState(current.current); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 20000); try { const response = await fetch(`${API_V1}/module-index/data`, { method: "PUT", credentials: CREDENTIALS, signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify(next), }); if (!active()) return false; if (response.status === 409) { const index = await read(controller.signal); if (!active()) return false; current.current = { owner, index, error: "" }; setState(current.current); notify("Folders changed somewhere else. Reloaded folders; try again."); return false; } const body = await response.json(); const index = response.ok ? parseModuleFolderIndex(body?.index) : null; if (!index) throw new Error("The folder change was not saved. Reload folders to retry."); if (!active()) return false; current.current = { owner, index, error: "" }; setState(current.current); return true; } catch { if (active()) { const error = "The folder change could not be confirmed. Reload folders to retry."; current.current = { ...previous, error }; setState(current.current); notify(error); } return false; } finally { clearTimeout(timer); if (active()) { pending.current = false; setSaving(false); } } }, [owner, notify]); return { index: state.owner === owner ? state.index : null, error: state.owner === owner ? state.error : "", saving, save, refresh: () => { generation.current += 1; setReload((value) => value + 1); } }; } /** S68-T54 (R37, C14): Artifacts, where everything the agent made lives; it hosts the Query page * for a saved Query answer, and `#/query` lands here (`nav.ts::REWRITTEN_ROUTES`). */ const ArtifactsPage = lazy(() => import("../artifacts/ArtifactsPage")); /** * ⭐⭐ 2026-08-14 (owner item 2) — THE AI ASSISTANT, UNBOARDED. * * ⛔ AND THE `ai-agent` MODULE IS GONE, WHICH IS THE SAME DECISION SEEN FROM THE OTHER SIDE. * Owner, verbatim: *"Remove the 'AI agent' module completely. previous wave did not follow * instruction. AI assistant module IS AI agent module. So no need to separate it like that."* * Wave 33's own note beside that rail row had already reached the same conclusion and declined to * act on it (*"that row's destination IS dead … retiring it in favour of this one looks right"*), * raising it as ASK C-9. This is the answer to that ask: ONE AI door, and it is this one. * * ⚠ The `ai_agent` automation ACTION KIND is a different thing and stays — it is a STEP inside a * flow (`automation_engine.py`), not a module, and `POST /automations/draft` behind it is still * mounted and still gated (`api/verify_automation.py::section_w33_ai_agent`). */ const AssistantPage = lazy(() => import("../assistant/AssistantPage")); // C3: the lane builds without the page, then loads lane G's default export after integration. const intelligencePages = import.meta.glob<{ default: ComponentType<{ initialPath?: string; principalKey?: string }> }>("../intelligence/IntelligencePage.tsx"); const loadIntelligencePage = intelligencePages["../intelligence/IntelligencePage.tsx"]; const IntelligencePage = loadIntelligencePage ? lazy(loadIntelligencePage) : null; // C3 permits an empty glob until the page lane joins this shell. const codeAppPages = import.meta.glob<{ default: ComponentType<{ applicationId: string }> }>("../apps/code/CodeAppPage.tsx"); const loadCodeAppPage = codeAppPages["../apps/code/CodeAppPage.tsx"]; const CodeAppPage = loadCodeAppPage ? lazy(loadCodeAppPage) : null; const customerCardPages = import.meta.glob<{ default: ComponentType<{ applicationId: string }> }>("../apps/customer-card/CustomerCardPage.tsx"); const loadCustomerCardPage = customerCardPages["../apps/customer-card/CustomerCardPage.tsx"]; const CustomerCardPage = loadCustomerCardPage ? lazy(loadCustomerCardPage) : null; const customerCardPublicPages = import.meta.glob<{ default: ComponentType<{ slug: string }> }>("../publish/CustomerCardPublic.tsx"); const loadCustomerCardPublic = customerCardPublicPages["../publish/CustomerCardPublic.tsx"]; const CustomerCardPublic = loadCustomerCardPublic ? lazy(loadCustomerCardPublic) : null; // C2: the App screens this build carries; the wizard offers no template whose view is missing. const APP_VIEW_FILES = new Set(Object.keys(import.meta.glob("../apps/?*/AppView.tsx"))); /** * Item 34's Suspense boundary, one definition for all six surfaces. * * ⛔ THE FALLBACK IS DELIBERATELY EMPTY, and that is a design decision rather than a stub. The * standing R6 rule is that this product shows a shared spinner mark and never load TEXT * (`verify_icons` asserts it across every source file, so a "Loading..." here would go red). * These chunks are tens of kilobytes off the same origin that just served the shell, so the * honest choice between a flash of a spinner and a frame of nothing is nothing — a spinner that * appears and vanishes within one frame reads as a glitch, not as progress. * * ⭐ WAVE 30 (R5) — AND AN ERROR BOUNDARY, INSIDE THE HELPER RATHER THAN AT SIX CALL SITES. * Three of these six (`TemplatePicker`, `SettingsModal`, `AlertsPane`) are siblings of `
`, * so the content-area boundary below cannot cover them; putting it here covers all six with one * edit. It also catches what `Suspense` alone cannot: a REJECTED chunk fetch. `lazy()` throws its * rejection at render, which before today unmounted the whole product because one deploy-time * cache miss made a modal's JavaScript unreachable. */ /** ⭐ WAVE 37 · T06 (R7) — is `route` a REAL surface this session was not granted? * * Returns its LABEL (so the placeholder can name what was knocked on) or `""`. * * ⛔ THE TABLE IS EXPLICIT AND SHORT ON PURPOSE. A generic "any route with no entry" rule would * board every stale bookmark and every hand-typed key, which is precisely what the `!active` * fallback to Home already handles correctly and deliberately. Only a surface that REALLY EXISTS * can be honestly called under construction; anything else is a lie about a feature. * The registry grants decide access. Assistant and Artifacts share `analyst`. * * ⛔⛔ AND IT MUST READ **BOTH** BUCKETS, WHICH IS THE BUG THIS FUNCTION SHIPPED WITH FOR AN HOUR. * The first version asked `entries` alone. `splitChrome` sends every page with `chrome === * "utility"` to `utility` and everything else to `entries` — and `analyst` is a UTILITY page, which * is why the shell's own `findAnalyst(utility)` exists twenty lines below. So `entries.some(key === * "analyst")` was ALWAYS false and the Assistant read "Under construction" **for everyone, * administrators included**. It was found by looking at a screenshot taken for a different ticket. * ⭐ THE LESSON IS THE ONE THIS WAVE ALREADY BOOKED TWICE (`NOTE C-14`, amendment A21): reading the * SYMBOL and not the DATA IT RESOLVES AGAINST. `entries` is a true name for a collection that does * not contain what this function needed. */ function boardedFor( route: string, entries: ReadonlyArray<{ key: string }>, utility: ReadonlyArray<{ key: string }>, ): string { const BOARDED: ReadonlyArray<[string, string, string]> = [ [ASSISTANT_ROUTE, "analyst", "Assistant"], [ARTIFACTS_ROUTE, "analyst", "Artifacts"], [INTELLIGENCE_ROUTE, "intelligence", "Brain"], ["automation", "automation", "Automation"], ]; for (const [r, key, label] of BOARDED) { if (route === r && !entries.some((e) => e.key === key) && !utility.some((e) => e.key === key)) return label; } return ""; } function Lazily({ children, surface, variant = "destination" }: { children: ReactNode; surface: string; variant?: "destination" | "overlay" }) { return ( ) : (
{Array.from({ length: 6 }, (_, row) => ( ))}
) }>{children}
); } interface CreatedTemplateApplication { id: string; name: string; type: string; templateKind: string; deepLink?: string; sourceDatabase?: string; openTarget?: { database?: string }; } type WizardLoad = | { phase: "idle" } | { phase: "loading" } | { phase: "ready"; value: T } | { phase: "error"; message: string }; function ApplicationWizard({ initialTemplate = "", panelRef, onClose, onBusyChange, onCreated, }: { initialTemplate?: string; panelRef: RefObject; onClose: () => void; onBusyChange: (busy: boolean) => void; onCreated: (application: CreatedTemplateApplication) => void; }) { const [step, setStep] = useState(0); const [templates, setTemplates] = useState>({ phase: "loading" }); const [templateReadAttempt, setTemplateReadAttempt] = useState(0); const [templateKind, setTemplateKind] = useState(initialTemplate); const [name, setName] = useState(""); const [shareEntries, setShareEntries] = useState([]); const [sharePeople, setSharePeople] = useState([]); const [shareQuery, setShareQuery] = useState(""); const [sharePickRole, setSharePickRole] = useState("view"); const [shareLoadPhase, setShareLoadPhase] = useState<"idle" | "loading" | "ready">("idle"); const [busy, setBusy] = useState(false); const requestScope = useRef(null); const actionGeneration = useRef(0); const template = templates.phase === "ready" ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null : null; // R33: a template binds its own connector source, so the wizard never asks for a database. const templateSource = template?.sourceDatabase ?? ""; const templateSourceLabel = (template as (ApplicationTemplate & { sourceLabel?: string }) | null) ?.sourceLabel ?? ""; useLayoutEffect(() => { const scope = new AbortController(); requestScope.current = scope; const invalidate = () => scope.abort(); window.addEventListener(UNAUTHORIZED_EVENT, invalidate); window.addEventListener(SIGNED_OUT_EVENT, invalidate); return () => { scope.abort(); window.removeEventListener(UNAUTHORIZED_EVENT, invalidate); window.removeEventListener(SIGNED_OUT_EVENT, invalidate); }; }, []); useLayoutEffect(() => { actionGeneration.current += 1; setBusy(false); }, [initialTemplate, templateKind, templateReadAttempt]); useEffect(() => { const controller = new AbortController(); const request = requestScope.current?.signal; setTemplates({ phase: "loading" }); void fetch(`${API_V1}/nav/application-templates`, { credentials: CREDENTIALS, signal: controller.signal, }).then(async (response) => { const body = await response.json().catch(() => ({})); if (!response.ok) throw new Error(applicationRefusal( body, "Application templates could not be loaded.", )); // C2: a template whose apps//AppView.tsx this build lacks is not offered. const offered = parseApplicationTemplates(body).filter((candidate) => { const view = (candidate as ApplicationTemplate & { view?: unknown }).view; return typeof view !== "string" || APP_VIEW_FILES.has(`../apps/${view}/AppView.tsx`); }); if (!offered.length) throw new Error("No Application templates are available."); if (!controller.signal.aborted && request && !request.aborted) { setTemplates({ phase: "ready", value: offered }); setName(offered.find((candidate: ApplicationTemplate) => candidate.kind === initialTemplate)?.label ?? ""); if (offered.some((candidate: ApplicationTemplate) => candidate.kind === initialTemplate)) setStep(1); } }).catch((reason: unknown) => { if (!controller.signal.aborted && request && !request.aborted) setTemplates({ phase: "error", message: reason instanceof Error ? reason.message : "Application templates could not be loaded.", }); }); return () => controller.abort(); }, [initialTemplate, templateReadAttempt]); useEffect(() => { onBusyChange(busy); return () => onBusyChange(false); }, [busy, onBusyChange]); useEffect(() => { const controller = new AbortController(); const request = requestScope.current?.signal; setShareEntries([]); setSharePeople([]); setShareQuery(""); setSharePickRole("view"); if (!templateSource) { setShareLoadPhase("idle"); return () => controller.abort(); } setShareLoadPhase("loading"); void fetch(`${API_V1}/share/database/${encodeURIComponent(templateSource)}`, { credentials: CREDENTIALS, signal: controller.signal, }).then(async (response) => { const body = await response.json().catch(() => ({})); if (!controller.signal.aborted && request && !request.aborted) { setSharePeople(response.ok ? parseShare(body).people : []); setShareLoadPhase("ready"); } }).catch(() => { if (!controller.signal.aborted && request && !request.aborted) { setSharePeople([]); setShareLoadPhase("ready"); } }); return () => controller.abort(); }, [templateSource]); useApplicationWizardOverlay(panelRef, onClose); const shareOptions = addablePeople(sharePeople, shareEntries); const shareRecipient = resolveShareRecipient(sharePeople, shareEntries, shareQuery); const canAddEveryone = !shareEntries.some((entry) => entry.user === EVERYONE); const shareNameOf = (user: string) => user === EVERYONE ? EVERYONE_LABEL : sharePeople.find((person) => person.user === user)?.name ?? user; const canContinue = step === 0 ? !!template : step === 1 ? true : !!name.trim(); const chooseTemplate = (candidate: ApplicationTemplate) => { setTemplateKind(candidate.kind); setName(candidate.label); }; const createApplication = async () => { if (!template || !canContinue || busy) return; const request = requestScope.current?.signal; if (!request || request.aborted) return; const generation = actionGeneration.current; const current = () => !request.aborted && generation === actionGeneration.current; setBusy(true); try { const response = await fetch(`${API_V1}/nav/applications`, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: name.trim(), templateKind: template.kind, type: template.applicationType, // routes_nav.py checks the caller may open this source; the registry binds C1 itself. navPlacement: template.defaultPlacement, }), }); const body = await response.json().catch(() => ({})); if (!current()) return; if (!response.ok || !body?.application?.id) { throw new Error(applicationRefusal(body)); } // An existing template App answers the add: its share belongs to its owner, never this wizard. if (shareEntries.length > 0 && !body.existing) { try { // ⛔⛔ FIXED AT THE WAVE-59 COMBINE: this PATCHed `/nav/applications/{id}`, and NO // SUCH ROUTE EXISTS -- `routes_nav.py` mounts only `POST /nav/applications`. Every // create therefore fell into the catch below and reported "sharing did not save", // so W59-T26's done-when ("creating the app persists those grants") could not hold. // The reviewed door is `PATCH /applications/{id}` in `routes_assets.py`, which // passes the body to `application_registry.mutate` -- and that is the writer that // already understands `{share: {mode, users}}`, the exact shape sent below. // ⚠ Only api_api's D-48 leg could see this: it is the one check that matches every // decidable client fetch path against a route the app actually MOUNTED, it belongs // to lane F, and lane E owned neither it nor `routes_nav.py`. const shareResponse = await fetch(`${API_V1}/applications/${encodeURIComponent(body.application.id)}`, { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ share: shareEntries.some((entry) => entry.user === EVERYONE) ? { mode: "tenant", users: [] } : { mode: "users", users: shareEntries.map((entry) => entry.user) }, }), }); await shareResponse.json().catch(() => ({})); if (!current()) return; if (!shareResponse.ok) throw new Error("Sharing did not save."); } catch { if (!current()) return; const sharingError = "The app was created, but sharing did not save. You can share it from the App module."; // Creation closes the wizard, so the shell must also carry the partial result. showToast(sharingError, "error"); } } if (!current()) return; onCreated(body.application as CreatedTemplateApplication); } catch (reason: unknown) { if (!current()) return; showToast(reason instanceof Error ? reason.message : "The Application was not saved.", "error"); } finally { if (current()) setBusy(false); } }; const headings = ["Choose a template", "Choose who can open it", "Review and create"]; return (

New Application

{headings[step]}

    {["Template", "Share", "Review"].map((label, index) => (
  1. {index + 1}{label}
  2. ))}
{step === 0 ? ( templates.phase === "loading" ? (
) : templates.phase === "error" ? (
{templates.message}{" "}
) : templates.phase === "ready" ? (
{templates.value.map((candidate) => ( ))}
) : null ) : null} {step === 1 ? ( shareLoadPhase === "loading" ? (

Loading people...

) : sharePeople.length === 0 ? (

Only you can open this app for now. You can share it from the App module later.

) : ( <>
{shareEntries.length === 0 ? (
Not shared with anyone yet.
) : null} {shareEntries.map((entry) => (
{shareNameOf(entry.user)}
))}
setShareQuery(event.target.value)} /> {canAddEveryone ?

Everyone you add can open this app. Only you can change it.

) ) : null} {step === 2 && template ? (
Template
{template.label}
{templateSourceLabel ?
Reads
{templateSourceLabel}
: null}
Shared with
{shareEntries.length ? shareEntries.map((entry) => shareNameOf(entry.user)).join(", ") : "Only you"}

The app opens on your {templateSourceLabel || "data"} as soon as you create it.

) : null}
{step > 0 ? ( ) : null} {step < 2 ? ( ) : ( )}
); } import { createAlert, fetchInbox, markRead as markInboxRead } from "../alerts/alertsApi"; import { ALERT_CREATE_EVENT, parseAlertCreate, } from "../alerts/alertsModel"; import { retryEmit } from "./targetRoute"; import { routeForTarget } from "./targetRoute"; import { emptyBellInbox } from "../alerts/alertsModel"; import type { BellInbox, BellNotice } from "../alerts/alertsModel"; import AlertsPane, { bellHref } from "../alerts/AlertsPane"; import type { AlertModule } from "../alerts/AlertsPane"; import ShareDialog from "./ShareDialog"; import { EVERYONE, EVERYONE_LABEL, SHARE_OPEN_EVENT, SHARE_ROLES, addablePeople, parseShare, parseShareRequest, resolveShareRecipient, withEntry, withoutEntry } from "./shareModel"; import type { ShareEntry, SharePerson, ShareRequest, ShareRole } from "./shareModel"; // WAVE 19 R8 — the chosen database mark. Read-only across the session fence. import { isAdmin, logout, me } from "./session"; import type { SessionUser } from "./session"; /** Navigation stays on the origin serving this shell. */ const APP_BASE = ""; /** X5's hash route. Also the route an unauthenticated shell is pinned to. */ const LOGIN_ROUTE = "login"; function applicationRefusal(body: unknown, fallback = "The Application was not saved."): string { const payload = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown }; message?: unknown } | string; } | null; const detail = typeof payload?.detail === "object" ? payload.detail : null; for (const message of [payload?.error?.message, detail?.error?.message, detail?.message, payload?.detail]) { if (typeof message === "string" && message.trim()) return message.trim(); } return fallback; } /** A sign-in return is an internal hash, never a URL or a permission grant. */ function safeSignInHash(hash: string): string | null { if (!hash.startsWith("#/")) return null; try { const decoded = decodeURIComponent(hash.slice(2)); if (/[\\\x00-\x1f\x7f#]/.test(decoded)) return null; const key = decoded.split("?", 1)[0]; if (!/^[a-z][a-z0-9_-]*(?:\/[a-z0-9_-]+)*$/i.test(key) || canonicalRoute(key) === LOGIN_ROUTE) return null; return hash; } catch { return null; } } /** HOTFIX 2026-09-24: the same-origin OAuth approval a sign-in interrupted, resumed once. */ function resumeOAuthApproval(): boolean { let saved: string | null = null; try { saved = window.sessionStorage.getItem("aios.oauthReturn"); window.sessionStorage.removeItem("aios.oauthReturn"); } catch { return false; } if (!saved) return false; try { const url = new URL(saved, window.location.origin); if (url.origin !== window.location.origin || url.pathname !== "/api/v1/external/oauth/authorize") return false; window.location.assign(url.href); return true; } catch { return false; } } /** A stable identity for "no nav yet" — see its use below. */ const NO_ENTRIES: NavEntry[] = []; /* ⛔⛔ W40-T22 (owner instruction 5, 2026-08-23) — `const GRID_CHAT_OPEN_EVENT` STOOD HERE, WITH A long argument for the shell→grid "open the chat" channel, AND IT IS DELETED. The owner: *"remove [the 'Ask about this data' icon] from the MAIN navigation entirely so it lives only in the secondary navigation"*. The twin constant existed for exactly ONE raiser — the minimised rail's launcher, deleted in the same ticket — so the argument it carried (why the literal is typed twice rather than imported) is an argument for a control that no longer exists, and leaving it standing is how the control comes back. ⚠ THE GRID SIDE IS UNTOUCHED AND THAT IS DELIBERATE: `CustomerGrid.tsx` still exports the same constant and still listens on it, and `ViewSidebar.tsx`'s `cg-chat-toggle` opens the panel directly through `onToggleChat` rather than through the event. The listener is now dormant, not broken; removing it is a separate decision and `CustomerGrid.tsx` was outside this ticket. ⚠ `verify_wiring.py`'s two W38-T06 rows, which asserted this constant and its click, are deleted with it and carry their own tombstone there. */ /* ⛔⛔ W41-T32 (owner instruction 29, ruling R2) — `DBFLY_MAX_H`, `flyoutAt` AND `flyoutFrom` STOOD HERE AND ARE DELETED WITH THE PANEL THEY POSITIONED. Owner: *"when a user click on a Database (let's rename it to Data), it doesn't pop up a [flyout] of the database, instead it should show the list of databases in the second navigation"*. R2 makes the rail a PATH STACK: the database list is a rail LEVEL now, a direct child of `.shell-nav`, so it inherits the rail's own scroll and needs no anchor, no clamp and no portal. Three exported symbols with zero call sites is [[artifact-with-no-importer]]; they go rather than stand as geometry for a control nobody can open. Checked before deleting: `grep flyoutAt\|flyoutFrom` over `web/src/**` returns this file only — no importer anywhere, and no `_test/` leg. ⚠ WAVE 23's C10 ARGUMENT WAS RIGHT FOR ITS OWN DESIGN and is worth keeping in view: a panel that escapes a scrolling, clipping, 44px-collapsible rail cannot be a descendant of it. This ticket does not answer that objection, it removes it — a LEVEL replaces the rail's contents instead of floating beside them, so there is nothing to escape from. The collapsed rail is handled at the click instead (the Data row expands the rail before it drills — see its own note). ⛔ AND THREE `verify_home.py` LEGS ASSERT WHAT THIS DELETES — see the tombstone at the flyout's old site further down for the exact line numbers. They are RETARGET work, not this lane's: `aios-web/api/verify_home.py` is a gate, and a gate is off this lane's fence. */ /** * WAVE 23 C9 (wiring W23-W2) — the PUBLIC form route: `#/form/`. * * ⛔ THE TOKEN IS WHITELISTED, NOT SLICED. `secrets.token_urlsafe` mints `[A-Za-z0-9_-]`, so * anything else in that position is not a token this product issued — and passing it through * would let a crafted hash decide what `FormPublic` puts in a URL. Refusing here means the frame * falls through to its normal routing (and the visitor meets the login page), which is the * correct answer for a link that is not one of ours. * * `null` for every other route, so the branch that reads it is a single truthiness test. */ export function formTokenOf(route: string): string | null { const m = /^form\/([A-Za-z0-9_-]{8,128})$/.exec(route); return m ? m[1] : null; } /** * ⭐⭐ WAVE 33 item 8b (ruling R5, W33-T26) — the PUBLISHED VIEW route: `#/v/`. * * The same construction as `formTokenOf` immediately above, and the same reason: the token is * WHITELISTED against `secrets.token_urlsafe`'s alphabet, never sliced out of the hash. Anything * else in that position is not a token this product minted, and passing it through would let a * crafted hash decide what `PublishedView` puts in a URL. Refusing here drops the frame back into * normal routing, where the visitor meets the login page — the right answer for a link that is * not one of ours. * * ⚠ `v` RATHER THAN `view`, and it is not brevity for its own sake: `#/view/...` would sit one * typo away from the app's own routes, while `v` is a namespace nothing else claims. R5 names * this exact shape. */ export function publishTokenOf(route: string): string | null { const m = /^v\/([A-Za-z0-9_-]{8,128})$/.exec(route); return m ? m[1] : null; } /** C3 public links carry the customer name and the minted secret. */ export function customerCardSlugOf(route: string): string | null { const match = /^c\/([a-z0-9-]{1,80}-[A-Za-z0-9_-]{32,128})$/.exec(route); return match && match[0] === route ? match[1] : null; } /** Admit only invitation tokens minted by the server. */ export function joinTokenOf(route: string): string | null { const m = /^join\/([A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43})$/.exec(route); return m && m[0] === route && m[1].length <= 8192 ? m[1] : null; } type Session = | { phase: "checking" } | { phase: "anon" } | { phase: "authed"; user: SessionUser }; type Nav = | { phase: "idle" } | { phase: "loading" } | { phase: "ready"; entries: NavEntry[]; utility: NavPage[]; /** WAVE 23 C10 — the Home landing's recently-opened list, per user, off the nav payload. */ recents: Recent[]; empty?: string; /** ⭐ W31-T11 — registry keys this workspace's catalogue leaves out. Deliberate. */ omitted?: string[]; /** ⛔ W31-T11 — parts of the payload the SERVER could not read. Not deliberate. */ degraded?: string[]; } | { phase: "error"; malformed?: boolean }; type FinanceNav = | { phase: "idle" | "loading" } | { phase: "error"; timedOut: boolean } | { phase: "ready"; applications: ApplicationTile[] }; const NO_UTILITY: NavPage[] = []; /** Stable identity, like `NO_ENTRIES` — a fresh `[]` per render would re-run Home's memo. */ const NO_RECENTS: Recent[] = []; /** * ⭐⭐ W33-T22 (owner item 1) — THE TWO ROWS THE PAYLOAD DECIDES, FOUND IN ONE PLACE. * * ⚠ Both predicates had exactly one call site, in the render body, and now have two — the render * and the memory effect below. Written out here so the two cannot answer differently: "is * Automation on this rail?" must not be `kind === "native"` in one place and `truthy` in the * other, or the remembered rail reserves a slot the render never fills [[one-question-two-normalizers]]. */ const findAnalyst = (utility: NavPage[]) => utility.find((p) => p.key === "analyst"); const findAutomation = (entries: NavEntry[]) => entries.find((e) => e.key === "automation" && e.kind === "native"); /** * ⭐⭐ W33-T22 — WHAT THIS ACCOUNT'S RAIL LOOKED LIKE LAST TIME, so first paint need not guess. * * ⛔ THE PROBLEM A PLACEHOLDER ALONE DOES NOT SOLVE, and it was found by a reviewer reading the * fix rather than by any gate. Holding a slot for a conditional row fixes the common case — the * row lands and fills the box it was already occupying — but for an account that does NOT have * the surface, the slot is reserved at first paint and then COLLAPSES when `/nav` says "silent". * That is a flash-then-shove, i.e. arguably worse for that user than the bug we set out to fix, * and `silent` must keep collapsing: reserving permanent space for a surface the server did not * grant would be the hard-coded row this frame refuses to have (see the file header). * * ⭐ SO THE FIRST PAINT REPRODUCES THE LAST ONE. On every `ready` payload we record which of the * two conditional rows this account actually had; on the next load we reserve a slot only for the * rows it had. A returning user therefore gets their FINAL rail geometry in the first paint, * whichever way it goes, and `/nav` only ever confirms it. * * ⚠ KEYED BY USERNAME, NOT BY BROWSER. `aios-nav-collapsed` above is a per-BROWSER preference and * that is right for it; this is a per-ACCOUNT fact about permissions, and on a shared machine an * un-keyed version would paint one person's grants for another. `who` is known at first paint * because the shell is released on `/me`, which is the same fact that makes this bug possible. * * ⛔ UNKNOWN IS NOT FALSE. A first-ever load has no memory, and the honest answer there is to * RESERVE the slot (`pending`), not to assume absence — an absent row that then arrives is the * original defect. Only a remembered, explicit `false` suppresses the placeholder. Same on a * blocked/parse-failed storage: fall back to reserving. */ // W33-T75 supersedes the T22 account-memory approach above. The whole rail owns loading, and a // settled known-absent module collapses completely; only an incomplete response keeps an honest // unavailable row. The absent marker below has no label, route, focus target, or layout. /** * ⭐⭐ W33-T75 (owner item 1, `reference/ERROR 6.png`) — THE RAIL PAINTS ONCE. * * ⛔ THE ACCEPTANCE TEST IS NOT "THE SPINNER IS GONE", IT IS "NO ROW IS EVER IN A DIFFERENT * STATE FROM ITS SIBLINGS." The owner has reported this four times. Every previous answer kept * the same shape — five finished rows plus one or two rows wearing a *distinguishable* loading * state — and shrank the difference: `/nav` went 11.0 s → 26 ms (still two paints, because * `:911` makes `entries` `NO_ENTRIES` until `nav.phase === "ready"`, so first paint happens * while "does this workspace have Automation / an Analyst?" is unknown at ANY speed); then W31-T11 * gave Automation a spinner slot; then W33-T22 gave the Assistant one too. `ERROR 6.png` is the * result: Home / Query / Inbox / Database / Connectors drawn in ink, **AI assistant and Automation * drawn as spinners**, and a sixth spinner below Connectors. Two states in one list is exactly * what "the navigation loads separately" describes, and a placeholder that ANNOUNCES itself as * pending is a second state however tall it is. * * ⛔ SO THE FIX IS AT THE OTHER END: while `/nav` is in flight the rail draws THIS and no rows at * all. One skeleton, seven identical bars, nothing claiming to be a destination — then the real * rail arrives in a single paint. There is no frame in which one row is further along than * another, which is the only form of the sentence that cannot come back a fifth time. * * ⚠ WHAT IT COSTS, STATED RATHER THAN DISCOVERED: Home / Query / Inbox / Database / Connectors * are not clickable for the length of the `/nav` round trip, where before they were. That is a * real trade and it is the owner's own priority — measured, `/nav` is **0.77 s cold on the * deployed build and 26 ms warm** (wave 33 close record), so the window is short; and the four * waves of reports are about the rail's shape, never about waiting for it. `phase: "error"` and * `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there * the answer has arrived and is bad news, which is a fact worth showing rather than a wait. * * The sixteen-row skeleton is a deliberate ceiling over the settled rail of nine or ten rows. * Finance applications now live as cards inside App and contribute no rail rows. * ⛔ KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than * the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove * W33-T22 was written about, arriving by a different door. The `.shell-nav-sep` hairline is * deliberately NOT counted: it is hidden by the same `is-rail-loading` rule as the rows. */ const RAIL_SKELETON_ROWS = 16; function RailSkeleton() { return (
{Array.from({ length: RAIL_SKELETON_ROWS }, (_, i) => ( ))}
); } function useHashRoute(): { route: string; hash: string } { // ⭐ W32-T04 (C3): a RETIRED key is translated here, before anything reads it — so the whole // shell (`resolveRoute`, `active`, every `route === X` below) sees one vocabulary and no reader // has to know a rename happened. `canonicalRoute` is identity for every live key. // // ⛔⛔ W34-T15 — `routeKeyOf` REPLACES `.replace(/^#\/?/, "")`, AND THAT IS THE WHOLE TICKET. // Lane D found it before it could ship (post D-1): the old expression took the WHOLE remainder // of the hash as the key, so `#/assistant?mode=query` resolved to the key // `assistant?mode=query`, matched no route, and fell through to Home. The redirect would have // put the right URL in the address bar and the wrong screen under it, and a gate asserting the // redirect's target string would have been green over it. const read = () => { if (!window.location.hash && /^\/(?:finance\/|(?:data|table)(?:\/|$))/.test(window.location.pathname)) { window.history.replaceState(window.history.state, "", `/#${window.location.pathname}${window.location.search}`); } let hash = rewrittenHash(window.location.hash) ?? window.location.hash; // Retired bookmarks and Slack callbacks keep their query and open Contact's existing door. if (canonicalRoute(routeKeyOf(hash)) === AI_API_ROUTE) { const params = new URLSearchParams(hash.split("?", 2)[1] ?? ""); params.set("section", "contact"); hash = `#/${CONNECTORS_ROUTE}?${params.toString()}`; } if (hash !== window.location.hash) window.history.replaceState(window.history.state, "", hash); return { route: canonicalRoute(routeKeyOf(hash)), hash }; }; // ⭐⭐ W34-T15 (R14 / C2) — `#/query` BECOMES `#/assistant?mode=query`, IN THE ADDRESS BAR. // // ⚠ A REWRITE, NOT A RESOLVE, and `LEGACY_ROUTES` alone would not do: the merged surface picks // which list to show from `?mode=` on the hash, so a translation that never touched the URL // would land a Query bookmark on the CHAT list. // // ⛔⛔ AND IT IS IN THE INITIALISER RATHER THAN AN EFFECT, WHICH IS NOT A STYLE CHOICE. // `AssistantPage` resolves its mode ONCE, in its own `useState` initialiser, by reading // `window.location.hash` (`assistant/AssistantPage.tsx::initialMode` — the hash wins, else the // stored preference). Children initialise AFTER their parent renders and BEFORE any effect // runs. So a rewrite in a `useEffect` here would land after the assistant had already read the // OLD hash, found no `?mode=`, fallen back to the stored preference and opened the Chat list — // right URL, wrong screen, and nothing anywhere to say so. Rewriting during this initialiser // updates `window.location.hash` synchronously, so the child reads the new one. // // ⚠ Safe to run twice (React StrictMode does): `rewrittenHash` answers null once the key is // `assistant`, so the second call is a no-op. `replace` rather than assignment, so a bookmark // redirect does not leave a back-button trap on the hash it came from. const [location, setLocation] = useState(read); useEffect(() => { // The SAME rewrite for a hash typed into the bar mid-session, where there is no child // initialiser to race: by then the assistant is mounted and reads `?mode=` on its own. const onChange = () => { // Data addressing lives in the query string, so two database hashes intentionally share // the canonical route `data`. Keep the whole hash in state to make every location a render. setLocation(read()); }; window.addEventListener("hashchange", onChange); return () => window.removeEventListener("hashchange", onChange); }, []); return location; } /** A surface that still lives in the current application. Honest copy, one * action — never a mock of the page it is not. */ function StranglerPage({ entry }: { entry: NavEntry }) { return (

{entry.label}

This surface runs in the current application.

Open {entry.label}
); } // --- the three nav glyphs (SVG, never emoji — the platform's own rule) ------ /** The database cylinder every source-backed row carries, mirroring the host * nav's Material `database` glyph. */ /* ⛔ `SearchIcon` LIVED HERE AND IS DELETED WITH THE QUERY RAIL ROW (wave 34, R14). It was the magnifier the owner asked for on 2026-08-14 (*"Change the icon for Query, it should just be a magnifying glass icon"*) and the Query row was its ONLY call site — `tsc` said so (TS6133) the moment that row went, which is the unused-locals check doing the remembering, exactly as `PlusMark`'s note one screen down predicted it would. ⚠ A COMMENT IN THIS FILE CLAIMED OTHERWISE FOR ABOUT A MINUTE. The first draft of the Query deletion asserted that "the flyout's own filter box draws it" and kept the function on that basis. It does not, and `tsc` refuted it immediately. Left here because the useful half is the habit, not the slip: a claim about who calls a symbol is checkable in one command, so check it rather than reason about it. The magnifier is not lost — `#/assistant`'s Query mode is where that vocabulary lives now. */ /** S72-T05 (R111): the props every sidebar row glyph shares. `is-glyph` paints fill, not stroke. */ const NAV_GLYPH = { className: "shell-nav-icon is-glyph", size: 16, "aria-hidden": true } as const; /* ⭐ `DbIcon` AND `gridScopeFor` LIVE IN `shell/dbFrame.tsx` (moved there 2026-08-14). They were private to this file, and the owner's Query instruction — *"the query module should exactly BE looking like the database module, COMPLETELY"* — made them a SECOND surface's too. `gridScopeFor` is not a move but a fix: the registry key and the grid scope are different spellings, and the map used to live inline in the native branch below where nothing else could reach it. ⛔ W53-T35 — THIS FILE NO LONGER DRAWS `DbIcon`. Owner instruction 26 standardised the database mark on the Home page's outline cylinder, so the Data rail row renders `shell/icons.tsx::DatabaseIcon` and only `gridScopeFor` is still imported from `dbFrame.tsx`. `DbIcon` stays exported there because `query/queryParts.tsx` still mounts it; if that surface is standardised too, it points at `icons.tsx` and `dbFrame.tsx`'s copy goes. ⛔ `DbHead` MOVED WITH THEM AND IS NOW DELETED (W36-T51, owner item 7 — *"Remove the header for database completely"*). Its tombstone, and the list of what must NOT be swept away with it, is in `dbFrame.tsx` where it lived. */ /** WAVE 19 R12 — the gear beside the account menu's one Settings row. Drawn in * the same 16x16 stroke vocabulary as the rest of this file (SVG, never an * emoji — the platform's own rule), so it sits beside `DatabaseIcon` and `SparkIcon` * as one family rather than as an icon borrowed from somewhere else. */ function GearIcon() { return ( ); } /* ⭐⭐ WAVE 36 · T50 (owner item 5) — THE OTHER FOUR ACCOUNT-MENU MARKS, so the menu is one column of icons rather than one gear and a stack of bare text. W35-T06 shipped Feedback, Usage and Subscription as rows with no glyph beside `GearIcon`, which left their labels starting 24px further left than Settings' — the raggedness is what the owner is looking at when item 5 says these rows "need their icon". ⚠ THEY ARE DEFINED HERE, BESIDE THE GEAR, AND NOT IN `ui/icons.tsx` — checked before choosing. That module is the shared presentation layer, its glyphs are `viewBox="0 0 24 24"` and it carries Download/Check/Alert/Bell/Star only; the account menu's vocabulary is the 16x16 box plus the `.shell-menu-icon` class (`fill:none`, `stroke: currentColor`, 1.2, muted). Adding four 16px marks to a 24px module would be the drift `ui/icons.tsx`'s own header warns about, from the other direction. Same argument `GearIcon`'s note makes: one family, one file. ⛔ NO EMOJIS (owner constant, DESIGN.md) — vector paths, `currentColor`, no colour written here. */ /** Feedback: a speech bubble. The row opens a page that asks the reader to SAY something, and a * bubble is the one mark that means "your words"; an envelope would collide with Inbox's. */ function BubbleIcon() { return ( ); } /** Usage: a PIE — a circle with one wedge marked off. * * ⚠ NOT a coin, and the PAGE is what decided it: `UsagePage` renders a METER of consumption (its * own comment argues about what a failed read must not look like — *"a meter reading zero is the * most reassuring possible lie"*). A coin would promise a balance the surface does not show. A pie * says "this much of it is gone", which is what the page says. * * ⭐ AND THE SHAPE WAS CHOSEN BY LOOKING, NOT BY REASONING, because the first one failed the eye. * Six candidates were rendered at 16px in this exact stroke vocabulary and read at true size * (`scratchpad/shots/glyph-candidates.png`): * · an ARC-AND-NEEDLE gauge — what shipped first, and it reads as a hill or an eyebrow: the * needle touches the arc and the two merge into one stroke at 16px; * · a COIN WITH A RIM (two concentric circles) — reads as a bullseye, and it is the loudest * mark in the menu; * · a COIN STACK — that WAS this rail's database mark (`dbFrame.tsx::DbIcon`), and the * argument stands under W53-T35's replacement: the shape is still spent on "database" * (now as `icons.tsx::DatabaseIcon`'s cylinder here, and as `DbIcon` on Query), and one * mark may mean one thing (DESIGN.md §4); * · a WALLET — reads as a battery; * · a gauge WITH A HUB — better than the first, still optically thin beside the gear. * The pie won on legibility and on weight: a closed circle sits at the same optical weight as * `GearIcon` above it, and nothing else in the client draws one. */ function PieIcon() { return ( ); } /** Subscription: a card. The row is about what the workspace pays with, and a card with its stripe * is legible at 16px where anything more literal (a receipt, a calendar of renewals) is not. */ function CardIcon() { return ( ); } /** Sign out: a door with the arrow leaving it. * ⚠ IT NEEDED A CSS RULE AS WELL AS A PATH, and that is the trap in adding a mark to this row: * `.shell-menu-item.is-signout` paints the row `--lp-red-deep` while `.shell-menu-icon` sets its * own `color: var(--lp-muted)`, so the glyph would have rendered grey beside red text and read as * a half-broken row. `index.css` gives the signout icon `color: inherit` at rest and on hover. */ function ExitIcon() { return ( ); } /* ⛔ `AutoIcon` LIVED HERE AND IS DELETED WITH THE AGENTS HEADER (W35-T32, owner item 2). It was the two-node flow glyph the head drew beside the word "Agents"; with the head gone it had no call site, and `tsc`'s unused-locals check named it in the same run — which is the argument for letting the compiler do the remembering rather than a sweep. ⚠ THAT SENTENCE IS STALE AND W51-T30 CORRECTS IT RATHER THAN LEAVING IT TO ROT. It read *"NOT the same mark as the rail's `RobotIcon`, which SURVIVES and is what owner item 5 asked for. Two glyphs, two jobs; only the header's is retired."* The rail's robot is gone too now (R15, wave 51) and the rail drew `FlowIcon` — a two-node flow glyph, which was the SAME FAMILY of mark this header one was. ⚠ THAT PARAGRAPH IS STALE IN ITS TURN AND W53-T34 CORRECTS IT RATHER THAN LEAVING IT TO ROT: `FlowIcon` IS GONE TOO (owner instruction 4), and there is no flow mark anywhere in the shell any more. The rail now draws `shell/icons.tsx::AgentIcon`, a square with two eyes. ⛔ THAT IS NOT A LICENCE TO BRING THIS ONE BACK — it is the opposite. `AutoIcon` belonged to a HEADER that no longer exists, at header geometry, and its family of mark has now been rejected by the owner on the rail. Resurrecting it would re-open a settled question with a glyph nobody asked for. */ /* ⭐ `BellIcon` LIVED HERE AND IS DELETED (wave 34, R15) — AND THAT DELETION CLOSES `D-207`. The Inbox row took `MailIcon`, leaving this local copy with no call site. D-207 records that `ui/icons.tsx` — the file whose own header warns that "a second hand-copy in the shell is the drift this module exists to prevent" — already carried a second `BellIcon`, and the shell had one anyway. Deleting the LOCAL copy and keeping the SHARED one is the right half to keep: the shared module is the one another surface can import. ⚠ So `ui/icons.tsx::BellIcon` is now the only bell in the client. `W34-T17` verifies that, rather than this comment asserting it. */ /* ⛔ S72-T05 (R111): `HomeIcon`, `PlugIcon`, `SheetIcon`, `AppIcon`, `TemplatesIcon`, `ArtifactsIcon`, `SparkIcon` and `RailToggleIcon` LIVED HERE AND ARE DELETED. Sidebar rows draw from `@phosphor-icons/react` (imports at the top). `verify_icons.py` fails on any of these names coming back as a function, and on `RobotIcon`, the wave-34 hand-drawn robot R15 deleted. */ /* ⛔ `PlusMark` LIVED HERE AND IS DELETED WITH THE THREE BUTTONS THAT DREW IT (wave 24 item 15a, ruling R9). It was the flyout footer's plus, used by nothing else — `CreateNewRow` brings its own `PlusIcon`, which is private to `NavExtras`. `tsc` named it the moment the last call site went (TS6133), which is the argument for a REQUIRED prop and an unused-locals check doing the remembering: the CSS twins `.shell-dbfly-make` and `.shell-dbfly-plus` went to zero call sites in the same edit and no compiler says a word about those — they are swept by hand below, in this session's own index.css region, rather than left as the D-42 residue class. */ /** WAVE 23 R7 — the disclosure caret on the "Database" row: this opens a panel, and the mark * says so before the click does (the same job `ExtIcon` does for a hand-off). */ /** ⭐ W41-T32 (owner instruction 29) — the path stack's `<` and `>`. * * ⛔ THE SAME PATH AS `CaretIcon` ABOVE, MIRRORED, and that is the whole design decision. The * rail already owns a chevron in a 12x12 box at this weight; importing a second one — or typing * the `‹` character, which is a font's opinion rather than the app's — would put two marks in one * rail meaning "there is more this way" (DESIGN §4: one mark, one meaning). * * ⚠ IT DOES NOT WEAR `.shell-nav-open`, which `CaretIcon` does. That class sits at `opacity: 0` * until its ROW is hovered, which is right for a disclosure hint riding a link and wrong for a * control that has to be findable before the pointer is on it. Its own class carries the same * 16px-family stroke vocabulary at full strength. */ /** * The account corner: ONE line (monogram + name + role, the host's * `_account_css` card) that opens a small menu, instead of three buttons * crushed into a 236px row — which is what the owner met as "the logout * button broke": Sign out wrapped into a 42px two-line stub beside a clipped * name. Every action keeps its full label inside the menu. */ function AccountMenu({ user, utility, onSignOut, onSettings, }: { user: SessionUser; /** Utility pages other than the Assistant and Brain rail slots. */ utility: NavPage[]; onSignOut: () => void; onSettings: (s: SettingsSection) => void; }) { const [open, setOpen] = useState(false); const wrap = useRef(null); // W51-T31 — Escape leaves through the shared stack. The local capture listener that used to // sit here closed this menu even when a dialog was open on top of it, because every overlay // arbitrated for itself and the winner was whichever listener registered last. useEscapeClose(open, () => setOpen(false), { container: () => wrap.current }); useEffect(() => { if (!open) return; const onDoc = (e: MouseEvent) => { if (wrap.current && !wrap.current.contains(e.target as Node)) setOpen(false); }; document.addEventListener("mousedown", onDoc); return () => document.removeEventListener("mousedown", onDoc); }, [open]); // ⚠ Unicode letter/number, not [a-z0-9]: the app's `_account_css` uses // Python's `str.isalnum()`, so an ASCII-only class here would give a // non-Latin name an initial in one shell and a blank circle in the other. const initial = (user.name.match(/[\p{L}\p{N}]/u)?.[0] ?? "").toUpperCase(); const extras = utility.filter((p) => p.key !== "analyst" && p.key !== "intelligence"); return (
{open ? (
{/* ⚠ WAVE 19 R12 SUPERSEDES WAVE 15 R12, IN BOTH HALVES. Wave 15 renamed this row "Settings" → "Profile" and kept a second, admin-only "Manage users" beside it. The owner has now ruled the opposite: ONE row, called **Settings**, with a gear, shown to EVERYONE, landing on Account — and admins meet "Manage users" where it always really lived, as a tab in the modal's own rail. The two rows were the problem, not either label. They opened the SAME modal at two different tabs, so the account menu was quietly acting as a second navigation for a surface that already has one; an admin had to decide which door to use before knowing which tab they wanted. Landing everyone on Account and letting the rail do the rest removes the decision. ⛔ `verify_ui.py`'s naming gate was inverted in the same change (its R12 check asserted the wave-15 wording, so it would have gone red on the correct edit). Wave-19 amendment 1 in the wave doc. */} {/* Account pages keep bookmarkable links below Settings for every workspace. */} setOpen(false)} > Feedback setOpen(false)} > Usage setOpen(false)} > Subscription {extras.length ?
: null} {extras.map((p) => ( setOpen(false)} > {/* WAVE 17 ITEM 15b (R8) — the `settings` special-case is GONE. This row used to relabel one registry key on its way to the screen, which is a client deciding what the payload meant. R8 deletes the host surface itself, so the honest client change is not to HIDE the key here — hard-coding an exclusion would outlive the thing it excludes — but to stop treating any key specially and let the payload decide. When `nav_pages` stops emitting it, the row stops existing, with nothing here to update. Every utility row now wears its registry label. */} {p.label} ))}
) : null}
); } /** * ⭐ WAVE 30 (R5) — THE OUTERMOST BOUNDARY, and the ONLY one that can cover the three * EARLY RETURNS below (`FormPublic`, the boot card, `LoginPage`) plus this component's own * body: its route resolution, its nav shaping and its derivations all run BEFORE any JSX * exists to wrap. A throw in any of them used to take the document with it, and a person * who cannot get past the login screen has no navigation left to escape with. * * ⚠ Split rather than nested inline for one reason: a boundary cannot catch a throw from * its OWN render. `ErrorBoundary` has to be the parent of the component that fails, so the * frame becomes a child and the default export becomes the wrapper. */ export default function Shell() { return ( ); } /** How the rail came to be folded, as persisted in `aios-nav-collapsed`. */ type NavFold = "0" | "1" | "auto"; /** The one key both halves of the fold read and write. */ const NAV_FOLD_KEY = "aios-nav-collapsed"; /** * ⭐⭐ WAVE 53 · T32 (ruling R1) — WHO FOLDED THE RAIL, not merely whether it is folded. * * The stored value used to be a boolean, and that is exactly why owner instruction 3 had to be * written: a rail the GRID folded on a cell click was indistinguishable from a rail the READER * folded with the minimize button, so the grid's fold followed you to Home and survived the next * app open. Three values keep them apart: * `"0"` the rail is open. * `"1"` the reader folded it themselves. A choice, and it holds everywhere, Home included. * `"auto"` the work surface folded it (`NAV_MINIMIZE_EVENT`). Still folded, still remembered, * but it is the surface's fold and it does not outlive that surface. * * ⚠ `"1"` IS READ BY THE OLD SPELLING TOO, and that is not an accident: every browser that has * opened this app before today holds a literal `"1"`, and treating it as an explicit fold is the * kinder reading of an unknowable one. Anything that is not `"0"` means folded, so a value this * function has never heard of still fails safe as folded rather than silently opening the rail. */ function readNavFold(): NavFold { try { const raw = localStorage.getItem(NAV_FOLD_KEY); if (raw === "auto") return "auto"; return raw === "1" ? "1" : "0"; } catch { // storage can be blocked; the rail then simply starts open, as it does for a new reader return "0"; } } function AuthenticatedBell({ modules, frozen, railHidden, onOpenView }: { modules: AlertModule[]; frozen: boolean; railHidden: boolean; onOpenView: (database: string, view: string) => void; }) { const [inbox, setInbox] = useState(emptyBellInbox); const [alertsOpen, setAlertsOpen] = useState(false); const [busy, setBusy] = useState(false); const [problem, setProblem] = useState(""); const request = useRef(null); const epoch = useRef(0); const marking = useRef(false); const active = useRef(true); const clear = useCallback(() => { active.current = false; epoch.current += 1; request.current?.abort(); setInbox(emptyBellInbox()); setAlertsOpen(false); setProblem(""); }, []); const load = useCallback(async () => { if (!active.current || marking.current) return; const turn = ++epoch.current; request.current?.abort(); const controller = new AbortController(); request.current = controller; setBusy(true); setProblem(""); try { const result = await fetchInbox(controller.signal); if (!result.ok) throw new Error(result.message); const next = result.value; if (!controller.signal.aborted && active.current && turn === epoch.current) setInbox(next); } catch (error) { if (!controller.signal.aborted && active.current && turn === epoch.current) { setInbox(emptyBellInbox()); setProblem(error instanceof Error ? error.message : "Alerts could not be loaded"); } } finally { if (active.current && turn === epoch.current) setBusy(false); } }, []); useEffect(() => { active.current = true; void load(); const refresh = () => { if (!document.hidden) void load(); }; const invalidate = () => { setInbox(emptyBellInbox()); setAlertsOpen(false); refresh(); }; const timer = window.setInterval(refresh, 60_000); window.addEventListener("focus", refresh); window.addEventListener(WORKSPACE_STALE_EVENT, invalidate); window.addEventListener(SIGNED_OUT_EVENT, clear); window.addEventListener(UNAUTHORIZED_EVENT, clear); return () => { active.current = false; epoch.current += 1; request.current?.abort(); window.clearInterval(timer); window.removeEventListener("focus", refresh); window.removeEventListener(WORKSPACE_STALE_EVENT, invalidate); window.removeEventListener(SIGNED_OUT_EVENT, clear); window.removeEventListener(UNAUTHORIZED_EVENT, clear); }; }, [clear, load]); const markRead = async (ids: string[]) => { const owned = ids.filter((id) => inbox.items.some((item) => item.id === id && !item.read)); if (!active.current || marking.current || frozen || !owned.length) return; marking.current = true; const turn = ++epoch.current; request.current?.abort(); const controller = new AbortController(); request.current = controller; setBusy(true); setProblem(""); try { const result = await markInboxRead(owned, controller.signal); if (!result.ok) throw new Error(result.message); const next = result.value; if (!controller.signal.aborted && active.current && turn === epoch.current) setInbox(next); } catch (error) { if (!controller.signal.aborted && active.current && turn === epoch.current) { showToast(error instanceof Error ? error.message : "Alerts could not be updated", "error"); } } finally { marking.current = false; if (active.current && turn === epoch.current) setBusy(false); } }; const open = (item: BellNotice) => { const destination = routeForTarget(item.target); const href = bellHref(item); if (!href) return; setAlertsOpen(false); if (destination?.surface === "database" && destination.viewId) { onOpenView(destination.key, destination.viewId); } else { window.location.hash = href; if (destination?.surface === "automation") signal(AUTOMATION_OPEN_EVENT, { autoId: destination.autoId, tab: destination.tab }); } }; return <> {/* Hidden with Templates and Connectors while /nav loads, so the rail paints once. */} {alertsOpen ? void markRead(ids)} onOpen={open} onClose={() => setAlertsOpen(false)} onRetry={() => void load()} /> : null} ; } function ShellFrame() { const freezeNotice = useFreezeNotice(); const [session, setSession] = useState({ phase: "checking" }); const [nav, setNav] = useState