// --------------------------------------------------------------------------- // sheet/SheetPage.tsx — the Sheet module's page (wave 49 · T01 shell, T05 grid). // // ⚠ THE VIEW RAIL IS RENDERED HERE RATHER THAN BY `customer-grid/ViewSidebar`, and that is a // measured decision, not a shortcut. `ViewSidebar` is not a portable props component: it reads // `localStorage` directly (`readRailPath`/`writeRailPath`), dispatches on the shared // `apiContract` event bus, and pulls six sibling `customer-grid` modules — mounting it needs a // `SavedView[]`, an `onViewReorder`, an `alertCounts` map and eight more required callbacks. // // ⭐⭐ W50-T17 (owner instruction 20) — THE RAIL MOVED INTO `SheetRail.tsx` AND THE LOADING STATE // STOPPED BEING A SENTENCE. Two things the owner named, in his words: the opening screen must be // the Data module's loading animation, and the rail must be the Data rail. So this page now owns // three states rather than two, and the third is the one that was missing: // // loading the rail draws `.shell-rail-skeleton*` and the main area draws `SheetLoading`, // a labelled row skeleton. NO SENTENCE. "Opening your workbook." was the // defect: a line of prose where the rest of the app shows a skeleton. // refused `loading` is over and nothing opened, so the reason is stated as a plain // sentence naming its subject (R16). // open the workbook and its grid. // // ⛔ THE THIRD STATE IS WHY `loading` IS ITS OWN FLAG AND NOT `book === null`. A null workbook // means BOTH "still opening" and "could not open", and collapsing them makes a failed open spin // forever behind a spinner that will never stop, which satisfies the loader clause while // breaking R16. `loading` is cleared on EVERY terminal path of the opening effect, including // each refusal branch. // // C3: embedded mounts own their address and storage without consulting the browser hash. // // ⭐ R12: THE REFRESH BUTTON LIVES IN THE HORIZONTAL RAIL, not on the cell bar alone. A sheet is a // SNAPSHOT (R10), so the one control that changes every number on screen is a page-level act and // is placed where a page-level act belongs. // --------------------------------------------------------------------------- import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import type { PointerEvent as ReactPointerEvent, ReactNode } from "react"; import { TOAST_EVENT } from "../apiContract"; import { viewAsActive } from "../settings/viewAs"; import "../styles/wave49/sheet.css"; import "../styles/wave50/sheet.css"; import "../styles/wave55/sheet.css"; import "../styles/wave57/sheet-tabs.css"; // ⛔⛔ W51-T09 — THE LAUNCHER'S OWN STYLESHEET, AND IT IS NOT OPTIONAL. `.cg-chat-toggle` and // `.cg-chat-dock` live in `customer-grid/chatDock.css`, which until this ticket ONLY // `CustomerGrid.tsx` imported. On a direct load of `#/sheet` that chunk is never fetched, so the // rail's new Ask button would have rendered in native UA chrome: the "1.78px outset black border // over rgb(240,240,240)" that `styles/wave46/rail-select.css` documents as the owner's "big square // outline". Nothing catches that — not `tsc`, not a text-presence gate, not the parity harness, // which measures five OTHER classes. Importing the sheet is the fix; re-declaring the class in a // lane sheet would fight the cascade the first time somebody visits Data before the Sheet. import "../customer-grid/chatDock.css"; import ChatDockSeat from "../customer-grid/ChatDockSeat"; import { readSheetAddress, sheetAddressHash, SHEET_VIEW_KIND, writeSheetAddress } from "./index"; import { ITEM_DELETED_EVENT, isMissingItem, itemDeleted } from "../starred/starredApi"; import type { DeletedItem } from "../starred/starredApi"; import type { SheetAddress } from "./index"; import { parseRef } from "./a1"; import BindingEditor from "./BindingEditor"; import PivotTab from "./PivotTab"; import DrillModal from "./DrillModal"; import type { DrillCellScope } from "./DrillModal"; import FormulaBar from "./FormulaBar"; import { OPEN_CELL_DATA_EVENT, SheetRefreshContext } from "./Ribbon"; import SheetGridBase from "./SheetGrid"; import type { BoundEvaluationRequest, SheetGridProps } from "./SheetGrid"; import SheetRail from "./SheetRail"; import SheetActivity from "./SheetActivity"; import SheetCatchUp from "./SheetCatchUp"; import RefreshHistory from "./RefreshHistory"; import WorkbookChecks from "./WorkbookChecks"; import { fetchRetryingBusy, readWorkbookChecks, writeWorkbookChecks } from "./sheetApi"; import type { RailStrata } from "./SheetRail"; import { computeCell, createdFolderIds, createWorkbook, deleteWorkbook, duplicateSheetTab, reorderSheetTab, patchTabCells, readIndex, readTab, readTabMeta, applyRefreshScope, isSettledStale, placementOnlyDelta, readWorkbook, refreshCells, refreshScope, retryRefresh, renameTabName, renameWorkbookName, writeIndex, writePlacements, writeWorkbook, sheetEditScope, withPendingSheetCells, } from "./sheetApi"; import type { RefreshScope, Result, SheetCellEdit, SheetIndex, SheetMountAddress, TabCellsSaved, WorkbookActivity } from "./sheetApi"; import SaveState, { useSaveState } from "../customer-grid/SaveState"; import { withCellLimits } from "./cellLimits"; // ⛔⛔ W51-T10 / R6 — THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to // be a hand-rolled `.sheet-drill-error` panel: no focus trap, no Escape, no backdrop, and its two // buttons wore the same quiet `.sheet-refresh` chrome, so the destructive one was indistinguishable // from Cancel. It is the same promise the workbook delete makes, so it is the same shape. import { ConfirmDialog } from "../ui/ConfirmDialog"; import { ITEM_NOT_AVAILABLE } from "../ui/itemAvailability"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import AssistantPanel from "../assistant/AssistantPanel"; import { editOutbox, fetchTopicRows, fetchWorkspace, peekWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; import type { FilterTree } from "../customer-grid/types"; import { addTab, applyStructureWorkbook, bandBoundLabel, boundCellsInBand, cellAt, drillAffordance, emptyHistory, growSheet, pushHistory, redoHistory, removeTab, removeTabRefusal, renameTab, renameTabRefusal, setColumnWidth, setFreeze, setTabView, reanchorWorkbookForMove, setTabVisibility, splitAddress, structureRefusal, tabCellCount, undoHistory, withCells, withRowGroupsTab, readFormulaSlot, } from "./sheetState"; import type { MovedBlock, SheetHistory, StructureOp } from "./sheetState"; import { bindingDisplay, emptyIndex, normalizeCellBinding, ROOT_FOLDER_ID, sheetExtent, withBindingDisplay } from "./types"; import type { BindingDisplay, Cell, IndexRepair, PivotSpec, SheetChartSpec, SheetPrintSettings, SheetRule, SheetRowGroup, SheetTab, SheetTabView, Workbook } from "./types"; import { ChartWorkbookContext } from "./ChartDialog"; import { SheetExportContext } from "./Ribbon"; // W57-T19: the page supplies the ordered options and saved-view filters used by every copy door. import { topicForScope } from "../customer-grid/types"; import { bindingOptionKey } from "./sheetState"; import type { OptionCatalogue } from "./sheetState"; import { bindingOnDrag, BINDING_ENDING_STEP, BINDING_PERIOD_STEP } from "./types"; import type { SavedViewShadow } from "./bindingRefs"; import { bindingStepValues, resolveFilterCell } from "./bindingRefs"; // Twin in HomePage.tsx; this ticket's file fence keeps the timeout local to each chunk. const FOLDER_WRITE_TIMEOUT_MS = 20000; function readSheetFolder(hash: string): string | undefined { return hash.startsWith("#/sheet?") ? new URLSearchParams(hash.slice(hash.indexOf("?") + 1)).get("folder") || undefined : undefined; } function reattachSheetFolder(folder: string | undefined): string { const hash = window.location.hash; if (!folder || folder === ROOT_FOLDER_ID || !hash.startsWith("#/sheet?") || new URLSearchParams(hash.slice(hash.indexOf("?") + 1)).has("folder")) return hash; // The address module is another fence's file; its builder drops unknown params. // Reattach after its writer, without a second hashchange or an extra Back entry. const next = hash + "&folder=" + encodeURIComponent(folder); window.history.replaceState(window.history.state, "", next); return next; } /** * ⭐⭐ W51-T08 / CONTRACT C1 — THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S. * * C1 says the ribbon lives inside `SheetGrid` and is fed from this page: the formula bar arrives * as a NODE it slots under the ribbon, and Refresh, Ctrl+S and Import arrive as handlers. Lane E * declares those members on `SheetGridProps`; this lane may not edit that file, so the call site * would be an unknown-attribute error until E lands. * * ⛔ THIS IS AN ASSIGNMENT, NOT A CAST, AND THAT IS THE WHOLE POINT. A parameter is contravariant, * so a function taking `SheetGridProps` is assignable to one taking `SheetGridProps & Seams` with * no `as` anywhere. Nothing is silenced: every OTHER prop is still checked against E's real type, * a missing `onCommit` is still an error, and a `formulaBar` of the wrong TYPE is still an error. * `as any` on the element would have thrown all of that away to buy the same three props. * * ⭐ AND IT SURVIVES THE COMBINE UNTOUCHED. Once E declares the three members, the intersection is * a no-op and the call typechecks against the REAL props; if E declares one with a DIFFERENT * signature the intersection makes that a `tsc` error at the merge rather than a silent mismatch, * which is the failure this shape is worth having for. Collapsing it back is two lines whenever * someone wants to: rename the import to `SheetGrid` and delete this block. * * ⚠ THE LOCAL IS NAMED `SheetGrid` ON PURPOSE. The JSX stays ``, so `verify_wiring`'s * W50-T17 row and every other reader keeps matching without being edited around a shim. */ type SheetGridSeams = { /** C1: rendered between the ribbon and the canvas. This page still renders it above the grid * as well, until W51-T14 deletes that interim render on the merged tree. */ formulaBar?: ReactNode; /** C1: Ctrl+S inside the grid, wired to this page's own save queue. */ onSaveNow?: () => void; /** C1: the ribbon's Import door. W51-T13 builds what it opens. */ onOpenImport?: () => void; }; const SheetGrid: (props: SheetGridProps & SheetGridSeams) => ReturnType = SheetGridBase; /** Reserve the grid with the existing Sheet row skeleton until its tab has arrived. */ function SheetLoading() { return (
); } /** * Turn the server's `repairs` list into ONE plain sentence naming what moved (R16). * * ⭐ THIS IS THE HALF A NAIVE COPY OF THE FOLDER MODEL DROPS. `core/sheets.py::save_folders` * REPAIRS a placement or a parent that names a folder which is not there, rather than refusing, * because deleting a folder creates exactly that. Silently swallowing the receipt is what makes * a folder reappear somewhere else with no explanation, so the rail says it out loud. */ function repairSentence(repairs: readonly IndexRepair[] | undefined): string { const list = repairs ?? []; if (list.length === 0) return ""; const moved = list.filter((r) => r.reason === "placement_missing_folder" || r.reason === "parent_missing" || r.reason === "placement_missing_workbook").length; const unstarred = list.filter((r) => r.reason === "starred_missing_workbook").length; if (moved > 0 && unstarred > 0) { return "Some items moved back to the top level and some stars were dropped, because the " + "folder or workbook they named is gone."; } if (moved > 0) { return moved === 1 ? "One item moved back to the top level, because the folder it was filed in is gone." : `${moved} items moved back to the top level, because the folder they were filed in ` + "is gone."; } if (unstarred > 0) { return "A star was dropped, because the workbook it named is gone."; } // ⛔ R16 REACHES THIS FAR DOWN, AND A CATCH-ALL IS WHERE IT USUALLY BREAKS. "Something was // tidied up" names no subject and is exactly the generic sentence the ruling forbids, so the // two collision reasons get their own words and their own id, and the last line names the // rows it is talking about rather than the rail in general. const collided = list.find((r) => r.reason === "duplicate_folder_id" || r.reason === "item_in_two_folders"); if (collided) { const subject = collided.folder_id || collided.item_id || ""; return subject ? `Two entries claimed the name ${subject}, so only the first one was kept.` : "Two entries claimed the same name, so only the first one was kept."; } return `${list.length === 1 ? "One row" : `${list.length} rows`} in this rail could not be ` + "read as a folder or a filing, so they were left out."; } // ═════════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T11 / RULING R4 — THE SAVE MODEL: A RANGE PER COMMIT, ONE TAB AT A TIME. // // R4, verbatim: *"the client saves a cell-range PATCH per commit with `rev`, opens one tab at a // time; recalc runs only on Refresh or a formula commit and its time is shown."* // // ⛔⛔ THE ONE THING THAT COULD HAVE DESTROYED DATA, AND IT IS THE REASON `tabLoadedRef` EXISTS. // Opening with `?tabs=meta` means the in-memory workbook holds tabs with EMPTY `cells` maps for // every tab nobody has looked at. Today's whole-workbook PUT sends `current.sheets` verbatim, so // a single fallback save after a lazy open would have written those empty maps over every unread // tab and deleted them, with every gate green and nothing thrown. So the PUT is fenced: it may // only run once every tab is in memory, and `ensureTabs` is what gets it there. // // ⛔ AND THE PUT FALLBACK IS THE LIVE PATH ON THIS BRANCH, not a theoretical branch. None of // contract C3's three routes are served yet, so on this tree the probe fails on the first save, // the status line reads "Saving the whole workbook", and everything above is what makes that // safe rather than destructive. // ═════════════════════════════════════════════════════════════════════════════════════════════ /** * How long a burst of keystrokes is allowed to gather before it is sent. * * ⚠ THE TICKET'S `how:` LINE SAYS THE DIRTY SET "DRAINS ON A DEBOUNCE" AND THERE WAS NO DEBOUNCE. * `queueSave` used to send the entire workbook synchronously on every commit, undo, redo, binding * save and structure op, serialised only by promise chaining. Ten characters typed into ten cells * were ten whole-workbook PUTs. This is the timer that was assumed to exist. * * ⭐ 600 ms IS CHOSEN AGAINST THE TYPING RHYTHM, not picked round. A commit in this grid is an * Enter or a Tab, so the gap between two commits is a person moving to the next cell and typing * it; shorter than about half a second and a steady typist still pays a request per cell, much * longer and a save feels detached from the edit that caused it. Ctrl+S bypasses it entirely. */ const SAVE_DEBOUNCE_MS = 600; /** * A workbook identity change may wait for persistence, but it may not strand the rail forever * behind an unreachable store. On expiry the identity stays put and the in-flight save keeps its * ordinary recovery path; the person can retry the switch after that path settles. */ const SAVE_FLUSH_TIMEOUT_MS = 5_000; /** A pointer drag starts only after ordinary click slop, so click and double click keep working. */ const TAB_DRAG_SLOP_PX = 4; interface TabDrag { workbookId: string; tabId: string; pointerId: number; element: HTMLButtonElement; originX: number; grabOffsetX: number; width: number; startIndex: number; targetIndex: number; moved: boolean; } /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */ const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`; type WorkbookOpening = Workbook & { openingTab?: SheetTab & { rev: number } }; async function readWorkbookOpening(id: string, tab?: string): Promise> { try { const response = await fetchRetryingBusy(`/api/v1/sheets/${encodeURIComponent(id)}?tabs=meta&opening=true` + (tab ? `&open_tab=${encodeURIComponent(tab)}` : ""), { credentials: "same-origin" }); const body = await response.json().catch(() => null) as { workbook?: Workbook; opened?: { id: string; rev: number; tab: SheetTab }; error?: { code?: string; message?: string; rev_current?: number }; } | null; if (!response.ok) return { ok: false, status: response.status, code: body?.error?.code ?? "unknown", message: body?.error?.message ?? "Something went wrong.", ...(typeof body?.error?.rev_current === "number" ? { rev_current: body.error.rev_current } : {}) }; const workbook = body?.workbook; if (!workbook || workbook.id !== id || !Array.isArray(workbook.sheets)) return { ok: false, status: 500, code: "workbook_unavailable", message: "That sheet could not be read, so it is not shown." }; const opened = body?.opened; if (opened && (opened.id !== workbook.id || opened.rev !== workbook.rev || !opened.tab?.id || !workbook.sheets.some((sheet) => sheet.id === opened.tab.id))) return { ok: false, status: 409, code: "workbook_revision_stale", message: "This workbook changed while opening. Refresh it to read one revision." }; const normalize = (sheet: SheetTab): SheetTab => ({ ...sheet, cells: Object.fromEntries(Object.entries(sheet.cells ?? {}).map(([addr, cell]) => [addr, cell?.binding ? { ...cell, binding: normalizeCellBinding(cell.binding) } : cell])) }); return { ok: true, value: { ...workbook, sheets: workbook.sheets.map(normalize), ...(opened ? { openingTab: { ...normalize(opened.tab), rev: opened.rev } } : {}) } }; } catch { return { ok: false, status: 0, code: "unreachable", message: "Cannot reach the server." }; } } // W56-T05: the last open workbook is one scalar, separate from the bounded per-workbook cell map. const LAST_WORKBOOK_KEY = "aios-sheet-last-workbook"; function readLastWorkbook(prefix = ""): string { try { return localStorage.getItem(prefix + LAST_WORKBOOK_KEY) ?? ""; } catch { return ""; } } function writeLastWorkbook(workbookId: string, prefix = ""): void { try { localStorage.setItem(prefix + LAST_WORKBOOK_KEY, workbookId); } catch { /* session only */ } } // ⭐⭐ W56-T04: LAST CELL IS ONE BOUNDED MAP, NOT ONE UNBOUNDED KEY PER WORKBOOK. // Object insertion order is the recency order: touching a workbook deletes and re-adds its row, // and the oldest row is the first one dropped when the 50-workbook cap is reached. const LAST_CELLS_KEY = "aios-sheet-last-cells"; const LAST_CELLS_LIMIT = 50; type LastCells = Record; function readLastCells(prefix = ""): LastCells { try { const raw = localStorage.getItem(prefix + LAST_CELLS_KEY); if (!raw) return {}; const parsed = JSON.parse(raw) as unknown; if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; const out: LastCells = {}; for (const [id, addr] of Object.entries(parsed).slice(-LAST_CELLS_LIMIT)) { if (id && typeof addr === "string" && addr) out[id] = addr; } return out; } catch { return {}; } } function writeLastCells(next: LastCells, prefix = ""): void { try { localStorage.setItem(prefix + LAST_CELLS_KEY, JSON.stringify(next)); } catch { /* session only */ } } function touchLastCell(current: LastCells, workbookId: string, addr: string): LastCells { const next = { ...current }; delete next[workbookId]; next[workbookId] = addr; const ids = Object.keys(next); const expired = ids.slice(0, Math.max(0, ids.length - LAST_CELLS_LIMIT)); for (const id of expired) delete next[id]; return next; } /** * Does this tab carry anything an undo could destroy? * * ⭐ THIS IS THE TEST BEHIND THE `historyRef` DECISION BELOW, and it is why the decision is not * simply "always drop the stack". */ const tabHoldsCells = (tab: SheetTab | null | undefined): boolean => Object.keys(tab?.cells ?? {}).length > 0; /** Tab reads carry the workbook revision from their envelope, never a separate tab counter. */ const tabRevOf = (tab: SheetTab, book: Workbook): number => { const own = (tab as { rev?: unknown }).rev; return typeof own === "number" ? Math.max(own, book.rev) : book.rev; }; /** * Is a tab-navigation response still the one the user is waiting for? * * `requested === undefined` is a caller that does not navigate (the save drain, a chart load): * it is never stale, because nothing about it is about which tab is on screen. */ export function tabNavVerdict(requested: number | undefined, current: number): "apply" | "discard" { if (requested === undefined) return "apply"; return requested === current ? "apply" : "discard"; } /** * Which tab the hidden-tab effect should move to, or null for "leave the page alone". * * Returns null when `tabId` names a tab this snapshot does not carry: that pair is a STALE * COMPUTATION, not a hidden tab, and redirecting on it is how a late response moved the user off * the sheet they had just clicked. */ export function hiddenTabRedirect( sheets: readonly { id: string; visibility?: string }[], tabId: string, ): string | null { const visible = (t: { visibility?: string }) => (t.visibility ?? "visible") === "visible"; const open = tabId ? sheets.find((t) => t.id === tabId) : sheets[0]; if (!open) return null; // stale pair, or an empty workbook: change nothing if (visible(open)) return null; // the open tab is fine const next = sheets.find(visible); return next && next.id !== tabId ? next.id : null; } export interface SheetPageProps { address?: SheetMountAddress; embedded?: boolean; onNavigate?: (address: { database: string; view?: string }) => void; } 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]); }; } export default function SheetPage({ address: mountAddress, embedded = false, onNavigate }: SheetPageProps = {}) { const instanceId = useId(); const storagePrefix = embedded ? `embed:sheet:${instanceId}:` : ""; const pageRef = useRef(null); const mountHash = sheetAddressHash({ wb: mountAddress?.wb ?? null, tab: mountAddress?.tab }); const [book, setBook] = useState(null); const includesSheetEdit = useCallback((edit: Parameters[0]) => sheetEditScope(edit, book?.id ?? mountAddress?.wb ?? ""), [book?.id, mountAddress?.wb]); const cellSaveState = useSaveState(includesSheetEdit); /** Read once for the mount decision; later opens write through `prepareWorkbookOpen`. */ const [lastWorkbookId] = useState(() => readLastWorkbook(storagePrefix)); const [sheetHash, setSheetHash] = useState(() => embedded ? mountHash : window.location.hash); const sheetHashRef = useRef(sheetHash); sheetHashRef.current = sheetHash; const currentSheetHash = useCallback( () => embedded ? sheetHashRef.current : window.location.hash, [embedded], ); const navigateSheetAddress = useCallback((address: SheetAddress, mode: "push" | "replace" = "push") => { if (!embedded) { writeSheetAddress(address, mode); return; } const next = sheetAddressHash(address); sheetHashRef.current = next; setSheetHash(next); }, [embedded]); useEffect(() => { if (!embedded) return; sheetHashRef.current = mountHash; setSheetHash(mountHash); }, [embedded, mountHash]); const [addressSelectionKey, setAddressSelectionKey] = useState(0); const [cellAddressRequest, setCellAddressRequest] = useState(0); const [tabId, setTabId] = useState(""); const [unreadableAddressTab, setUnreadableAddressTab] = useState(""); const [pendingTab, setPendingTab] = useState<{ workbookId: string; tabId: string; generation: number; } | null>(null); const [busy, setBusy] = useState(false); const [notice, setNotice] = useState(""); const showRefusal = useRefusalToast(); const [readAttempt, setReadAttempt] = useState(0); const readRetry = useRef<(() => void) | null>(null); const retryOpeningRead = () => { setNotice(""); handledSheetHashRef.current = ""; setReadAttempt((attempt) => attempt + 1); }; /** W53-T09: bumped by the ribbon's Import button; `SheetRail` opens its dialog on a change. */ const [importRequest, setImportRequest] = useState(0); /** * ⭐⭐ W53-T08 (owner instructions 14 and 19, ruling R2) — THE MACHINE'S OWN STATUS LINE IS GONE, * STATE AND ALL. Owner: *"Remove the whole strip under Home in the sheet module where * notifications like 'Recalculated in 0.0 s' appear."* W51-T11's reasoning for keeping it apart * from `notice` was correct and is not what changed; what changed is that R2 makes a formula * resolve client-side the instant it is committed, so a whole-workbook recalculation is no * longer something a person waits on and is told about afterwards. Excel agrees and it is worth * recording why: its status bar shows "Calculating (n%)" only WHILE a long recalculation runs, * and it shows no completion notice of any kind * (`AutoWiki/research/excel-formula-ux.md` section 5). * ⛔ NOTHING REPLACES IT HERE. Per R2 the per-cell shimmer on a database-bound cell is what * reports work in progress, and that lives on the cell rather than in a page-level strip. * ⚠ `notice` DIRECTLY BELOW IS A DIFFERENT LINE AND IT STAYS. It carries refusals - an edit * that did not land, a sheet that reloaded underneath you - and deleting it would take away the * only place a save conflict is ever said out loud. */ /** * ⛔ THE THIRD STATE (W50-T17). See the header: `book === null` cannot distinguish "opening" * from "could not open", and a spinner shown for the second one never stops. */ const [loading, setLoading] = useState(true); /** A LATER workbook switch. The main area waits; the rail keeps the list it is showing. */ const [opening, setOpening] = useState(false); /** * The rail's own document: workbook rows, folders, placements and stars. * * ⚠ `SheetIndex` (W51-T10) rather than `WorkbookIndex`, and the difference is two OPTIONAL * members the server does not send yet: contract C5's `sharedWithMe` and the index's own `rev`. * `sheet/types.ts` is another lane's file this wave, so the widening lives in `sheetApi.ts`; * `emptyIndex()` stays assignable because both members are optional. */ const [index, setIndex] = useState(emptyIndex); /** * S72-T64: workbook names written ahead of the index. A row below `rev` shows `name`, so an * index read that started before a rename landed never paints the old name back. */ const [railNames, setRailNames] = useState>({}); const railIndex = useMemo((): SheetIndex => { if (!Object.keys(railNames).length) return index; const named = (rows: SheetIndex["workbooks"]) => rows.map((row) => { const held = railNames[row.id]; return held && row.rev < held.rev ? { ...row, name: held.name, ...(Number.isFinite(held.rev) ? { rev: held.rev } : {}), } : row; }); return { ...index, workbooks: named(index.workbooks), ...(index.sharedWithMe ? { sharedWithMe: named(index.sharedWithMe) } : {}), }; }, [index, railNames]); const railIndexRef = useRef(railIndex); railIndexRef.current = railIndex; const folderPlacementsRef = useRef(index.itemFolders); folderPlacementsRef.current = index.itemFolders; const folderHashRef = useRef(sheetHash); /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */ const [drillAt, setDrillAt] = useState(""); /** * ⭐⭐ W54-T34 (owner instruction 10) — THE CONTROL HALF OF "I HEARD YOU". * * Owner: *"Clicking View rows still takes a long time; if it must, we need a loading button so * the user knows their click worked."* The button itself lives in `sheet/CellActionBar.tsx`, * which this ticket may not edit, so the busy state is driven through the ONE prop that already * crosses that fence: `busy`, which the bar spends on `disabled`. This flag is folded into it * below rather than being a second prop nobody forwards. * * ⛔ IT IS ITS OWN FLAG AND NOT `busy` REUSED, for the reason the CSS needs: `busy` is also a * refresh in flight, and the two want different words on the same control. `data-drill` on the * page root is what lets `styles/wave49/sheet.css` say "this control is working" rather than * "this control is unavailable", which is all `:disabled` can say on its own. */ const [drillLoading, setDrillLoading] = useState(false); /** The address whose binding is being edited, or "" for none (W49-T06). */ const [editAt, setEditAt] = useState(""); /** * ⭐⭐ W50-T21's BAR ADDRESS, AND W50-T20 LANDED ITS HANDOVER. * * The bar "mirrors the SELECTED cell" needed glide's selection, which lives inside * `SheetGrid.tsx::selected` and had no way out: `SheetGridProps` carried no `onSelect`. It does * now, and the grid fires it from an effect on that same memo, so this state is written by * BOTH doors: the grid's selection and the bar's own name box. * * ⭐ THE NAME BOX SURVIVES AND IS NOT A LEFTOVER. It is Excel's own control and it is what * makes the bar reachable from the keyboard alone. NOTHING IN `FormulaBar.tsx` CHANGED. */ const [barAddr, setBarAddr] = useState("A1"); // S67-T03 / C1: the in-cell editor's live draft, from `SheetGrid`'s `onDraftChange`, which the // formula bar shows while it is a string. null whenever no cell editor is open. const [cellDraft, setCellDraft] = useState(null); /** R18 / R20: a delete that would drop a bound cell asks first. Null when nothing is pending. */ const [bandAt, setBandAt] = useState<{ op: StructureOp; message: string; workbookId: string; tabId: string; } | null>(null); /** The tab whose menu is open, and the element it hangs off. */ const [tabMenu, setTabMenu] = useState<{ id: string; el: HTMLElement } | null>(null); /** The tab being renamed, and the draft name. Null when nothing is being renamed. */ const [tabRename, setTabRename] = useState<{ id: string; name: string } | null>(null); /** The tab whose deletion is being confirmed, because it holds cells. */ const [tabDelete, setTabDelete] = useState<{ id: string; name: string; cells: number } | null>( null, ); /** Every database this reader may open (R8). Fetched from nav, never invented here. */ const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐ W50-T18 — THE COMMIT PATH, AND WHY IT IS BUILT ON REFS RATHER THAN ON STATE. // // A commit has to read the workbook it is amending SYNCHRONOUSLY, one keystroke after the last // one, and `setBook` does not deliver that: two Enters in the same tick would both read the // pre-edit workbook and the second would overwrite the first. So the latest workbook lives in // a ref that is written at the same instant as the state, and every commit reads the ref. // // ⛔ THE SAVES ARE A CHAIN, NOT A RACE. `put_workbook` refuses a stale `rev`, so two PUTs in // flight with the same rev means the second is REFUSED. Queueing them behind one promise makes // the second send the rev the first came back with. // ═══════════════════════════════════════════════════════════════════════════════════════════ const bookRef = useRef(null); const tabIdRef = useRef(""); /** Live session copy; blocked storage still remembers positions until this page unmounts. */ const lastCellsRef = useRef(null); if (lastCellsRef.current === null) lastCellsRef.current = readLastCells(storagePrefix); /** Workbook adoption or an address chooses this target; a background refresh never moves it. */ const openAtRef = useRef({ workbookId: "", tabId: "", addr: "A1" }); const historyRef = useRef(emptyHistory()); const saveChainRef = useRef>(Promise.resolve()); const cellSaveBarrierRef = useRef>(Promise.resolve()); const acknowledgedCellRevRef = useRef(new Map()); const nameWritesRef = useRef(new Set()); const tabWritesRef = useRef(new Set()); const refreshRequestsRef = useRef(new Map>()); const refreshExportBarrierRef = useRef>(Promise.resolve()); /** Bumped by every local edit, so a save knows whether the tree moved under it. */ const editSeqRef = useRef(0); /** * A workbook identity transition is single-flight even though the rail stays interactive while * the main pane shows its opening spinner. State alone cannot guard the second click: React may * not have committed `opening` before another rail event runs, so this ref closes the boundary * synchronously and prevents an older, slower read from winning after a newer choice. */ const workbookTransitionRef = useRef(false); const addressMountedRef = useRef(false); const addressInitializedRef = useRef(false); const handledSheetHashRef = useRef(null); const acceptedAddressRef = useRef(null); // Hold the last real surface while metadata and its first tab are being read. const previousOpenRef = useRef<{ book: Workbook; address: SheetAddress; tabId: string; openAt: SheetGridProps["openAt"]; history: SheetHistory; } | null>(null); /** The one background refresh allowed to replace the workbook opened on screen. */ const openRefreshRef = useRef<{ id: string; restore: () => void } | null>(null); /** The bottom tab strip and its one pointer-captured drag. High-frequency motion stays in DOM. */ const tabStripRef = useRef(null); const tabDragRef = useRef(null); /** A completed drag emits a click after pointerup; consume that click instead of opening twice. */ const suppressTabClickRef = useRef(""); /** Clears suppression when a browser emits no post-drag click (for example after release outside). */ const suppressTabClickTimerRef = useRef(null); // ── W51-T11's five refs ──────────────────────────────────────────────────────────────────── /** Changed addresses are captured into durable cell operations in the commit turn. */ const dirtyRef = useRef>>(new Map()); /** Set by anything a cell PATCH cannot express: a row, a column, a tab, a workbook name. */ const structureDirtyRef = useRef(false); /** A refused whole snapshot cannot save again until a full read replaces its cells. */ const workbookConflictRef = useRef(null); /** The same answer for the per-tab READ, learned the same way and kept for the same reason. */ const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown"); /** Tabs holding cells in the adopted tree. Keyed `workbookId:tabId`, so books cannot collide. */ const tabLoadedRef = useRef>(new Set()); /** The latest tab navigation; an older response must not move the page or paint its notice. */ const tabNavGenRef = useRef(0); /** The pending debounce, or null when nothing is waiting. */ const saveTimerRef = useRef(null); /** * ⭐⭐ W54-T32 — DID THE DRAIN THAT JUST FINISHED ACTUALLY PERSIST WHAT IT CARRIED? * * ⛔⛔ THE ONE READER IS `onSaveBinding`, AND IT EXISTS BECAUSE A SECOND SENTENCE OVERWROTE A * TRUE ONE. Observed in the running app on a read-only tenant: the cell PATCH was refused * `503 store_write_refused` and `sendDirtyCells` said so, correctly; the recompute that follows * a binding save then asked the server about a cell that had never reached it, was correctly * answered `404 cell_missing`, and painted "Cell A1 is not filled in." over the real cause. The * reader was told the wrong thing about their own workbook. A refusal names its cause or it is * worse than silence. * * ⚠ WHY NOT THE DIRTY SET, WHICH IS THE OBVIOUS SIGNAL. It answers only the case that was * observed. `sendDirtyCells` RE-ARMS the addresses on a plain refusal (the 503 above), so the * set does distinguish that one, but four other non-landings leave it EMPTY by design and would * read as success: a 409 re-reads the tab instead, a 413 must never re-send an oversized * payload, `sendWholeWorkbook` clears the set before its PUT and does not restore it, and a * `refused[]` entry on an otherwise accepted PATCH is a cell that did not land inside a request * that did. This flag is set at each of those exits instead, which is the same list as "the * places that already write a notice of their own". * * ⚠ TRUE IS THE RESTING VALUE. A drain with nothing to send has lost nothing. */ const savedCleanRef = useRef(true); /** The current drain, so the unmount flush can call it without re-arming its own effect. */ const drainRef = useRef<() => void>(() => {}); // W57-T19: stable pair keys keep these background reads out of ordinary edits and paints. const copyPairs = useMemo(() => { const fields = new Set(); const views = new Set(); for (const sheet of book?.sheets ?? []) { // ⛔⛔ W57-T19 - `cells` IS OPTIONAL ON A STORED TAB AND `Object.values(undefined)` // THROWS. Measured: without this guard the whole Sheet route rendered its failure // card on tenant #0's own workbook, and tsc, the gates and the production build were // all green, because the shape is only wrong at RUNTIME on a tab saved without a // cells map. A background read must never be able to take the page down with it. for (const cell of Object.values(sheet?.cells ?? {})) { if (cell?.kind !== "bound" || !cell.binding) continue; const binding = cell.binding; const database = typeof binding.database === "string" ? binding.database.trim() : ""; if (!database) continue; for (const step of bindingOnDrag(binding).steps ?? []) { if (step.field !== BINDING_ENDING_STEP && step.field !== BINDING_PERIOD_STEP) fields.add(bindingOptionKey(database, step.field)); } const scope = binding.scope as { view_id?: unknown } | undefined; const viewId = typeof scope?.view_id === "string" ? scope.view_id.trim() : ""; if (viewId) views.add(JSON.stringify([database, viewId])); } } return { fields: JSON.stringify([...fields].sort()), views: JSON.stringify([...views].sort()) }; }, [book?.sheets]); const optionRequestKey = JSON.stringify([book?.id ?? "", copyPairs.fields]); const shadowRequestKey = JSON.stringify([book?.id ?? "", copyPairs.views]); const [copyOptions, setCopyOptions] = useState<{ key: string; value: OptionCatalogue }>( { key: "", value: {} }, ); const [copyShadows, setCopyShadows] = useState<{ key: string; value: SavedViewShadow[] }>( { key: "", value: [] }, ); const optionCatalogue = copyOptions.key === optionRequestKey ? copyOptions.value : undefined; const viewShadows = copyShadows.key === shadowRequestKey ? copyShadows.value : undefined; useEffect(() => { const [, pairsKey] = JSON.parse(optionRequestKey) as [string, string]; const databases = new Map>(); for (const pair of JSON.parse(pairsKey) as string[]) { const [database, field] = JSON.parse(pair) as [string, string]; const fields = databases.get(database) ?? new Set(); fields.add(field); databases.set(database, fields); } if (!databases.size) return; let live = true; const scopeOf = (database: string): SurfaceScope | null => { if (database === "customer_data") return "customer"; if (database === "product_data") return "product"; return database.startsWith("ut_") ? (database as SurfaceScope) : null; }; // HOTFIX 2026-09-29: this is a WHOLE-TABLE download per database, for drag-fill options only; // it waits until the opened tab and its refresh have gone first. A drag before it lands says // the options have not loaded (W51-T19 R10), exactly as it did on a slow network. const deferred = window.setTimeout(() => void Promise.allSettled([...databases].map(async ([database, wanted]) => { const scope = scopeOf(database); if (!scope) return; const workspace = await fetchWorkspace(scope); if (!live || !workspace) return; // The complete permission-scoped catalogue includes hidden/custom Step fields. const payload = await fetchTopicRows(topicForScope(scope)); if (!live || !payload) return; const fields = payload.fields.filter((field) => wanted.has(field.key)); const catalogue: OptionCatalogue = {}; for (const field of fields) { catalogue[bindingOptionKey(database, field.key)] = bindingStepValues( field, payload.rows, payload.userOptions ?? workspace.userOptions ?? [], ); } setCopyOptions((current) => ({ key: optionRequestKey, value: { ...(current.key === optionRequestKey ? current.value : {}), ...catalogue }, })); })), 2500); return () => { live = false; window.clearTimeout(deferred); }; }, [optionRequestKey]); // HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The Edit // panel waits on its database's workspace before it paints; warming that memo once the tab is up // lets the FIRST Edit paint at once (BindingEditor reads `peekWorkspace`, then revalidates). const boundScopesKey = useMemo(() => { const cells = book?.sheets.find((sheet) => sheet.id === tabId)?.cells ?? {}; const scopes = new Set(); for (const cell of Object.values(cells)) { const database = cell.kind === "bound" ? String((cell.binding as { database?: unknown } | undefined)?.database ?? "") : ""; const scope = database === "customer_data" ? "customer" : database === "product_data" ? "product" : database.startsWith("ut_") ? database : ""; if (scope) scopes.add(scope); } return JSON.stringify([...scopes].sort().slice(0, 4)); }, [book?.sheets, tabId]); useEffect(() => { const scopes = JSON.parse(boundScopesKey) as SurfaceScope[]; if (!scopes.length) return undefined; const timer = window.setTimeout(() => { for (const scope of scopes) if (!peekWorkspace(scope)) void fetchWorkspace(scope); }, 1500); return () => window.clearTimeout(timer); }, [boundScopesKey]); useEffect(() => { const [workbookId, pairsKey] = JSON.parse(shadowRequestKey) as [string, string]; const wanted = new Set(JSON.parse(pairsKey) as string[]); if (!workbookId || !wanted.size) return; const bindings = new Map>(); for (const sheet of bookRef.current?.sheets ?? []) { // ⛔⛔ W57-T19 - `cells` IS OPTIONAL ON A STORED TAB AND `Object.values(undefined)` // THROWS. Measured: without this guard the whole Sheet route rendered its failure // card on tenant #0's own workbook, and tsc, the gates and the production build were // all green, because the shape is only wrong at RUNTIME on a tab saved without a // cells map. A background read must never be able to take the page down with it. for (const cell of Object.values(sheet?.cells ?? {})) { if (cell?.kind !== "bound" || !cell.binding) continue; const binding = cell.binding; const scope = binding.scope as { view_id?: unknown } | undefined; const pair = JSON.stringify([String(binding.database ?? "").trim(), String(scope?.view_id ?? "").trim()]); if (wanted.has(pair) && !bindings.has(pair)) bindings.set(pair, binding); } } const controller = new AbortController(); void (async () => { try { const response = await fetch( `/api/v1/sheets/${encodeURIComponent(workbookId)}/binding-shadows`, { method: "POST", credentials: "same-origin", signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bindings: [...bindings.values()] }) }, ); if (!response.ok) return; const payload = await response.json() as { shadows?: SavedViewShadow[] }; if (!controller.signal.aborted && Array.isArray(payload.shadows)) { setCopyShadows({ key: shadowRequestKey, value: payload.shadows }); } } catch { // An unavailable snapshot keeps the grid's existing missing-view copy notice. } })(); return () => controller.abort(); }, [shadowRequestKey]); /** Write the ref and the state together. Nothing in this file calls `setBook` on its own. */ const applyLocal = useCallback((next: Workbook, restorePending = true) => { // Computes run outside the save chain; late answers must never move a revision backwards. const live = bookRef.current; if (live?.id === next.id) next = { ...next, rev: Math.max(live.rev, next.rev) }; if (restorePending) next = withPendingSheetCells(next); bookRef.current = next; setBook(next); }, []); /** Decide the opening cell in the same act that adopts the workbook. */ const prepareWorkbookOpen = useCallback(( next: Workbook, address?: SheetAddress, fallbackAddr?: string, ): string => { writeLastWorkbook(next.id, storagePrefix); const requestedTab = next.sheets.find((t) => t.id === address?.tab && (t.visibility ?? "visible") === "visible"); const selectedTab = requestedTab ?? next.sheets.find((t) => (t.visibility ?? "visible") === "visible"); const nextTab = selectedTab?.id ?? ""; const requestedCell = splitAddress(address?.cell ?? ""); const extent = sheetExtent(selectedTab); const validCell = requestedCell && requestedCell.col >= 1 && requestedCell.col <= extent.cols && requestedCell.row >= 1 && requestedCell.row <= extent.rows && !selectedTab?.hiddenCols?.includes(requestedCell.col) && !selectedTab?.hiddenRows?.includes(requestedCell.row); const addr = (validCell ? address?.cell : undefined) ?? fallbackAddr ?? lastCellsRef.current?.[next.id] ?? "A1"; openAtRef.current = { workbookId: next.id, tabId: nextTab, addr }; setUnreadableAddressTab(""); setBarAddr(addr); return nextTab; }, [storagePrefix]); const rememberLastCell = useCallback((addr: string) => { const workbookId = bookRef.current?.id; if (!workbookId) return; const next = touchLastCell(lastCellsRef.current ?? {}, workbookId, addr); lastCellsRef.current = next; writeLastCells(next, storagePrefix); }, [storagePrefix]); useEffect(() => { tabIdRef.current = tabId; }, [tabId]); // ⭐⭐ S67-T04 (QI7, 2026-09-28) — THE CELL DATABASE PANEL AND THE VIEW DATA WINDOW BELONG TO // THE TAB THEY WERE OPENED ON. Both are keyed by an ADDRESS only, so left open across a tab // switch they read the NEW tab's cell at that address, and Save wrote the binding onto the // other tab (`saveBindingAt` targets the open tab). Whatever moves the page to another tab (the // tab bar, Ctrl+PageDown, an address, a chart's destination, a deleted tab) closes both, and // unsaved panel edits are discarded exactly like Cancel (O13). Focus goes back to the grid. const panelTabRef = useRef(""); const refocusGridRef = useRef(false); useEffect(() => { if (!editAt && !drillAt) return; if (!panelTabRef.current || panelTabRef.current === tabId) return; // ⛔ The ref is NOT cleared here: a render can land between this effect and the state update // below, and with the ref empty the mount guards would let the stale address render against // the NEW tab for that one render (measured: one `/drill?tab=` request). The ref only // moves when a panel opens, and every door sets it. refocusGridRef.current = true; setEditAt(""); setDrillAt(""); setDrillLoading(false); }, [drillAt, editAt, tabId]); // Focus returns once the new tab's grid exists: a tab not loaded yet has none until its cells // arrive (which a busy store can stretch past half a minute), so this keys on the pending load // rather than on a clock, then waits a few frames for the grid's canvas to exist before asking // the grid to focus itself. Focus the person has already moved anywhere but the page body or // the Sheets tab strip is left where it is. useEffect(() => { if (!refocusGridRef.current || pendingTab) return; const deadline = performance.now() + 3000; let frame = 0; const refocus = () => { const now = document.activeElement; if (embedded && now && now !== document.body && !pageRef.current?.contains(now)) { refocusGridRef.current = false; return; } if (now && now !== document.body && !now.closest('[aria-label="Sheets"]')) { refocusGridRef.current = false; return; } const canvases = [...((embedded ? pageRef.current : document)?.querySelectorAll( '.sheet-grid-canvas canvas[data-testid="data-grid-canvas"]') ?? [])]; const main = canvases.find((c) => !c.closest(".sheet-frozen-rows")) ?? canvases[0]; if (main) { refocusGridRef.current = false; // SheetGrid focuses itself through glide (the literal is its listener's name too). document.dispatchEvent(new CustomEvent(embedded ? `aios:sheet-focus-grid:${storagePrefix}` : "aios:sheet-focus-grid")); } else if (performance.now() < deadline) { frame = window.requestAnimationFrame(refocus); } }; frame = window.requestAnimationFrame(refocus); return () => window.cancelAnimationFrame(frame); }, [embedded, pendingTab, storagePrefix, tabId]); const markDirty = useCallback((tabId2: string, addr: string) => { const held = dirtyRef.current.get(tabId2) ?? new Set(); held.add(addr); dirtyRef.current.set(tabId2, held); }, []); /** Everything in this workbook is in memory: a full read, a refresh, or a workbook just made. */ const markAllLoaded = useCallback((wb: Workbook) => { for (const t of wb.sheets) tabLoadedRef.current.add(tabKeyOf(wb.id, t.id)); }, []); useEffect(() => { const restoreDrafts = () => { if (bookRef.current) applyLocal(bookRef.current); }; const stopDrafts = editOutbox.subscribe(restoreDrafts); const stopReceipts = editOutbox.subscribeReceipts((edit, receipt) => { if (edit.kind !== "sheet-cells") return; const patch = edit.payload as SheetCellEdit; const result = receipt.result as Result | undefined; if (result?.ok) acknowledgedCellRevRef.current.set(patch.workbookId, Math.max(acknowledgedCellRevRef.current.get(patch.workbookId) ?? 0, result.value.rev)); const live = bookRef.current; if (!live || !sheetEditScope(edit, live.id)) return; if (!result?.ok) { savedCleanRef.current = false; if (result && result.code === "sheet_structure_stale") { structureDirtyRef.current = false; dirtyRef.current = new Map(); void readWorkbook(live.id).then((fresh) => { if (!fresh.ok || bookRef.current?.id !== live.id) return; historyRef.current = emptyHistory(); markAllLoaded(fresh.value); applyLocal(fresh.value); }); } return; } const value = result.value; if (value.rev < live.rev) { void readWorkbook(live.id).then((fresh) => { if (fresh.ok && bookRef.current?.id === live.id) { markAllLoaded(fresh.value); applyLocal(fresh.value); } }); savedCleanRef.current = !editOutbox.snapshot().pending.some((entry) => sheetEditScope(entry, live.id)) && !structureDirtyRef.current && !workbookConflictRef.current; return; } const refused = new Set(value.refused.map((row) => row.addr)); const pending = editOutbox.snapshot().pending.filter((entry) => sheetEditScope(entry, live.id)) .map((entry) => entry.payload as SheetCellEdit); const sheets = live.sheets.map((tab) => { const cells = { ...tab.cells }; if (tab.id === patch.tabId) for (const [addr, cell] of Object.entries(patch.cells)) { if (refused.has(addr)) continue; if (cell === null) delete cells[addr]; else cells[addr] = cell; } const rows = tab.id === patch.tabId ? value.computed : value.computedTabs[tab.id]; for (const [addr, row] of Object.entries(rows ?? {})) { const cell = cells[addr]; if (!cell || cell.kind !== "bound" || pending.some((entry) => entry.tabId === tab.id && addr in entry.cells)) continue; const merged: Cell = { ...cell, value: row.value, display: row.display, state: row.state as Cell["state"] }; if (row.refusal) merged.refusal = row.refusal; else delete merged.refusal; cells[addr] = merged; } return { ...tab, cells }; }); applyLocal({ ...live, rev: value.rev, sheets }); savedCleanRef.current = pending.length === 0 && !structureDirtyRef.current && !workbookConflictRef.current; if (pending.length === 0 && structureDirtyRef.current) drainRef.current(); }); void editOutbox.start().then(restoreDrafts); return () => { stopDrafts(); stopReceipts(); }; }, [applyLocal, markAllLoaded]); useEffect(() => { if (!book || (acknowledgedCellRevRef.current.get(book.id) ?? 0) <= book.rev) return; // A restored receipt can arrive before the workbook's opening read finishes. void readWorkbook(book.id).then((fresh) => { if (!fresh.ok || bookRef.current?.id !== book.id) return; markAllLoaded(fresh.value); applyLocal(fresh.value); }); }, [book, applyLocal, markAllLoaded]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⛔⛔ THE `historyRef` DECISION, WHICH THE TICKET ASKS TO BE STATED IN A COMMENT. // // `pushHistory` snapshots the WHOLE `sheets` array, so every recorded step describes a tree in // which an unloaded tab has NO CELLS. Merge that tab's real cells in afterwards and the stack // is now lying about it: one Ctrl+Z would restore the empty version, and because undo SAVES, // the emptiness would then be written. That is silent data loss caused by a keystroke that is // supposed to be the safe one. // // ⭐ SO: A LAZY LOAD DROPS THE UNDO STACK, BUT ONLY WHEN THE TAB IT LOADED HOLDS SOMETHING. // Loading an empty tab changes nothing an undo could get wrong, and dropping the stack on every // tab switch would punish the ordinary case for the rare one. What the narrow rule still gives // up is a tab's GEOMETRY (its `cols`, `rows` and dragged column widths): an undo can put those // back to the defaults the placeholder carried. That is recoverable by dragging, it is not // data, and it is written down here rather than hidden. Booked as a follow-up. // ═══════════════════════════════════════════════════════════════════════════════════════════ const mergeTab = useCallback((workbookId: string, next: SheetTab) => { const live = bookRef.current; if (!live || live.id !== workbookId) return; // S67-T09: two `ensureTabs` calls can both see a tab unloaded and both read it. The read that // lands SECOND must not overwrite the first one's tab, or it wipes whatever was written onto // that tab in between (a moved block's re-anchored references) and empties the undo history. if (tabLoadedRef.current.has(tabKeyOf(workbookId, next.id))) return; tabLoadedRef.current.add(tabKeyOf(workbookId, next.id)); if (tabHoldsCells(next)) historyRef.current = emptyHistory(); editSeqRef.current += 1; applyLocal({ ...live, rev: tabRevOf(next, live), sheets: live.sheets.map((t) => (t.id === next.id ? { ...t, ...next } : t)), }); }, [applyLocal]); /** * ⭐⭐ MAKE SURE THE NAMED TABS ARE IN MEMORY, AND ANSWER WHETHER THEY NOW ARE. * * This is the lazy fetch, its cache and its repair path in one door, because all three have to * agree about what "loaded" means. A tab already loaded in the current adopted tree is not * fetched twice; adopting fresh metadata invalidates the entries for the empty tabs it brings. * * ⛔ THE REPAIR IS WHAT MAKES THIS SAFE ON A SERVER THAT SERVES NEITHER NEW ROUTE. If the * per-tab read answers `status >= 400` and not 403, the route is absent, so the WHOLE workbook * is read in one go and every tab that is not already loaded takes its cells from that read. * Loaded tabs keep local edits while the server revision is adopted independently. * * ⛔ AND IT IS KEYED ON `status >= 400 && status !== 403`, NEVER ON 404. The tab route sits * under the `/sheets/{workbook_id}` path parameter, so an unbuilt route there answers 405 and a * `=== 404` test would leave this stuck. [[an-unbuilt-route-under-a-path-param-answers-405]] */ const rememberOpenWorkbook = useCallback(() => { const live = bookRef.current; const address = acceptedAddressRef.current; previousOpenRef.current = live && address?.wb === live.id ? { book: live, address, tabId: tabIdRef.current, openAt: { ...openAtRef.current, addr: barAddr }, history: historyRef.current, } : null; }, [barAddr]); const restoreMissingOpen = useCallback((id: string, missingTab?: string) => { // A late refusal must not undo a newer address choice or reopen a page already left. if (!addressMountedRef.current || readSheetAddress(currentSheetHash())?.wb !== id) return; if (embedded && !missingTab) { bookRef.current = null; setBook(null); setTabId(""); setEditAt(""); setDrillAt(""); setUnreadableAddressTab(""); showRefusal(ITEM_NOT_AVAILABLE); acceptedAddressRef.current = null; handledSheetHashRef.current = currentSheetHash(); return; } const previous = previousOpenRef.current; const candidate = previous?.book.id === id ? missingTab ? { ...previous.book, sheets: previous.book.sheets.filter((t) => t.id !== missingTab) } : null : previous?.book; const previousTab = candidate?.sheets.find((t) => t.id === previous?.tabId) ?? candidate?.sheets.find((t) => (t.visibility ?? "visible") === "visible" && tabLoadedRef.current.has(tabKeyOf(candidate.id, t.id))); const restored = candidate && previousTab ? candidate : null; const address: SheetAddress = restored && previous ? { ...previous.address, wb: restored.id, tab: previousTab!.id } : { wb: null }; bookRef.current = restored; setBook(restored); tabIdRef.current = restored ? previousTab!.id : ""; setTabId(tabIdRef.current); setEditAt(""); setDrillAt(""); setUnreadableAddressTab(""); setNotice(""); if (restored && previous) { openAtRef.current = { ...previous.openAt, workbookId: restored.id, tabId: previousTab!.id }; setBarAddr(previous.openAt?.addr ?? "A1"); historyRef.current = missingTab && restored.id === id ? emptyHistory() : previous.history; writeLastWorkbook(restored.id, storagePrefix); } acceptedAddressRef.current = restored ? address : null; handledSheetHashRef.current = sheetAddressHash(address); // Notify the shell through the existing History API path so a bare address mounts the gallery. navigateSheetAddress(address, "replace"); }, [currentSheetHash, embedded, navigateSheetAddress, storagePrefix]); const discardMissingWorkbook = useCallback((id: string, refusal: { status: number; code?: string }) => { if (!isMissingItem("workbook", refusal)) return false; itemDeleted({ kind: "workbook", id }); setNotice(""); if (bookRef.current?.id === id) { bookRef.current = null; setBook(null); setTabId(""); setEditAt(""); setDrillAt(""); } restoreMissingOpen(id); return true; }, [restoreMissingOpen]); useEffect(() => { const drop = (event: Event) => { const item = (event as CustomEvent).detail; if (item?.kind !== "workbook") return; if (previousOpenRef.current?.book.id === item.id) previousOpenRef.current = null; setIndex((current) => ({ ...current, workbooks: current.workbooks.filter((row) => row.id !== item.id), sharedWithMe: current.sharedWithMe?.filter((row) => row.id !== item.id), })); }; window.addEventListener(ITEM_DELETED_EVENT, drop); return () => window.removeEventListener(ITEM_DELETED_EVENT, drop); }, []); /** * Only the current tab navigation may restore a missing tab or write its refusal notice. * Read the generation AFTER each await: another click may have won while the request was away. * * ⛔ THE CELL LOADS ARE NOT NAVIGATION. Keep merging by tab id, settling the route and marking * loaded tabs even when the navigation is stale. `sendWholeWorkbook` awaits this same fence: * its PUT writes `sheets` verbatim, so skipping cells behind the navigation guard could send * the empty maps from `?tabs=meta` and silently delete unvisited sheets' data. Callers without * a navigation generation keep their existing behavior and the same loaded/not-loaded answer. * * Pass a predicate rather than a generation number: the W61-T22 runner executes this function * under `with (env)` against a fixture it owns, so a new free identifier here causes a * ReferenceError in that gate rather than a compile error here. */ const ensureTabs = useCallback(async ( workbookId: string, keys: string[], quiet = false, stillCurrent?: () => boolean, ): Promise => { const wanted = keys.filter((k) => k && !tabLoadedRef.current.has(tabKeyOf(workbookId, k))); if (wanted.length === 0) return true; if (tabRouteRef.current !== "no") { let served = true; for (const key of wanted) { const got = await readTab(workbookId, key); const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard"; if (!got.ok && discardMissingWorkbook(workbookId, got)) return false; if (!got.ok && got.status === 404 && got.code === "tab_missing") { const live = bookRef.current; if (live?.id === workbookId) { applyLocal({ ...live, sheets: live.sheets.filter((tab) => tab.id !== key) }); if (still === "apply" && tabIdRef.current === key) setTabId(""); } if (still === "apply") { setNotice(""); restoreMissingOpen(workbookId, key); } return false; } if (got.ok && got.value) { tabRouteRef.current = "yes"; mergeTab(workbookId, got.value); continue; } const absent = !got.ok && got.status >= 400 && got.status !== 403; if (!absent || tabRouteRef.current === "yes") { // ⛔ A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly // like the cells having been deleted, so the reason is said instead. if (!quiet && still === "apply") { setNotice(got.ok ? "That sheet could not be read, so it is not shown." : got.message); readRetry.current = () => { setNotice(""); void ensureTabs(workbookId, [key], false, stillCurrent); }; } return false; } tabRouteRef.current = "no"; served = false; break; } if (served) return true; } const fresh = await readWorkbook(workbookId); const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard"; if (!fresh.ok) { if (discardMissingWorkbook(workbookId, fresh)) return false; if (!quiet && still === "apply") { setNotice(fresh.message); readRetry.current = () => { setNotice(""); void ensureTabs(workbookId, keys, false, stillCurrent); }; } return false; } const live = bookRef.current; if (!live || live.id !== workbookId) return false; let dropHistory = false; const sheets = live.sheets.map((s) => { if (tabLoadedRef.current.has(tabKeyOf(workbookId, s.id))) return s; const full = fresh.value.sheets.find((f) => f.id === s.id); if (!full) return s; if (tabHoldsCells(full)) dropHistory = true; return { ...s, ...full }; }); if (dropHistory) historyRef.current = emptyHistory(); editSeqRef.current += 1; applyLocal({ ...live, sheets, rev: fresh.value.rev }); markAllLoaded({ ...live, sheets }); return true; }, [applyLocal, markAllLoaded, mergeTab, discardMissingWorkbook, restoreMissingOpen]); // Workbook transitions own their loading state and invalidate any tab-only navigation. useEffect(() => { tabNavGenRef.current += 1; setPendingTab(null); }, [book?.id, opening]); /** * Resolve the bound cells a structural edit or a new tab left without an answer. * ⛔ Opening a workbook or a tab never calls this: an open only reads stored results. * A cell the server serves stale with a reason keeps its stored value and is not resolved here. * * ⛔ THIS PASS NEVER SETS `busy`. The grid stays usable while a large workbook recomputes, * and the existing per-cell stale mark is the progress signal. Its answer is abandoned when a * newer open owns the pass, the reader moved to another workbook, the reader typed while it was * away, or the read failed. In every abandon path only the pending cell objects this pass painted * are restored, so neither cached values nor newer edits are replaced. */ const refreshOpenedWorkbook = useCallback((wid: string, loadedTab: string) => { const painted = bookRef.current; if (!painted || painted.id !== wid || !tabLoadedRef.current.has(tabKeyOf(wid, loadedTab))) return; const loaded = painted.sheets.find((tab) => tab.id === loadedTab); // ⭐⭐ HOTFIX 2026-09-29 (owner: "the whole sheet cell database is pulsing because its still // loading ... we should only update or refresh cells that are affected"). ONE cell without an // answer used to mark EVERY bound cell on the tab pending and re-resolve the WHOLE workbook // (~470 cells, minutes on Daily Sales). Now only the cells that need it are marked, sent to // `POST /refresh {cells}`, and merged back one by one; every other cell keeps its answer. const needs = loaded ? Object.entries(loaded.cells).filter(([, cell]) => cell.kind === "bound" && ((cell.state === "stale" && !isSettledStale(cell)) || (cell.state === "refused" && cell.refusal?.code === "sheet_refresh_required"))) : []; if (needs.length === 0) return; const pass = { id: wid, restore: () => restoreMarkedCells() }; openRefreshRef.current = pass; const marked = new Map(); const cells = { ...loaded!.cells }; for (const [addr, cell] of needs) { const pending: Cell = cell.state === "stale" ? cell : { ...cell, state: "stale" }; marked.set(addr, { before: cell, pending }); cells[addr] = pending; } applyLocal({ ...painted, sheets: painted.sheets.map((tab) => tab.id === loadedTab ? { ...tab, cells } : tab) }); const restoreMarkedCells = () => { const live = bookRef.current; if (!live || live.id !== wid) return; let restored = false; const restoredSheets = live.sheets.map((tab) => { if (tab.id !== loadedTab) return tab; const next = { ...tab.cells }; for (const [addr, held] of marked.entries()) { if (next[addr] !== held.pending || held.pending === held.before) continue; next[addr] = held.before; restored = true; } return restored ? { ...tab, cells: next } : tab; }); if (restored) applyLocal({ ...live, sheets: restoredSheets }); }; refreshExportBarrierRef.current = (async () => { const got = await refreshCells(wid, [...marked.keys()].map((addr) => `${loadedTab}!${addr}`)); const live = bookRef.current; if (!got.ok || !live || live.id !== wid) { restoreMarkedCells(); if (openRefreshRef.current === pass) openRefreshRef.current = null; return; } // Merged CELL BY CELL: a cell the reader edited meanwhile is no longer the pending object // this pass painted, so its answer is dropped and their edit stands. No history is cleared. let changed = false; const sheets = live.sheets.map((tab) => { if (tab.id !== loadedTab) return tab; const next = { ...tab.cells }; for (const [addr, held] of marked.entries()) { const row = got.value.cells[`${loadedTab}!${addr}`]; if (next[addr] !== held.pending) continue; if (!row) { if (held.pending !== held.before) { next[addr] = held.before; changed = true; } continue; } const merged: Cell = withCellLimits({ ...held.before, value: row.value, display: row.display, state: row.state as Cell["state"] }, row.limits); if (row.refusal) merged.refusal = row.refusal; else delete merged.refusal; if (row.refreshed_at) merged.refreshed_at = row.refreshed_at; next[addr] = merged; changed = true; } return changed ? { ...tab, cells: next } : tab; }); const rev = typeof got.value.rev === "number" ? got.value.rev : live.rev; if (changed || rev > live.rev) applyLocal({ ...live, sheets, rev: Math.max(rev, live.rev) }); if (openRefreshRef.current === pass) openRefreshRef.current = null; })().catch(() => { restoreMarkedCells(); if (openRefreshRef.current === pass) openRefreshRef.current = null; }); }, [applyLocal]); /** The tab bar's own door: switch, then fetch the cells if this is the first visit. */ const openTab = useCallback((id: string) => { rememberOpenWorkbook(); setUnreadableAddressTab(""); setNotice(""); setTabId(id); const generation = ++tabNavGenRef.current; const current = bookRef.current; const needsCells = current && !tabLoadedRef.current.has(tabKeyOf(current.id, id)); setPendingTab(needsCells ? { workbookId: current.id, tabId: id, generation } : null); // Opening a tab only reads. The sync schedule and the Refresh button compute bound cells. if (!current || !needsCells) return; const stillCurrent = () => tabNavVerdict(generation, tabNavGenRef.current) === "apply" && addressMountedRef.current && !workbookTransitionRef.current && bookRef.current?.id === current.id && readSheetAddress(currentSheetHash())?.wb === current.id; void (async () => { try { const loaded = await ensureTabs(current.id, [id], false, stillCurrent); // Missing tabs and workbooks already restore a real surface through ensureTabs. if (!loaded && stillCurrent() && bookRef.current?.sheets.some((tab) => tab.id === id)) { setUnreadableAddressTab(id); } } catch { if (stillCurrent()) { setNotice("That sheet could not be read, so it is not shown."); readRetry.current = () => openTab(id); setUnreadableAddressTab(id); } } finally { setPendingTab((pending) => pending?.generation === generation ? null : pending); } })(); }, [currentSheetHash, ensureTabs, rememberOpenWorkbook]); // Wave 60 base kit: a hidden or very hidden sheet has no tab, so it is never the open one. When // the open tab is hidden (by the View ribbon, an undo, or a workbook that opened on one), the // page opens the first visible tab through the tab bar's own door, which fetches its cells. // A stale pair whose snapshot lacks the selected tab must leave the page alone. useEffect(() => { if (!book) return; const next = hiddenTabRedirect(book.sheets, tabId); if (next) openTab(next); }, [book, openTab, tabId]); // Read the whole hash, as the shell does: workbook changes keep the same route key. useEffect(() => { addressMountedRef.current = true; if (embedded) return () => { addressMountedRef.current = false; }; const onHashChange = () => { const hash = window.location.hash; const workbookId = readSheetAddress(hash)?.wb; const previous = folderHashRef.current; const folder = readSheetFolder(hash) ?? (workbookId && workbookId === readSheetAddress(previous)?.wb ? readSheetFolder(previous) : undefined) ?? (workbookId ? folderPlacementsRef.current[workbookId] : undefined); const next = reattachSheetFolder(folder); folderHashRef.current = next; if (handledSheetHashRef.current === hash) handledSheetHashRef.current = next; setSheetHash(next); }; window.addEventListener("hashchange", onHashChange); onHashChange(); return () => { addressMountedRef.current = false; window.removeEventListener("hashchange", onHashChange); }; }, [embedded]); // R8: "any database the user or a shared user has access to". The list comes from the nav door, // so a cell can never offer a database the rail does not, and this page invents nothing. useEffect(() => { let live = true; (async () => { try { const res = await fetch("/api/v1/nav", { credentials: "same-origin" }); if (!res.ok) return; const body = (await res.json()) as { pages?: { key: string; label: string }[] }; if (!live) return; setDatabases((body.pages ?? []) .filter((p) => p && typeof p.key === "string") .map((p) => ({ key: p.key, label: p.label || p.key }))); } catch { /* the editor simply offers nothing, and says so through its own empty picker */ } })(); return () => { live = false; }; }, []); const onRefresh = useCallback(async (scope: RefreshScope = { workbook: true }, retryId?: string) => { if (!book) return; setBusy(true); setNotice(""); const refreshSeq = editSeqRef.current; const hadPending = dirtyRef.current.size > 0 || structureDirtyRef.current; const pending = retryId ? retryRefresh(book.id, retryId) : refreshScope(book.id, scope, refreshRequestsRef.current); refreshExportBarrierRef.current = pending; const got = await pending; setBusy(false); if (bookRef.current?.id !== book.id) return; if (!got.ok) { if (typeof got.rev_current === "number") applyLocal({ ...bookRef.current, rev: got.rev_current }); showRefusal(got.message); return; } const live = bookRef.current; if (hadPending || editSeqRef.current !== refreshSeq || dirtyRef.current.size > 0 || structureDirtyRef.current || got.value.workbook.rev < live.rev) { applyLocal({ ...live, rev: got.value.workbook.rev }); return; } // ⚠ A refresh REPLACES the tree the undo stack was taken against, so the stack is dropped // rather than left pointing at cells that no longer hold the values it recorded. historyRef.current = emptyHistory(); editSeqRef.current += 1; dirtyRef.current = new Map(); const refreshed = applyRefreshScope(live, got.value); if (!("cells" in got.value)) markAllLoaded(refreshed); applyLocal(refreshed); // ⭐⭐ W53-T08 (instruction 14, ruling R2) — THE RECALC TIME IS NO LONGER ANNOUNCED. Wave 49's // R4 asked for it to be shown; instruction 14 retires that, and R2 is why it stops being // useful information: a formula now resolves as it is committed, so the number this reported // was the cost of a whole-workbook round trip that the commit path no longer makes. // ⚠ `got.value.recalcMs` is still READ from the response and simply not painted; the server // half is untouched, and lane C keeps `POST /sheets/{id}/refresh` for the load and import // paths. }, [applyLocal, book, markAllLoaded]); // The action bar's Edit button opens the binding panel below, for any cell - R5 (W52-T09) // retired the separate "typing over this cell needs confirming" question this comment once // described; a typed value now commits directly, through `SheetGrid.tsx::onKeyDown`. const onEdit = useCallback((addr: string, _cell: Cell | null) => { setNotice(""); panelTabRef.current = tabIdRef.current; setEditAt(addr); }, []); useEffect(() => { const openCellData = () => { if (!barAddr) return; setNotice(""); panelTabRef.current = tabIdRef.current; setEditAt(barAddr); }; const name = embedded ? `${OPEN_CELL_DATA_EVENT}:${storagePrefix}` : OPEN_CELL_DATA_EVENT; document.addEventListener(name, openCellData); return () => document.removeEventListener(name, openCellData); }, [barAddr, embedded, storagePrefix]); /** Accept every dirty delta before waiting for any earlier network request. */ const sendDirtyCells = useCallback((): Promise => { const pending = dirtyRef.current; dirtyRef.current = new Map(); const requests: Promise[] = []; for (const [tabKey, addrs] of pending) { const current = bookRef.current; const sheet = current?.sheets.find((tab) => tab.id === tabKey); if (!current || !sheet) continue; const cells: Record = {}; for (const addr of addrs) cells[addr] = sheet.cells?.[addr] ?? null; requests.push(patchTabCells(current.id, tabKey, { cells, rev: tabRevOf(sheet, current) })); } const accepted = Promise.all(requests); cellSaveBarrierRef.current = Promise.all([cellSaveBarrierRef.current, accepted]); return accepted.then(() => undefined); }, []); /** Discard the refused tree; a failed read keeps every later save behind this read fence. */ const reloadWholeWorkbookAfterConflict = useCallback(async (workbookId: string) => { workbookConflictRef.current = workbookId; savedCleanRef.current = false; dirtyRef.current = new Map(); structureDirtyRef.current = false; const fresh = await readWorkbook(workbookId); if (bookRef.current?.id !== workbookId) return; if (!fresh.ok) { showRefusal("Your edit was not saved. Reload the workbook before editing again."); return; } historyRef.current = emptyHistory(); editSeqRef.current += 1; // Edits made during this read belong to the refused tree too, including shifted addresses. dirtyRef.current = new Map(); structureDirtyRef.current = false; markAllLoaded(fresh.value); applyLocal(fresh.value); workbookConflictRef.current = null; showRefusal("This workbook changed. Your edit was not saved and the workbook was reloaded."); }, [applyLocal, markAllLoaded]); /** * Send the workbook the ref currently holds for structure changes only. * Adopt the server's full answer only if no keystrokes landed during the round trip. */ const sendWholeWorkbook = useCallback(async (structural = false) => { const opening = bookRef.current; if (!opening) return; // ⛔⛔ THE FENCE. This PUT writes `sheets` verbatim, and after a `?tabs=meta` open the tabs // nobody has visited hold an EMPTY cell map. Sending that would delete them, silently, with // every gate green. So every tab is read in first, and a workbook that cannot be completed // is not written at all. const whole = await ensureTabs(opening.id, opening.sheets.map((t) => t.id)); const current = bookRef.current; // `ensureTabs` awaits network reads. If another transition won while those reads were away, // never turn that newer workbook into the subject of this older drain. if (!current || current.id !== opening.id) return; if (!whole) { // ⛔⛔ THE FLAG GOES BACK ON, AND THIS IS THE SAME RE-ARM DISCIPLINE THE DIRTY SET GETS. // `drainSave` clears `structureDirtyRef` before the await, so a return from here without // restoring it would leave the next drain believing there is no structure change pending: // it would take the CELL PATCH instead, sending addresses whose positions have already // moved, against a server still holding the row that was inserted. The insert would never // be sent and the cells that were would describe a grid the server does not have. structureDirtyRef.current = true; savedCleanRef.current = false; showRefusal("Some sheets in this workbook could not be read, so nothing was saved. " + "Reload the page and try again."); return; } // The PUT carries every cell, so anything the dirty set was still holding is covered by it. dirtyRef.current = new Map(); const seq = editSeqRef.current; const payload = { name: current.name, sheets: current.sheets, rev: current.rev, printSettings: current.printSettings, namedRanges: current.namedRanges, structureChanged: structural, }; const saved = await writeWorkbook(current.id, payload); if (bookRef.current?.id !== current.id) return; if (!saved.ok) { // A current revision does not make these old cells current. Never re-send this snapshot. if (saved.code === "sheet_structure_stale" || saved.code === "workbook_revision_stale") { await reloadWholeWorkbookAfterConflict(current.id); return; } // A refusal that is not a revision conflict leaves the local tree intact, so the pending // structure change is still pending and the next drain must still carry it. structureDirtyRef.current = true; savedCleanRef.current = false; showRefusal(saved.message); return; } if (bookRef.current?.id !== current.id) return; if (editSeqRef.current === seq && saved.value.rev >= bookRef.current.rev) { markAllLoaded(saved.value); applyLocal(saved.value); } else if (bookRef.current?.id === current.id) { applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at }); } }, [applyLocal, ensureTabs, markAllLoaded, reloadWholeWorkbookAfterConflict]); /** * ⭐ ONE DRAIN, BEHIND WHATEVER SAVE IS ALREADY IN FLIGHT. * * ⛔ THE CHAIN IS WHAT MAKES A REVISION GUARD WORK AT ALL: two writes in flight carrying the * same `rev` means the second is refused, so they are queued rather than raced. The debounce * decides WHEN a drain is appended; the chain decides that only one runs at a time. */ const drainSave = useCallback(() => { saveChainRef.current = saveChainRef.current.then(async () => { if (!bookRef.current) return; if (workbookConflictRef.current === bookRef.current.id) { await reloadWholeWorkbookAfterConflict(bookRef.current.id); return; } if (!structureDirtyRef.current) void sendDirtyCells(); await cellSaveBarrierRef.current; if (!bookRef.current) return; if (editOutbox.snapshot().pending.some((edit) => sheetEditScope(edit, bookRef.current!.id))) { savedCleanRef.current = false; return; } const structural = structureDirtyRef.current; structureDirtyRef.current = false; const hasPendingCells = dirtyRef.current.size > 0; // A flush appends a drain behind any request already in flight. If that request refuses, // the appended drain may find nothing to send; it must not turn the refusal back into a // clean result merely by existing. Only a drain that owns real pending authored work may // clear the prior failure, and each refusal path below sets it false again. if (!structural && !hasPendingCells) return; savedCleanRef.current = true; if (!structural) return; await sendWholeWorkbook(structural); // HOTFIX 2026-09-29: a row or column edit leaves the bound cells whose references moved // `stale`, and nothing resolved them, so they shimmered until a manual Refresh. Resolve // exactly those cells now that the new structure is saved. const after = bookRef.current; if (structural && after && tabIdRef.current) refreshOpenedWorkbook(after.id, tabIdRef.current); }); }, [sendDirtyCells, sendWholeWorkbook, refreshOpenedWorkbook, reloadWholeWorkbookAfterConflict]); useEffect(() => { drainRef.current = drainSave; }, [drainSave]); /** * ⛔ AN UNMOUNT WITH A TIMER STILL PENDING IS AN EDIT THE PERSON WATCHED THEMSELVES MAKE AND * WILL NEVER SEE AGAIN. Navigating away inside the debounce window has to drain, not discard. */ useEffect(() => () => { if (saveTimerRef.current !== null) { window.clearTimeout(saveTimerRef.current); saveTimerRef.current = null; drainRef.current(); } if (suppressTabClickTimerRef.current !== null) { window.clearTimeout(suppressTabClickTimerRef.current); suppressTabClickTimerRef.current = null; } }, []); /** Drain now, cancelling any pending debounce, and answer when the write has finished. */ const flushSave = useCallback((): Promise => { if (saveTimerRef.current !== null) { window.clearTimeout(saveTimerRef.current); saveTimerRef.current = null; } drainSave(); return saveChainRef.current; }, [drainSave]); /** * C2's bounded barrier before a workbook identity changes. * * `flushSave` is intentionally called before the target workbook is even requested or created: * the old workbook must keep owning `bookRef`, its dirty addresses and its revision until the * final queued write has settled. A timeout does not cancel that write. It leaves the current * workbook in place, which lets the ordinary stale-revision/refusal recovery finish without a * late response ever being adopted into a different workbook. */ const flushBeforeWorkbookChange = useCallback(async (): Promise => { const leavingId = bookRef.current?.id; if (!leavingId) return true; let timer: number | null = null; const outcome = await Promise.race([ flushSave().then(() => "flushed" as const), new Promise<"timeout">((resolve) => { timer = window.setTimeout(() => resolve("timeout"), SAVE_FLUSH_TIMEOUT_MS); }), ]); if (timer !== null) window.clearTimeout(timer); if (outcome === "timeout") { showRefusal("This workbook is still saving. Wait for it to finish before opening another one."); workbookTransitionRef.current = false; return false; } // A refusal already left its exact sentence in `notice`. Do not hide it behind a generic // transition error, and do not clear the dirty tree by adopting another workbook. const mayChange = savedCleanRef.current && bookRef.current?.id === leavingId; if (!mayChange) workbookTransitionRef.current = false; return mayChange; }, [flushSave]); /** * ⭐⭐ THE DEBOUNCE THE TICKET ASSUMED ALREADY EXISTED. Every commit, undo, redo, binding save * and structure op calls this; the drain runs once the typing stops. * * ⚠ THE NAME IS PINNED. `verify_wiring.py`'s W51-T08 leg matches `const onSaveNow = useCallback * (() => { queueSave();`, so this door keeps its name and Ctrl+S keeps calling it, whatever the * body now does. */ const queueSave = useCallback(() => { // Durability starts in the commit turn, before debounce or an earlier network promise. if (!structureDirtyRef.current && !workbookConflictRef.current) void sendDirtyCells(); if (saveTimerRef.current !== null) window.clearTimeout(saveTimerRef.current); saveTimerRef.current = window.setTimeout(() => { saveTimerRef.current = null; drainSave(); }, SAVE_DEBOUNCE_MS); }, [drainSave, sendDirtyCells]); /** * ⭐ W51-T08 / C1 — CTRL+S. The grid owns the keystroke; the save belongs to the page, because * `queueSave` is what serialises a save behind whichever one is already in flight. * * ⭐ W51-T11 / R4 — AND IT IS THE DIRTY SET'S SECOND DOOR. Saving is already automatic on a * debounce, so what Ctrl+S adds is IMMEDIACY: the pending timer is cancelled and the drain runs * now. Pressing it twice costs one extra round trip and cannot reorder anything. */ const onSaveNow = useCallback(() => { queueSave(); void flushSave(); }, [queueSave, flushSave]); const captureExport = useCallback(async () => { const opening = bookRef.current; const activeSheetId = tabIdRef.current || opening?.sheets[0]?.id || ""; if (!opening) throw new Error("Open a workbook before exporting."); await refreshExportBarrierRef.current; await flushSave(); if (!savedCleanRef.current) throw new Error("Save the workbook successfully before exporting."); if (bookRef.current?.id !== opening.id) throw new Error("The workbook changed. Open Export again."); if (!await ensureTabs(opening.id, bookRef.current.sheets.map(sheet => sheet.id))) throw new Error("Some sheets could not be loaded. Try exporting again."); await flushSave(); const live = bookRef.current; if (!live || live.id !== opening.id || !savedCleanRef.current) throw new Error("The workbook changed or could not be saved. Try exporting again."); const checks = await readWorkbookChecks(live.id); if (!checks.ok) throw new Error(checks.message); if (checks.value.rev !== live.rev || bookRef.current !== live || !savedCleanRef.current) throw new Error("The workbook changed. Open Export again."); const { checks: priorChecks, checkResults: priorResults, ...authored } = live as import("./sheetApi").CheckedWorkbook; void priorChecks; void priorResults; return { book: structuredClone({ ...authored, ...(checks.value.checks.length ? { checks: checks.value.checks } : {}), ...(checks.value.checkResults ? { checkResults: checks.value.checkResults } : {}) }), activeSheetId }; }, [ensureTabs, flushSave]); const savePrintSettings = useCallback(async (settings: SheetPrintSettings) => { const snapshot = await captureExport(); const live = bookRef.current; if (!live || live.id !== snapshot.book.id) throw new Error("The workbook changed. Open Export again."); editSeqRef.current += 1; structureDirtyRef.current = true; savedCleanRef.current = false; applyLocal({ ...live, printSettings: settings }); await flushSave(); if (!savedCleanRef.current || bookRef.current?.id !== live.id) throw new Error("The print settings could not be saved."); }, [applyLocal, captureExport, flushSave]); /** * ⭐⭐ W53-T09 (owner instruction 20) — THE IMPORT DOOR IS LIVE. THIS IS THE ONE EDIT W51-T13 * WAS SUPPOSED TO MAKE AND NEVER DID. * * The owner reported that the ribbon's Import button does nothing, and the code looked wired, * which is exactly why two reads missed it: `Ribbon.tsx`'s `case "import"` calls * `onOpenImport?.()`, `SheetGrid.tsx` forwards it, and the chain arrived HERE at a function * whose whole body was `return;` under the comment *"Deliberately inert until then."* The seam * was honest when it was written; W51-T13 never landed, so a placeholder shipped as a dead * control. ⚠ THIS IS THE SHAPE TO WATCH FOR: a deliberately inert handler is indistinguishable * from a working one at every layer above it, and no gate can tell them apart. * ⛔ NO SECOND DIALOG. `SheetRail.tsx` already owns `ImportDialog` for its own "Import .xlsx" * menu item, so this bumps a counter the rail watches: one dialog, two doors. A counter rather * than a boolean because a boolean would have to be reset from here when the dialog closed, * which is the two-way coupling the rail's own note explains. */ const onOpenImport = useCallback(() => setImportRequest((n) => n + 1), []); /** * ⭐ THE ONE COMMIT DOOR. Every edit the grid can make arrives here: a typed cell, a paste, a * fill, a range delete and the R20 conversion. It takes ONE history step, applies the cells * through `sheetState.ts::withCells` and queues ONE save, which is what makes an undo of a * paste undo the whole paste rather than its last cell. */ const commitCellsRef = useRef<(edits: Record, move?: MovedBlock) => void>( () => undefined); const commitCells = useCallback((edits: Record, move?: MovedBlock) => { const base = bookRef.current; if (!base || Object.keys(edits).length === 0) return; const target = base.sheets.find((t) => t.id === tabIdRef.current)?.id ?? base.sheets[0]?.id ?? ""; if (!target) return; // S67-T09: re-anchoring reads every tab (the rule `structureBase` keeps for structure), and a // tab never opened has no cells here yet. Load them all, then land the move in ONE step; if // they cannot load, the move still lands and says nothing it cannot back up. if (move) { const all = base.sheets.map((t) => t.id); if (all.some((id) => !tabLoadedRef.current.has(tabKeyOf(base.id, id)))) { void ensureTabs(base.id, all).then((ok) => commitCellsRef.current(edits, ok ? move : undefined)); return; } } historyRef.current = pushHistory(historyRef.current, base.sheets, { namedRanges: base.namedRanges }); // ⭐⭐ S67-T09 (QI5, D-3285) — A MOVED BLOCK TAKES ITS REFERENCES ALONG, ON EVERY TAB, IN THIS // SAME HISTORY STEP, so one Undo puts the block AND every reference back. References live on // other tabs and in the workbook's named ranges, which a cell PATCH cannot carry, so a move // that re-points anything saves through the whole-workbook PUT, as structure does. if (move) { const landed = withCells(base, target, edits); const movedOn = landed.sheets.find((t) => t.id === target)?.name ?? ""; const out = reanchorWorkbookForMove(landed.sheets, landed.namedRanges, movedOn, move); if (out.changed > 0) { editSeqRef.current += 1; setNotice(""); structureDirtyRef.current = true; applyLocal({ ...landed, sheets: out.sheets, namedRanges: out.namedRanges }, false); queueSave(); return; } } editSeqRef.current += 1; setNotice(""); // ⭐⭐ W51-T11 / R4 — THE DIRTY SET, AND `edits` IS ALREADY EXACTLY IT. The changed addresses // arrive as this function's own parameter, so the PATCH body is in hand at the one place // every cell write in this module passes through: a typed cell, a paste, a fill, a range // delete and the R20 conversion. Nothing else has to be diffed against anything. for (const addr of Object.keys(edits)) markDirty(target, addr); applyLocal(withCells(base, target, edits), false); queueSave(); }, [applyLocal, ensureTabs, markDirty, queueSave]); commitCellsRef.current = commitCells; // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W50-T20 — STRUCTURE, THROUGH THE SAME DOOR AS A KEYSTROKE. // // ⛔ EVERY STRUCTURAL WRITE GOES THROUGH `commitSheets`, WHICH IS THE TICKET'S OWN WORDING and // it is not decoration: `put_workbook` bumps and CHECKS `rev` on every accepted write, so a // second writer that built its own `sheets` array and PUT directly would be refused as stale // the moment a keystroke was in flight. One history step, one `rev`, one save. That is also // what makes Ctrl+Z undo an inserted row rather than only the last cell edited. // // ⛔⛔ AND THE WALL RUNS BEFORE THE WRITE, NOT INSIDE IT. R18's insert refusal and R20's // bound-cell confirmation are asked here, where the whole workbook is in hand, because the grid // knows the selection and nothing else. // ═══════════════════════════════════════════════════════════════════════════════════════════ const commitSheets = useCallback((update: SheetTab[] | Workbook) => { const base = bookRef.current; const sheets = Array.isArray(update) ? update : update.sheets; if (!base || sheets === base.sheets) return; historyRef.current = pushHistory(historyRef.current, base.sheets, { namedRanges: base.namedRanges }); editSeqRef.current += 1; setNotice(""); // ⛔⛔ W51-T11 / C3 — STRUCTURE STAYS ON PUT, AND THIS FLAG IS THE WHOLE DIVISION. An inserted // row moves every cell below it, a deleted column moves every cell to its right, and a // renamed tab changes what every formula on every OTHER sheet resolves against. A cell PATCH // can express none of that: it names addresses, and the addresses themselves have moved. // C3 is explicit that *"`PUT` stays for structure and stays capped"*. structureDirtyRef.current = true; // Structural rewrites carry workbook names through the same history/save door as sheets. applyLocal({ ...base, ...(Array.isArray(update) ? {} : { namedRanges: update.namedRanges }), sheets }, false); queueSave(); }, [applyLocal, queueSave]); /** The tab the structure controls act on, resolved from the ref so a commit reads it live. */ const openTabId = useCallback((base: Workbook): string => base.sheets.find((t) => t.id === tabIdRef.current)?.id ?? base.sheets[0]?.id ?? "", []); const structureBase = useCallback(async (workbookId: string, target: string) => { const opening = bookRef.current; if (!opening || opening.id !== workbookId || openTabId(opening) !== target) return null; // Reanchoring reads every tab. Hydrating during the later PUT would overwrite changes // made to metadata-only tabs (including charts displayed on a sheet never opened). if (!await ensureTabs(workbookId, opening.sheets.map(sheet => sheet.id))) return null; const live = bookRef.current; return live?.id === workbookId && openTabId(live) === target ? live : null; }, [ensureTabs, openTabId]); const onStructure = useCallback(async (op: StructureOp) => { const opening = bookRef.current; if (!opening) return; const target = openTabId(opening); if (!target) return; const base = await structureBase(opening.id, target); if (!base) return; const refusal = structureRefusal(base, target, op); if (refusal) { showRefusal(refusal); return; } const bound = boundCellsInBand(base.sheets.find((t) => t.id === target), op); if (bound > 0) { setBandAt({ op, message: bandBoundLabel(bound, op.axis), workbookId: base.id, tabId: target }); return; } commitSheets(applyStructureWorkbook(base, target, op)); }, [commitSheets, openTabId, structureBase]); const confirmBand = useCallback(async () => { const pending = bandAt; setBandAt(null); if (!pending) return; const base = await structureBase(pending.workbookId, pending.tabId); if (!base) return; const refusal = structureRefusal(base, pending.tabId, pending.op); if (refusal) { showRefusal(refusal); return; } commitSheets(applyStructureWorkbook(base, pending.tabId, pending.op)); }, [bandAt, commitSheets, structureBase]); const onGrow = useCallback((dCols: number, dRows: number) => { const base = bookRef.current; if (base) commitSheets(growSheet(base, openTabId(base), dCols, dRows)); }, [commitSheets, openTabId]); const onFreeze = useCallback((patch: { cols?: number; rows?: number }) => { const base = bookRef.current; if (base) commitSheets(setFreeze(base, openTabId(base), patch)); }, [commitSheets, openTabId]); const onColumnWidth = useCallback((colIndex: number, width: number) => { const base = bookRef.current; if (base) commitSheets(setColumnWidth(base, openTabId(base), colIndex, width)); }, [commitSheets, openTabId]); /** Wave 60 base kit: the open tab's display settings, same door as `onFreeze`. */ const onTabView = useCallback((patch: Partial) => { const base = bookRef.current; if (base) commitSheets(setTabView(base, openTabId(base), patch)); }, [commitSheets, openTabId]); /** * Wave 60 base kit: hide or show a tab, same door as `onFreeze`. `setTabVisibility` refuses to * hide the last visible one; the effect beside `openTab` moves the page off a hidden open tab. */ const onTabVisibility = useCallback((target: string, visibility: "visible" | "hidden") => { const base = bookRef.current; if (base) commitSheets(setTabVisibility(base, target, visibility)); }, [commitSheets]); const onRowHeight = useCallback((height: number) => { const base = bookRef.current; if (!base) return; const target = openTabId(base); commitSheets(base.sheets.map(sheet => sheet.id === target ? { ...sheet, rowHeight: Math.max(18, Math.min(200, Math.round(height))) } : sheet)); }, [commitSheets, openTabId]); /** * ⭐ W54-T10 / LANE B — THE INSERT TAB'S CHARTS, THROUGH THE SAME DOOR EVERY OTHER TAB-LEVEL * WRITE TAKES. `charts` is a key ON the tab (never a cell), so replacing the open tab's list and * handing the result to `commitSheets` is one history step, one PUT and one `rev`, which is what * makes an inserted chart survive a reload and Ctrl+Z remove it. Same shape as `onGrow`, * `onFreeze` and `onColumnWidth` above; the only difference is that the transform is a one line * replace rather than a named helper in `sheetState.ts`, a file this lane does not own. */ const onCharts = useCallback((charts: SheetChartSpec[]) => { const base = bookRef.current; if (!base) return; const target = openTabId(base); if (!target) return; commitSheets(base.sheets.map((t) => (t.id === target ? { ...t, charts } : t))); }, [commitSheets, openTabId]); const loadChartSheet = useCallback((id: string) => { const current = bookRef.current; if (current) void ensureTabs(current.id, [id]); }, [ensureTabs]); const saveChart = useCallback(async (chart: SheetChartSpec, cells?: Record) => { const opening = bookRef.current; if (!opening) return false; const active = openTabId(opening); const sourceId = chart.source?.sheetId || active; const requested = chart.sheetId || active; const needed = [active, sourceId, ...(requested.startsWith("new:") ? [] : [requested])]; if (!await ensureTabs(opening.id, [...new Set(needed)])) return false; const base = bookRef.current; if (!base || base.id !== opening.id) return false; let sheets = base.sheets; let destination = requested; if (requested.startsWith("new:")) { const made = addTab(base); const refusal = renameTabRefusal({ ...base, sheets: made.sheets }, made.id, requested.slice(4)); if (refusal) { showRefusal(refusal); return false; } destination = made.id; sheets = made.sheets.map(t => t.id === destination ? { ...t, name: requested.slice(4) } : t); } if (!sheets.some(t => t.id === destination) || !sheets.some(t => t.id === sourceId)) { showRefusal("The chart's source or destination sheet is unavailable."); return false; } const saved = { ...chart, sheetId: destination, source: { ...chart.source, ranges: chart.source?.ranges ?? [chart.range], sheetId: sourceId } }; commitSheets(sheets.map(t => ({ ...t, ...(cells && t.id === sourceId ? { cells: { ...t.cells, ...cells } } : {}), charts: [...(t.charts ?? []).filter(c => c.id !== chart.id), ...(t.id === destination ? [saved] : [])], }))); // A newly created worksheet is complete locally until its first whole-workbook save. if (requested.startsWith("new:")) tabLoadedRef.current.add(tabKeyOf(base.id, destination)); setTabId(destination); if (cells) { await flushSave(); if (structureDirtyRef.current || dirtyRef.current.size) return false; await onRefresh(); } return true; }, [commitSheets, ensureTabs, flushSave, onRefresh, openTabId]); /** * ⭐⭐ W54-T05's HANDOVER, COMPLETED AT THE COMBINE. Lane A built colour scales, data bars and * Cell styles and could not wire them: `SheetPage.tsx` is lane E's file and carried four live * lane-E tickets, so the declaration named this edit `integration: combine-owned` rather than * reaching across a lane. * * ⛔ WITHOUT IT THE FEATURE SAVES NOTHING AND SAYS SO. `SheetGrid.tsx` reads * `const rules = (onRules ? tab.rules : localRules) ?? []`, so an unwired page falls back to a * per-session list and the sheet tells the user its rules last only as long as the tab stays * open. Both halves this depends on were already proven on the lane: the server keeps the rule * (`_clean_sheet` round-trips `kind` and `scale`) and `rules.ts::parseRange` reads the * `{col0,row0,col1,row1}` rect the server normalises a range into. * * ⭐ SAME DOOR AS `onCharts`. `rules` and the hidden bands are keys ON the tab, never cells, so * replacing the open tab and handing the result to `commitSheets` is one history step, one PUT * and one `rev` -- which is what makes a colour scale survive a reload and Ctrl+Z remove it. */ const onRules = useCallback((rules: SheetRule[]) => { const base = bookRef.current; if (!base) return; const target = openTabId(base); if (!target) return; commitSheets(base.sheets.map((t) => (t.id === target ? { ...t, rules } : t))); }, [commitSheets, openTabId]); /** * ⭐ AND `onHideBands` BESIDE IT, which lane A's declaration asked for in the same breath and for * the same reason: W51-T18 left hidden rows and columns on a session-local fallback for want of * this one wire. The patch is a partial, so a call that hides only rows must not erase the * hidden columns -- hence the two `??` guards rather than a spread of `patch`. */ const onHideBands = useCallback((patch: { hiddenRows?: number[]; hiddenCols?: number[] }) => { const base = bookRef.current; if (!base) return; const target = openTabId(base); if (!target) return; commitSheets(base.sheets.map((t) => (t.id === target ? { ...t, hiddenRows: patch.hiddenRows ?? t.hiddenRows, hiddenCols: patch.hiddenCols ?? t.hiddenCols } : t))); }, [commitSheets, openTabId]); // The index carries the server's effective role, including shares and public view access. const outlineRole = (index.workbooks.concat(index.sharedWithMe ?? []) .find(row => row.id === book?.id) as { role?: string } | undefined)?.role; const canEditOutline = !viewAsActive() && (outlineRole === "owner" || outlineRole === "editor"); const onRowGroups = useCallback((groups: SheetRowGroup[]) => { const base = bookRef.current; if (!base || !canEditOutline) return; const target = openTabId(base); if (!target) return; commitSheets(base.sheets.map(t => t.id === target ? withRowGroupsTab(t, groups) : t)); }, [canEditOutline, commitSheets, openTabId]); // ── the tab bar (wave-49 R7) ─────────────────────────────────────────────────────────────── const onAddTab = useCallback(() => { if (!canEditOutline) return; const base = bookRef.current; if (!base) return; const made = addTab(base); commitSheets(made.sheets); // A tab this page just made has no cells anywhere but here, so it is loaded by construction // and must never be fetched: a lazy read of it would 404 or answer an empty tab. tabLoadedRef.current.add(tabKeyOf(base.id, made.id)); setTabId(made.id); }, [commitSheets, canEditOutline]); const onCreatePivot = useCallback(() => { if (!canEditOutline) return; const base = bookRef.current; if (!base) return; const made = addTab(base, { kind: "pivot", pivot: { database: "", rows: [], columns: [], values: [], filters: [], } }); commitSheets(made.sheets); tabLoadedRef.current.add(tabKeyOf(base.id, made.id)); setEditAt(""); setDrillAt(""); setTabId(made.id); }, [commitSheets, canEditOutline]); const onPivotChange = useCallback((pivot: PivotSpec) => { if (!canEditOutline) return; const base = bookRef.current; if (!base) return; const target = openTabId(base); commitSheets(base.sheets.map(t => t.id === target && t.kind === "pivot" ? { ...t, pivot } : t)); }, [commitSheets, canEditOutline, openTabId]); const mutateTab = useCallback((id: string, index?: number) => { const opening = bookRef.current; if (!canEditOutline || !opening || tabWritesRef.current.has(opening.id)) return; const workbookId = opening.id; tabWritesRef.current.add(workbookId); setTabMenu(null); // The drain and tab request share one chain, so dirty cells commit before the copy. void flushSave(); saveChainRef.current = saveChainRef.current.then(async () => { const base = bookRef.current; if (!base || base.id !== workbookId || !savedCleanRef.current || workbookConflictRef.current === workbookId) return; const result = index === undefined ? await duplicateSheetTab(workbookId, id, base.rev) : await reorderSheetTab(workbookId, id, index, base.rev); const still = bookRef.current; if (!still || still.id !== workbookId) return; if (!result.ok) { if (result.status === 409) await reloadWholeWorkbookAfterConflict(workbookId); else showRefusal(result.message); return; } const saved = result.value; const beforeIds = new Set(base.sheets.map(tab => tab.id)); const existing = new Map(still.sheets.map(tab => [tab.id, tab])); const added = saved.sheets.find(tab => !beforeIds.has(tab.id)); // Preserve edits, additions and deletions made while this request was in flight. const sheets = saved.sheets.filter(tab => !beforeIds.has(tab.id) || existing.has(tab.id)) .map(tab => existing.get(tab.id) ?? tab); const returnedIds = new Set(saved.sheets.map(tab => tab.id)); sheets.push(...still.sheets.filter(tab => !returnedIds.has(tab.id))); const namedRanges = still.namedRanges === base.namedRanges ? saved.namedRanges : [...(still.namedRanges ?? []), ...(saved.namedRanges ?? []) .filter(range => added && (range.sheet === added.id || range.sheet === added.name))]; applyLocal({ ...still, rev: saved.rev, updated_at: saved.updated_at, namedRanges, sheets }); setNotice(""); if (added) { tabLoadedRef.current.add(tabKeyOf(workbookId, added.id)); setTabId(added.id); refreshOpenedWorkbook(workbookId, added.id); } }).catch(() => showRefusal("The tab change could not be saved.")) .finally(() => { tabWritesRef.current.delete(workbookId); }); }, [applyLocal, canEditOutline, flushSave, refreshOpenedWorkbook, reloadWholeWorkbookAfterConflict]); const onMoveTab = useCallback((id: string, step: number) => { const base = bookRef.current; if (!base) return; const at = base.sheets.findIndex(tab => tab.id === id); const target = Math.max(0, Math.min(base.sheets.length - 1, at + step)); if (at >= 0 && at !== target) mutateTab(id, target); }, [mutateTab]); /** Capture the whole tab, preserving the exact point inside it that the pointer grabbed. */ const startTabDrag = useCallback((id: string, event: ReactPointerEvent) => { if (!canEditOutline) return; if (event.button !== 0 || !bookRef.current || tabDragRef.current) return; const element = event.currentTarget; const rect = element.getBoundingClientRect(); const startIndex = bookRef.current.sheets.findIndex((sheet) => sheet.id === id); if (startIndex < 0) return; element.setPointerCapture(event.pointerId); element.dataset.dragging = "true"; element.setAttribute("aria-grabbed", "true"); tabDragRef.current = { workbookId: bookRef.current.id, tabId: id, pointerId: event.pointerId, element, originX: event.clientX, grabOffsetX: event.clientX - rect.left, width: rect.width, startIndex, targetIndex: startIndex, moved: false, }; }, [canEditOutline]); /** * Gesture frames write only a transform and a target index. React state would re-layout the * flex row on every pointermove; keeping siblings still gives the grabbed tab 1:1 tracking. */ const moveTabDrag = useCallback((event: ReactPointerEvent) => { const held = tabDragRef.current; if (!held || held.pointerId !== event.pointerId) return; const delta = event.clientX - held.originX; if (!held.moved && Math.abs(delta) < TAB_DRAG_SLOP_PX) return; held.moved = true; event.preventDefault(); held.element.style.setProperty("--sheet-tab-drag-x", `${delta}px`); const strip = tabStripRef.current; if (!strip) return; const draggedCenter = event.clientX - held.grabOffsetX + (held.width / 2); const peers = Array.from( strip.querySelectorAll("button[data-sheet-tab-id]"), ); held.targetIndex = peers.reduce((index, peer) => { if (peer === held.element) return index; const box = peer.getBoundingClientRect(); return draggedCenter > box.left + (box.width / 2) ? index + 1 : index; }, 0); }, []); const finishTabDrag = useCallback(( event: ReactPointerEvent, commit: boolean, ) => { const held = tabDragRef.current; if (!held || held.pointerId !== event.pointerId) return; tabDragRef.current = null; delete held.element.dataset.dragging; held.element.removeAttribute("aria-grabbed"); held.element.style.removeProperty("--sheet-tab-drag-x"); if (held.element.hasPointerCapture(held.pointerId)) { held.element.releasePointerCapture(held.pointerId); } if (!commit || !held.moved) return; suppressTabClickRef.current = held.tabId; if (suppressTabClickTimerRef.current !== null) { window.clearTimeout(suppressTabClickTimerRef.current); } // `click` normally follows this pointerup before the next task. If release happened outside // and no click arrives, do not let a stale suppression consume the person's next real click. suppressTabClickTimerRef.current = window.setTimeout(() => { if (suppressTabClickRef.current === held.tabId) suppressTabClickRef.current = ""; suppressTabClickTimerRef.current = null; }, 0); const base = bookRef.current; if (!base || base.id !== held.workbookId) return; const at = base.sheets.findIndex((sheet) => sheet.id === held.tabId); // Wave 60 base kit: `targetIndex` counts VISIBLE peers (hidden sheets have no tab), so it is // placed after that many visible peers in the full order. With nothing hidden this is the // same number it was. const others = base.sheets.filter((sheet) => sheet.id !== held.tabId); const shownOthers = others.filter((sheet) => (sheet.visibility ?? "visible") === "visible"); const peerIndex = Math.max(0, Math.min(held.targetIndex, shownOthers.length)); const target = shownOthers.length === 0 ? Math.max(0, at) : peerIndex === 0 ? others.indexOf(shownOthers[0]) : others.indexOf(shownOthers[peerIndex - 1]) + 1; if (at >= 0 && at !== target) mutateTab(held.tabId, target); }, [mutateTab]); const onRenameTab = useCallback(() => { if (!canEditOutline) { showRefusal("This workbook is read only."); return; } const pending = tabRename; const base = bookRef.current; if (!pending || !base) return; if (nameWritesRef.current.has(base.id)) { showRefusal("The name is still saving."); return; } const refusal = renameTabRefusal(base, pending.id, pending.name); if (refusal) { showRefusal(!pending.name.trim() ? "A sheet needs a name." : pending.name.includes("'") ? "A sheet name cannot contain an apostrophe." : "Another sheet already has that name."); return; } setTabRename(null); const from = base.sheets.find((t) => t.id === pending.id)?.name ?? ""; const to = pending.name.trim(); if (!from || to === from) return; // S72-T64: one undo step and the new name at once; then a name-only PATCH on the save chain. // The server moves formulas in tabs this page never loaded, so no tab is read or sent. const priorHistory = historyRef.current; const renameHistory = pushHistory(priorHistory, base.sheets, { namedRanges: base.namedRanges }); historyRef.current = renameHistory; editSeqRef.current += 1; setNotice(""); const renamedSheets = renameTab(base, pending.id, to); applyLocal({ ...base, sheets: renamedSheets }); const workbookId = base.id; nameWritesRef.current.add(workbookId); const rollback = (message: string) => { const still = bookRef.current; if (!still || still.id !== workbookId) return; if (still.sheets.find((t) => t.id === pending.id)?.name === to) { // Restore only cells this rename changed, preserving edits made while it was saving. const sheets = still.sheets.map((tab) => { const before = base.sheets.find((t) => t.id === tab.id); const optimistic = renamedSheets.find((t) => t.id === tab.id); if (!before || !optimistic) return tab; const cells = { ...tab.cells }; for (const [addr, cell] of Object.entries(optimistic.cells ?? {})) { if (cell !== before.cells?.[addr] && cells[addr] === cell) cells[addr] = before.cells[addr]; } return { ...tab, cells, name: tab.id === pending.id ? from : tab.name }; }); applyLocal({ ...still, sheets }); } if (historyRef.current === renameHistory) historyRef.current = priorHistory; showRefusal(message); }; saveChainRef.current = saveChainRef.current.then(async () => { const live = bookRef.current; if (!live || live.id !== workbookId) return; const saved = await renameTabName(workbookId, pending.id, to, live.rev); const still = bookRef.current; if (!still || still.id !== workbookId) return; if (saved.ok) { applyLocal({ ...still, rev: saved.value.rev, updated_at: saved.value.updated_at }); return; } rollback(saved.message); }).catch(() => rollback("The name could not be saved.")) .finally(() => { nameWritesRef.current.delete(workbookId); }); }, [applyLocal, tabRename, canEditOutline]); const onRemoveTab = useCallback((id: string) => { if (!canEditOutline) return; const base = bookRef.current; setTabMenu(null); if (!base) return; const refusal = removeTabRefusal(base, id); if (refusal) { showRefusal(refusal); return; } const target = base.sheets.find((t) => t.id === id); const held = tabCellCount(target); if (held > 0) { setTabDelete({ id, name: target?.name ?? "", cells: held }); return; } commitSheets(removeTab(base, id)); if (tabIdRef.current === id) setTabId(base.sheets.find((t) => t.id !== id)?.id ?? ""); }, [commitSheets, canEditOutline]); const confirmRemoveTab = useCallback(() => { const pending = tabDelete; const base = bookRef.current; setTabDelete(null); if (!pending || !base) return; commitSheets(removeTab(base, pending.id)); if (tabIdRef.current === pending.id) { setTabId(base.sheets.find((t) => t.id !== pending.id)?.id ?? ""); } }, [commitSheets, tabDelete]); /** Undo and redo save cell patches unless tab structure or named ranges changed. */ const restoreHistoryStep = useCallback((base: Workbook, step: { sheets: SheetTab[]; namedRanges?: Workbook["namedRanges"]; }) => { const outline = (tabs: SheetTab[]) => tabs.map((tab) => Object.fromEntries( Object.entries(tab).filter(([key]) => !["cells", "usedExtent", "cellCount", "rev"].includes(key)), )); const structural = JSON.stringify(outline(base.sheets)) !== JSON.stringify(outline(step.sheets)) || JSON.stringify(base.namedRanges) !== JSON.stringify(step.namedRanges); if (structural) structureDirtyRef.current = true; else for (const tab of step.sheets) { const before = base.sheets.find((held) => held.id === tab.id); if (!before || before.cells === tab.cells) continue; for (const addr of new Set([...Object.keys(before.cells), ...Object.keys(tab.cells)])) { if (JSON.stringify(before.cells[addr]) !== JSON.stringify(tab.cells[addr])) markDirty(tab.id, addr); } } editSeqRef.current += 1; setNotice(""); applyLocal({ ...base, sheets: step.sheets, namedRanges: step.namedRanges }, false); queueSave(); }, [applyLocal, markDirty, queueSave]); const onUndo = useCallback(() => { const base = bookRef.current; if (!base) return; const step = undoHistory(historyRef.current, base.sheets, { namedRanges: base.namedRanges }); if (!step) return; historyRef.current = step.history; restoreHistoryStep(base, step); }, [restoreHistoryStep]); const onRedo = useCallback(() => { const base = bookRef.current; if (!base) return; const step = redoHistory(historyRef.current, base.sheets, { namedRanges: base.namedRanges }); if (!step) return; historyRef.current = step.history; restoreHistoryStep(base, step); }, [restoreHistoryStep]); /** * Persist ONE NAMED CELL's binding AND recompute that one cell, so a save shows the number. * * ⭐⭐ W54-T35 — IT TAKES THE ADDRESS AS AN ARGUMENT NOW, AND THAT IS THE WHOLE REFACTOR. It * used to read `editAt`, which is the binding panel's own state and is empty while the drill is * open, so the drill's filter edit had no way through this door and would have had to build a * second writer: another `commitCells`, another `flushSave`, another recompute, and two places * to keep the save-then-compute ordering right. `onSaveBinding` below is now a two-line wrapper * that supplies `editAt`, so the panel's behaviour is byte-identical and there is still exactly * one writer of a cell binding on this page. * * ⚠ IT RETURNS A PROMISE THAT SETTLES WHEN THE RECOMPUTE IS DONE. The panel ignores it, as it * always has; the drill awaits it, because it has to re-read the rows AFTER the server holds the * new binding. Nothing about the panel's path changed to make that true. * * ⭐⭐ W54-T32 (owner instruction 9) — THE SHIMMER USED TO RUN UNTIL SOMEBODY PRESSED REFRESH. * Owner: *"When I Save a database cell in Sheet, it shows the loading animation but never loads * until I press Refresh."* The comment that stood here recorded W53's R10 as the reason ("a * snapshot"), and it was an accurate description of a defect: the cell was committed `stale`, * `stale` is exactly what `SheetGrid.tsx` paints the moving band for, and nothing on any path * afterwards ever resolved it. R10 says a bound cell stores its value as LAST COMPUTED; it does * not say the save must decline to compute one. * * ⛔ AND IT IS NOT A WHOLE-WORKBOOK REFRESH. `refreshWorkbook` would answer, and it is the wrong * answer: it recomputes every bound cell and every formula in the document, drops the undo * stack and the dirty set, and repaints every tab, to deliver the one number this person asked * for. `computeCell` is the one-cell door. * * ⛔⛔ `flushSave` FIRST, AND IT IS THE WHOLE ORDERING. `commitCells` queues a DEBOUNCED save, * so the binding is not on the server when this function would otherwise call for it; the * server reads the STORED cell, so it would compute the cell as it was BEFORE the edit, or * refuse `cell_missing` on a cell that has never been saved at all. * * ⚠ THE ANSWER IS DROPPED IF THE CELL MOVED WHILE THE ROUND TRIP WAS OUT. The binding object * committed below is compared by IDENTITY against what the cell now holds, so an undo, a retype * or a second binding save during those few tens of milliseconds wins over an answer that * describes a cell that no longer exists. */ const saveBindingAt = useCallback((addr: string, binding: Record, settle: "computed" | "saved" = "computed") => { // ⚠ IT GOES THROUGH `commitCells` LIKE EVERY OTHER WRITE (W50-T18). It used to build its // own `sheets` array and PUT directly, which was correct while it was the only writer; now // that a keystroke also saves, two writers each sending the `rev` they last read is exactly // the race `put_workbook` refuses. One door, one queue, one rev. if (!addr) return Promise.resolve(); const base = bookRef.current; const target = base?.sheets.find((t) => t.id === tabIdRef.current)?.id ?? base?.sheets[0]?.id ?? ""; const held = base?.sheets.find((t) => t.id === target)?.cells?.[addr]; // A newly bound cell is STALE, never fresh: nothing has been computed yet, and marking it // fresh would show an empty value wearing the mark that means "this number is current". The // recompute below is what takes it out of that state, in one round trip. commitCells({ [addr]: { ...held, kind: "bound" as const, state: "stale" as const, binding, value: null }, }); if (!base || !target) return Promise.resolve(); const wid = base.id; return (async () => { await flushSave(); const settled = bookRef.current; if (!settled || settled.id !== wid) return; // ⛔⛔ THE SAVE HAS TO HAVE LANDED BEFORE THE RECOMPUTE MAY SPEAK. If it did not, the cell // is not on the server, so the compute below would be answered `cell_missing` truthfully // and that sentence would then paint over the save path's own, which is the one that names // what actually went wrong. So this returns SILENTLY: the drain already wrote the accurate // notice, and a second sentence for one failure is worse than none. if (!savedCleanRef.current) return; const recompute = (async () => { const got = await computeCell(wid, addr, target); const live = bookRef.current; if (!live || live.id !== wid) return; if (!got.ok) { if (typeof got.rev_current === "number") applyLocal({ ...live, rev: got.rev_current }); // ⚠ A COMPUTE THAT FAILS ON ITS OWN MERITS AFTER A SAVE THAT DID LAND still speaks, and // this is the case the line was written for: an unreadable database, a scope that cannot // be compiled, a mirror still syncing. Nothing else has written a sentence about it. showRefusal(got.message); return; } applyLocal({ ...live, rev: got.value.rev || live.rev }); const held = live.sheets.find((t) => t.id === target)?.cells?.[addr]; if (!held || held.binding !== binding) return; applyLocal({ ...withCells(live, target, { [addr]: got.value.cell }), rev: got.value.rev || live.rev, }); })(); // S68-T23: View data re-drills the STORED binding, so its filter door settles once the // save has landed and the cell's own recompute finishes behind it, off the repaint path. if (settle === "computed") await recompute; })(); }, [applyLocal, commitCells, flushSave]); /** * ⭐⭐ W56-T01 / C2 + R7 - A PASTED BOUND BLOCK TAKES SAVE'S SCOPED COMPUTE PATH TOO. * The grid has already committed every landed cell through `commitWithRecalc` before this * callback runs, so the stale cells paint immediately and this remains a second, async step. * * ⛔ ONE FLUSH FOR THE BLOCK, THEN ONE COMPUTE AT A TIME. `computeCell` persists its answer and * advances the workbook revision, so parallel calls could return revisions out of order and * make the next PATCH conflict with a revision this client caused itself. `refreshWorkbook` * would avoid neither race and would recompute cells outside the pasted range. * * ⚠ THE SCHEDULED BINDING OBJECT IS THE LEASE. An undo, retype or second paste that replaces * it while a round trip is out wins; the old answer may advance the revision, but never replaces * the newer cell. */ const onEvaluateBindings = useCallback(({ tabId: target, cells }: BoundEvaluationRequest) => { const base = bookRef.current; const scheduled = Object.entries(cells); if (!base || scheduled.length === 0) return; const wid = base.id; void (async () => { await flushSave(); const settled = bookRef.current; if (!settled || settled.id !== wid || !savedCleanRef.current) return; let spoke = false; for (const [addr, cell] of scheduled) { if (cell.kind !== "bound" || !cell.binding) continue; const before = bookRef.current; if (!before || before.id !== wid) return; const heldBefore = before.sheets.find((tab) => tab.id === target)?.cells?.[addr]; if (!heldBefore || heldBefore.binding !== cell.binding) continue; const got = await computeCell(wid, addr, target); const live = bookRef.current; if (!live || live.id !== wid) return; if (!got.ok) { if (typeof got.rev_current === "number") applyLocal({ ...live, rev: got.rev_current }); if (!spoke) { showRefusal(got.message); spoke = true; } continue; } const rev = got.value.rev || live.rev; const held = live.sheets.find((tab) => tab.id === target)?.cells?.[addr]; if (!held || held.binding !== cell.binding) { // ⛔ THE REVISION STILL LANDS WHEN THE CELL ANSWER DOES NOT. The server persisted the // compute before the local identity changed, so dropping its rev would manufacture the // next save conflict even though the newer cell correctly wins the screen. applyLocal({ ...live, rev }); continue; } applyLocal({ ...withCells(live, target, { [addr]: got.value.cell }), rev, }); } })(); }, [applyLocal, flushSave]); /** The binding panel's Save. It names the cell the panel is editing, and nothing else. */ const onSaveBinding = useCallback((binding: Record) => { const addr = editAt; if (!addr) return; // S67-T04: a panel opened on another tab never saves here (the close above normally wins). if (panelTabRef.current && panelTabRef.current !== tabIdRef.current) { setEditAt(""); return; } setEditAt(""); void saveBindingAt(addr, binding); }, [editAt, saveBindingAt]); /** * ⭐⭐ W54-T35 (owner instruction 8, ruling R8) — A FILTER CHANGED INSIDE THE DRILL. * * Owner: *"they should be able to change the filter there too."* The only thing that changes is * `scope.filter`; everything else the binding says about the cell (its database, its aggregate, * its period, its drag behaviour) is carried over verbatim, because the reader edited a filter * and not a cell. * * ⛔ `scope` IS SPREAD RATHER THAN REBUILT, WHICH IS WHAT KEEPS R11's `adoptedFrom` ALIVE. A * filter adopted from a purged view carries that provenance in its scope and the binding panel * is careful to re-save it; a scope rebuilt here as `{ filter }` would erase it, and the * sentence in the panel that explains where the filter came from would silently disappear the * first time somebody edited the filter from the drill. * * ⛔ AND A VIEW-BOUND CELL IS REFUSED HERE AS WELL AS IN THE DRILL. R8: a saved view already * fixes the rows. The drill offers no editor for one, and this is the second half of that rule, * so a caller reaching the handler another way cannot fork a cell off its view. */ const onDrillFilterChange = useCallback((addr: string, tree: FilterTree) => { const base = bookRef.current; const target = base?.sheets.find((t) => t.id === tabIdRef.current) ?? base?.sheets[0] ?? null; const held = target?.cells?.[addr]; const binding = held?.binding as Record | undefined; if (!binding) return Promise.resolve(); const scope = (binding.scope ?? {}) as Record; if (typeof scope.view_id === "string" && scope.view_id.trim()) return Promise.resolve(); return saveBindingAt(addr, { ...binding, scope: { ...scope, filter: tree } }, "saved"); }, [saveBindingAt]); // W60-T11 / C4: display belongs to this cell, including when its rows come from a saved View. // No view_id guard here: withBindingDisplay preserves scope and never writes the shared View. const onDrillDisplayChange = useCallback((addr: string, display: BindingDisplay) => { const base = bookRef.current; const target = base?.sheets.find((t) => t.id === tabIdRef.current) ?? base?.sheets[0] ?? null; const held = target?.cells?.[addr]; const binding = held?.binding as Record | undefined; if (!binding) return Promise.resolve(); return saveBindingAt(addr, withBindingDisplay(binding, display)); }, [saveBindingAt]); // ⭐ R17 is enforced BEFORE the popup opens, not inside it. `drillAffordance` already disables // the control for a formula or a literal and names the reason; this guard is the second half of // the same rule, so a keyboard path that reaches the handler cannot open a popup the button // refuses. Two doors, one rule. const onViewRows = useCallback((addr: string, cell: Cell | null) => { const affordance = drillAffordance(cell); if (!affordance.enabled) { showRefusal(affordance.reason); return; } setNotice(""); // ⭐ W54-T34: the busy state goes on in the SAME act as the open, so the control changes in the // same frame the surface appears. `DrillModal` takes it off again through `onSettled`. setDrillLoading(true); panelTabRef.current = tabIdRef.current; setDrillAt(addr); }, []); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐ THE RAIL'S DOORS (W50-T17). Every one of them is composed from the workbook routes that // already exist plus the ONE new index door, which is why this ticket adds no per-action // route: `sheets.py` gained folders and stars, not five verbs. // // ⛔ `opening` IS A SECOND FLAG AND NOT `loading` REUSED. `loading` is the FIRST paint, when // the rail has nothing to draw and the skeleton is honest. Switching workbooks later leaves // the rail's own contents unchanged, so replacing it with a skeleton would blank a list the // reader is still using; only the main area waits. // ═══════════════════════════════════════════════════════════════════════════════════════════ const refreshIndex = useCallback(async () => { const got = await readIndex(); if (got.ok) setIndex(got.value); setNotice(got.ok ? "" : got.message); if (!got.ok) readRetry.current = () => void refreshIndex(); }, []); /** * @param held `"all"` when the workbook arrived complete (a full read, a create, a duplicate); * `"meta"` when only its tab LIST arrived and the cells have still to be fetched. * * ⛔ GETTING THIS ARGUMENT WRONG IS THE DATA-LOSS BUG. Calling it `"all"` over a meta read * tells the PUT fallback that empty tabs are the truth, and the next save writes that. */ const adoptWorkbook = useCallback(( next: Workbook, held: "all" | "meta", address?: SheetAddress, ) => { // A different workbook is a different tree, so the undo stack is dropped rather than left // pointing at cells that no longer hold the values it recorded. historyRef.current = emptyHistory(); editSeqRef.current += 1; // The dirty set names addresses in the workbook being left. It does not travel. dirtyRef.current = new Map(); structureDirtyRef.current = false; // ⛔ THE ONE LINER IS LOAD BEARING. `verify_wiring`'s W51-T11 row asserts the literal // `if (held === "all") markAllLoaded(next);`, so wrapping it in braces to gain an `else` // makes that row red about a rule this code still obeys. The `else` hangs off it instead. if (held === "all") markAllLoaded(next); else { // A meta read deliberately replaces these tabs with empty cell maps, so their loaded memo // must be replaced too. We do not preserve cells in a second client-side workbook cache: // the meta response is the authoritative tab list, and reconciling an old tree and revision // would create another source of workbook truth. `ensureTabs` now fetches only the open tab. for (const tab of next.sheets) { tabLoadedRef.current.delete(tabKeyOf(next.id, tab.id)); } } const firstTab = prepareWorkbookOpen(next, address); applyLocal(next); setTabId(firstTab); return firstTab; }, [applyLocal, markAllLoaded, prepareWorkbookOpen]); // C2: a rail choice and browser Back enter the same serialized open path below. const openWorkbook = useCallback((id: string) => { if (!addressMountedRef.current) return; navigateSheetAddress({ wb: id }); }, [navigateSheetAddress]); useEffect(() => { const address = readSheetAddress(sheetHash); if (!address || handledSheetHashRef.current === sheetHash || workbookTransitionRef.current || opening) return; // The bare route retains its existing mount behavior; the gallery belongs to lane E. if (addressInitializedRef.current && address.wb === null) return; handledSheetHashRef.current = sheetHash; const initial = !addressInitializedRef.current; const current = () => addressMountedRef.current && currentSheetHash() === sheetHash; workbookTransitionRef.current = true; // A new address must see the real refusals, not an abandoned pass's pending marks. openRefreshRef.current?.restore(); openRefreshRef.current = null; setOpening(true); setNotice(""); void (async () => { try { // Keep the old workbook's dirty tree and revision until its final save has settled. if (!initial && !await flushBeforeWorkbookChange()) { if (current() && acceptedAddressRef.current) { const accepted = acceptedAddressRef.current; handledSheetHashRef.current = sheetAddressHash(accepted); navigateSheetAddress(accepted, "replace"); } return; } if (!current()) return; rememberOpenWorkbook(); let targetId = address.wb; if (initial) { // W61-T17: staging took 8,064 ms to the grid; 5,857 ms was a directory the address // did not need. Only a bare address waits for the index to choose a workbook. if (address.wb === null) { // One index read supplies the rail; its server-side access filter stays authoritative. const got = await readIndex(); if (addressMountedRef.current && got.ok) { setIndex(got.value); addressInitializedRef.current = true; } if (!current()) return; if (!got.ok) { setNotice(got.message); readRetry.current = retryOpeningRead; return; } // An explicit id never falls through, including when access filtering omitted its row. if (targetId === null) { targetId = (got.value.workbooks.find((row) => row.id === lastWorkbookId) ?? got.value.workbooks[0])?.id ?? null; } } else { void readIndex().then((got) => { if (addressMountedRef.current) { if (got.ok) setIndex(got.value); else { setNotice(got.message); readRetry.current = () => void refreshIndex(); } } }); addressInitializedRef.current = true; } } const alreadyOpen = targetId !== null && targetId === bookRef.current?.id; let activeTab: string; if (alreadyOpen) { const live = bookRef.current!; if (!address.tab && !address.cell) { acceptedAddressRef.current = address; return; } // A cell-only link narrows the current tab; unknown tabs quietly keep that tab. const tab = live.sheets.find((t) => t.id === address.tab && (t.visibility ?? "visible") === "visible"); activeTab = prepareWorkbookOpen( live, { ...address, tab: tab?.id ?? tabIdRef.current }, barAddr, ); setTabId(activeTab); } else { // The opening response carries metadata and one tab at the same stored revision. const got = targetId !== null ? await readWorkbookOpening(targetId, address.tab) : await createWorkbook("Default workbook"); if (!current()) return; if (!got.ok && targetId !== null && discardMissingWorkbook(targetId, got)) { return; } if (!got.ok || !got.value || (targetId !== null && got.value.id !== targetId)) { // A refused address has no substitute workbook behind its notice. bookRef.current = null; setBook(null); setTabId(""); setEditAt(""); setDrillAt(""); setNotice(got.ok ? "That sheet could not be read, so it is not shown." : got.message); readRetry.current = retryOpeningRead; return; } const { openingTab, ...openedWorkbook } = got.value as WorkbookOpening; activeTab = adoptWorkbook(openedWorkbook, targetId === null ? "all" : "meta", address); if (openingTab?.id === activeTab) mergeTab(openedWorkbook.id, openingTab); if (targetId === null) await refreshIndex(); } if (!current()) return; const opened = bookRef.current!; if (activeTab) { const narrowed = activeTab === address.tab; const loaded = await ensureTabs(opened.id, [activeTab], narrowed); if (!current()) return; if (!bookRef.current) return; if (!loaded && narrowed) { // An unreadable tab is only a failed narrowing inside this readable workbook. const fallback = opened.sheets.find((t) => t.id !== activeTab && (t.visibility ?? "visible") === "visible"); if (fallback) { activeTab = prepareWorkbookOpen(bookRef.current!, { wb: opened.id, tab: fallback.id }); setTabId(activeTab); if (!await ensureTabs(opened.id, [activeTab]) && current()) setUnreadableAddressTab(activeTab); } else setUnreadableAddressTab(activeTab); } } if (!current()) return; // SheetGrid applies openAt once per mount. A new address can select another cell in // the same tab, while ordinary saves and background refreshes keep the existing mount. setAddressSelectionKey((key) => key + 1); acceptedAddressRef.current = { ...address, wb: opened.id }; } finally { workbookTransitionRef.current = false; if (addressMountedRef.current) { // Retry the latest hash after this request settles, even if Back arrived mid-read. setLoading(false); setOpening(false); } } })(); }, [sheetHash, opening, barAddr, adoptWorkbook, ensureTabs, flushBeforeWorkbookChange, lastWorkbookId, prepareWorkbookOpen, refreshIndex, discardMissingWorkbook, rememberOpenWorkbook, currentSheetHash, navigateSheetAddress, mergeTab, readAttempt]); // The workbook can open before its index arrives. Enrich only after the open has settled, // so changing the hash cannot invalidate an in-flight workbook read's address guard. useEffect(() => { if (embedded || opening || workbookTransitionRef.current || index.rev === undefined || !book || readSheetAddress(sheetHash)?.wb !== book.id || window.location.hash !== sheetHash) return; const next = reattachSheetFolder(readSheetFolder(sheetHash) ?? index.itemFolders[book.id]); folderHashRef.current = next; if (next === sheetHash) return; if (handledSheetHashRef.current === sheetHash) handledSheetHashRef.current = next; setSheetHash(next); }, [book, embedded, index, opening, sheetHash]); /** R2's create door: made and OPENED in one act, with no name step in between. */ const createAndOpen = useCallback(async () => { if (workbookTransitionRef.current) return; workbookTransitionRef.current = true; const originHash = currentSheetHash(); setOpening(true); setNotice(""); if (!await flushBeforeWorkbookChange()) { setOpening(false); return; } const made = await createWorkbook("Untitled workbook"); if (!made.ok) { showRefusal(made.message); workbookTransitionRef.current = false; setOpening(false); return; } adoptWorkbook(made.value, "all"); if (addressMountedRef.current && currentSheetHash() === originHash) { acceptedAddressRef.current = { wb: made.value.id }; navigateSheetAddress(acceptedAddressRef.current); } await refreshIndex(); workbookTransitionRef.current = false; setOpening(false); }, [adoptWorkbook, currentSheetHash, flushBeforeWorkbookChange, navigateSheetAddress, refreshIndex]); /** * ⭐ DUPLICATE IS COMPOSED, NOT ROUTED. Read the source, create an empty workbook, then write * the source's sheets into it with the NEW workbook's own `rev`. Sending the source's rev * would be refused as stale against a document that has only ever been at rev 1. */ const duplicateWorkbook = useCallback(async (id: string) => { if (workbookTransitionRef.current) return; workbookTransitionRef.current = true; const originHash = currentSheetHash(); setOpening(true); setNotice(""); if (!await flushBeforeWorkbookChange()) { setOpening(false); return; } const source = await readWorkbook(id); if (!source.ok) { showRefusal(source.message); workbookTransitionRef.current = false; setOpening(false); return; } const made = await createWorkbook(`${source.value.name} copy`); if (!made.ok) { showRefusal(made.message); workbookTransitionRef.current = false; setOpening(false); return; } const filled = await writeWorkbook(made.value.id, { name: made.value.name, sheets: source.value.sheets, rev: made.value.rev, }); if (!filled.ok) { showRefusal(filled.message); workbookTransitionRef.current = false; setOpening(false); return; } adoptWorkbook(filled.value, "all"); if (addressMountedRef.current && currentSheetHash() === originHash) { acceptedAddressRef.current = { wb: filled.value.id }; navigateSheetAddress(acceptedAddressRef.current); } await refreshIndex(); workbookTransitionRef.current = false; setOpening(false); }, [adoptWorkbook, currentSheetHash, flushBeforeWorkbookChange, navigateSheetAddress, refreshIndex]); /** * S72-T64: the new name shows at once in the rail and the book, then a name-only PATCH saves it. * ⛔ The request carries the name and the revision, never the sheets. * ⛔ The rail never reads the name back: the answer updates the row, and `railNames` keeps an * older index read from painting the old name. * The open workbook's write rides the save chain, so it reads the revision the last save left. */ const renameWorkbook = useCallback(async (id: string, name: string) => { if (workbookTransitionRef.current) return; if (nameWritesRef.current.has(id)) { showRefusal("The name is still saving."); return; } setNotice(""); name = name.trim(); const open = bookRef.current?.id === id ? bookRef.current : null; const rows = railIndexRef.current.workbooks.concat(railIndexRef.current.sharedWithMe ?? []); const row = rows.find((row) => row.id === id); const before = open?.name ?? row?.name ?? ""; if (!name) { showRefusal("A workbook needs a name."); return; } if (name === before) return; nameWritesRef.current.add(id); setRailNames((held) => ({ ...held, [id]: { name, rev: Number.POSITIVE_INFINITY } })); if (open) { editSeqRef.current += 1; applyLocal({ ...open, name }); } const refuse = (message: string) => { setRailNames((held) => { if (held[id]?.name !== name) return held; return { ...held, [id]: { name: before, rev: open?.rev ?? row?.rev ?? 0 } }; }); const still = bookRef.current; if (still?.id === id && still.name === name) applyLocal({ ...still, name: before }); showRefusal(message); }; const send = async (): Promise => { let rev = bookRef.current?.id === id ? bookRef.current.rev : row?.rev; if (rev === undefined) { const meta = await readTabMeta(id); if (!meta.ok) { refuse(meta.message); return; } rev = meta.value.rev; } const saved = await renameWorkbookName(id, name, rev); if (!saved.ok) { refuse(saved.message); return; } const landed = saved.value; setRailNames((held) => (held[id]?.name === name ? { ...held, [id]: { name, rev: landed.rev } } : held)); const patchRows = (list: SheetIndex["workbooks"]) => list.map((row) => ( row.id === id && row.rev <= landed.rev ? { ...row, name: landed.name, rev: landed.rev, updated_at: landed.updated_at ?? row.updated_at } : row)); setIndex((current) => ({ ...current, workbooks: patchRows(current.workbooks), ...(current.sharedWithMe ? { sharedWithMe: patchRows(current.sharedWithMe) } : {}), })); const still = bookRef.current; if (still?.id === id) applyLocal({ ...still, name: landed.name, rev: landed.rev, updated_at: landed.updated_at }); }; try { if (!open) { await send(); return; } const queued = saveChainRef.current.then(send).catch(() => refuse("The name could not be saved.")); saveChainRef.current = queued; await queued; } catch { refuse("The name could not be saved."); } finally { nameWritesRef.current.delete(id); } }, [applyLocal]); const removeWorkbook = useCallback(async (id: string) => { if (workbookTransitionRef.current) return; setNotice(""); const gone = await deleteWorkbook(id); if (!gone.ok && !isMissingItem("workbook", gone)) { showRefusal(gone.message); return; } itemDeleted({ kind: "workbook", id }); const rows = await readIndex(); if (rows.ok) setIndex(rows.value); if (bookRef.current?.id !== id) return; const next = rows.ok ? rows.value.workbooks[0] : undefined; if (!next) { bookRef.current = null; setBook(null); setNotice(""); return; } await openWorkbook(next.id); }, [openWorkbook]); /** Retain the revision read by the rail until a write or fresh read replaces it. */ const indexRev = index.rev; /** * The ONE door for every folder, placement and star change. * * ⭐ OPTIMISTIC, THEN CORRECTED BY THE SERVER'S ANSWER, and the correction is the point: the * server REPAIRS a placement or a parent naming a folder that is gone, and adopting its reply * wholesale is what puts the rail back in step with what was actually stored. A refusal (a * cycle, an over deep chain) re-reads instead, so the rail never keeps a tree the store refused. */ const saveStrata = useCallback(async (next: RailStrata) => { const previousIndex = index; const placements = placementOnlyDelta(index, next); setNotice(""); setIndex((prev) => ({ ...prev, folders: next.folders, itemFolders: next.itemFolders, starred: next.starred, })); /** * ⭐⭐ W51-T10 — THE REVISION RIDES ALONG WHEN THERE IS ONE, AND IS OMITTED WHEN THERE IS NOT. * * The index PUT is wholesale and carries no `rev` today (D-639), so two people filing at once * overwrite each other in silence. W51-T25 stamps one; this is the ONE place a star, a move, * a rename and a folder change all pass through, so forwarding it here covers every strata * write at once. ⛔ `rev: undefined` is NOT the same as no key: it would serialise as an * absent field on some paths and as a null on others, and the server's guard would then have * to read two spellings of "I did not send one". */ let timeout: ReturnType | undefined; const timeoutError = new Error("The folder move timed out. Your items were put back."); try { const saved = await Promise.race([ placements ? writePlacements(placements) : writeIndex({ ...next, ...(indexRev === undefined ? {} : { rev: indexRev }), createdFolderIds: createdFolderIds(index, next) }), new Promise((_, reject) => { timeout = setTimeout(() => reject(timeoutError), FOLDER_WRITE_TIMEOUT_MS); }), ]); if (!saved.ok) { setIndex(previousIndex); showRefusal(saved.message); clearTimeout(timeout); const rows = await Promise.race([ readIndex(), new Promise((_, reject) => { timeout = setTimeout(() => reject(timeoutError), FOLDER_WRITE_TIMEOUT_MS); }), ]); if (rows.ok) setIndex(rows.value); return; } setIndex(saved.value); const sentence = repairSentence(saved.value.repairs); if (sentence) showRefusal(sentence); } catch (error) { setIndex(previousIndex); showRefusal(error instanceof Error ? error.message : "Folders could not be saved. Reload folders to retry."); } finally { clearTimeout(timeout); } }, [index, indexRev]); // The page owns both the rail launcher and the retained dock seat. const [chatOpen, setChatOpen] = useState(false); const toggleChat = useCallback(() => setChatOpen((open) => !open), []); const closeChat = useCallback(() => setChatOpen(false), []); // Fresh bindings take precedence over resolved source metadata on bound cells. const boundDatabases = useMemo(() => { const seen: string[] = []; for (const sheet of book?.sheets ?? []) { for (const cell of Object.values(sheet.cells ?? {})) { if (cell?.kind !== "bound") continue; const bound = (cell?.binding as { database?: unknown } | undefined)?.database; const source = cell.source?.database; const key = (typeof bound === "string" ? bound.trim() : "") || (typeof source === "string" ? source.trim() : ""); if (key && !seen.includes(key)) seen.push(key); } } return seen; }, [book]); const selectedTab = book?.sheets.find((t) => t.id === tabId) ?? book?.sheets[0] ?? null; const tab = selectedTab?.id === unreadableAddressTab ? null : selectedTab; const tabReadError = selectedTab?.id === unreadableAddressTab ? notice || "That sheet could not be read, so it is not shown." : ""; const tabPending = pendingTab !== null && pendingTab.workbookId === book?.id && pendingTab.tabId === tabId; const requestedWorkbookId = readSheetAddress(sheetHash)?.wb; const addressMismatch = book !== null && requestedWorkbookId != null && requestedWorkbookId !== book.id; /** * ⭐⭐ W54-T35 — WHICH ROWS THE DRILLED CELL ASKED FOR, read off the LOCAL workbook. * * ⚠ THE LOCAL COPY RATHER THAN THE DRILL ANSWER, AND THE DIFFERENCE IS THE POINT. The answer * describes what the server used for the rows on screen; this describes what the cell holds * now, so the sentence in the drill moves the instant an edit is committed here and does not * wait on a round trip to say what the reader just did. * * ⚠ NOT MEMOISED, ON PURPOSE. `DrillModal` depends on the KIND and on the tree's identity, not * on this object's, precisely so that a page re-rendering for an unrelated reason cannot churn * the drill's callbacks. The tree itself is the one held on the binding, so its identity is * stable until the cell is rewritten. */ const drillBinding = (drillAt ? tab?.cells?.[drillAt]?.binding : null) as Record | null | undefined; const drillBindingScope = (drillBinding?.scope ?? null) as Record | null; const drillViewId = typeof drillBindingScope?.view_id === "string" ? drillBindingScope.view_id.trim() : ""; const drillAggregate = drillBinding?.aggregate as Record | undefined; const drillAggregateField = typeof drillAggregate?.field === "string" ? drillAggregate.field.trim() : ""; const drillStep = bindingOnDrag(drillBinding).down; // W60-T11: reopen from this cell's saved display through the existing scope seam. const drillDisplay = bindingDisplay(drillBinding); const drillScope: DrillCellScope | null = !drillBindingScope ? null : drillViewId ? { kind: "view", name: typeof drillBindingScope.view_name === "string" ? drillBindingScope.view_name : "", ...(drillDisplay ? { display: drillDisplay } : {}), ...(drillAggregateField ? { aggregateField: drillAggregateField } : {}), ...(drillStep !== "none" ? { stepField: drillStep.field } : {}), } : { kind: "filter", tree: (drillBindingScope.filter as FilterTree | null | undefined) ?? { conj: "and", nodes: [] }, ...(drillDisplay ? { display: drillDisplay } : {}), ...(drillAggregateField ? { aggregateField: drillAggregateField } : {}), ...(drillStep !== "none" ? { stepField: drillStep.field } : {}), }; // The shell owns the gallery. Leave no workbook controls mounted during its route handover. if (!embedded && readSheetAddress(sheetHash)?.wb === null) return null; if (embedded && !loading && !opening && !book && notice) { return

{notice}{" "}

; } return ( // ⛔ `data-view-kind` STAYS IN THIS FILE. `verify_wiring.py`'s W49-W1 row asserts // `data-view-kind={SHEET_VIEW_KIND}` inside `sheet/SheetPage.tsx` by path, so moving the rail // out without moving this attribute up would have turned a green wiring row red for a reason // that has nothing to do with what it guards. R2's one view kind is a property of the PAGE. // ⭐ W54-T34: `data-drill` is the ONE hook the stylesheet needs to reach a button in a file // this ticket does not own. The action bar is a plain descendant of this element (it is not // portalled), so `.sheet-page[data-drill="loading"] .sheet-action-bar .sheet-action` matches.
{/* ⭐⭐ W51-T09 (R12) — THE DOCK, SEATED BETWEEN THE RAIL AND THE BODY, which is where the Data module seats its own ("docked to the RIGHT of the secondary navigation"). It is mounted in the same change as its launcher, deliberately: a panel whose only entry point is a prop nobody flips is mounted-but-never-offered, which is the defect this repo has shipped more often than any other. `verify_wiring.py` asserts both halves. The shared seat retains the panel until its width transition completes. */} {/* ⛔⛔ THE LOADING BODY IS ITS OWN BRANCH AND CARRIES NO SENTENCE. The owner named the defect: "the 'opening your workbook' loading screen must be the Data module's loading animation". A line of prose where the rest of the app shows a spinner is the thing being removed, so the sentence has no place in this branch at all; the REFUSAL sentence lives one branch down, where `loading` is over and nothing opened. */} {loading ? (
) : (
{/* ⭐⭐ W51-T08 (owner instructions 8 and 10) — THERE IS NO PAGE TOOLBAR AND NO TITLE HERE, AND THAT IS THE RULE, NOT AN OMISSION. Exactly ONE ribbon sits above exactly ONE formula bar above the canvas; a `.sheet-toolbar` row holding an `

` and a second Refresh button would be a THIRD band of chrome, and the workbook's name is already the selected row in the rail beside it. Refresh did not disappear, it MOVED: R8 puts it on the ribbon's own row, handed down as `onRefresh` (C1) rather than drawn here, because a sheet is a snapshot and the one act that changes every number on screen is a page-level act. ⭐⭐ W57-T15 (owner instructions 6 and 12) — AND THE NOTICE NO LONGER SITS HERE EITHER. It used to render at the top of this column, so every refusal pushed the ribbon and the whole grid down under the reader's cursor. It now renders just above the tab strip; see `.sheet-tab-notices` below. ⭐⭐ W53-T08 — THE `.sheet-status` LINE THAT SAT HERE IS DELETED (instruction 14). Its hook class went with it. ⚠ `verify_wiring.py:4124` still asserts that line's JSX is present in this file and has therefore been RED since W53-T08 landed; the gate is what is stale, not the code. */} {/* ⭐ THREE OUTCOMES, IN THE ORDER THEY CAN HAPPEN. A workbook is switching, so the grid skeleton; a workbook is open, so the grid; nothing opened and `loading` is over, so the reason IS said, as a plain sentence naming its subject (R16). The last branch is why `notice` is not enough on its own: it is a sentence about a REFUSAL, never a stand-in for a loading state. */} {opening || addressMismatch || tabPending ? ( ) : book && tab ? ( tab.kind === "pivot" ? : { if (!sel) return; setBarAddr(sel.addr); if (sel.readerCaused) rememberLastCell(sel.addr); }} onStructure={onStructure} onGrow={onGrow} onFreeze={onFreeze} onColumnWidth={onColumnWidth} onTabView={onTabView} onTabVisibility={onTabVisibility} onRowHeight={onRowHeight} // ⭐ W54-T10 / lane B — the Insert tab's chart door. It sits AFTER // `onCommit={commitCells}` on purpose: `verify_wiring`'s W50-T17 row scans forward // from ``; the slot below closes a self-closing element, so putting it // earlier in this list would red a row this ticket does not own. // // ⛔ `formulaBar` IS A NODE, NOT A FLAG. The bar carries the page's own commit door and // its address state, so building it here and handing E a rendered node is what keeps // ONE formula bar in the app; a boolean would have made E build a second one. formulaBar={ { openAtRef.current = { workbookId: book.id, tabId: tab.id, addr }; setBarAddr(addr); setCellAddressRequest((request) => request + 1); }} onCommit={commitCells} draft={cellDraft} />} onSaveNow={onSaveNow} onOpenImport={onOpenImport} /> ) : (

{tabReadError ? tabReadError : notice ? notice : "No workbook is open. Use Create new in the rail to start one."}

{notice || tabReadError ? : null}
)} {book && notice && !tabReadError ?

{notice}{" "}

: null} {book && Object.keys(cellSaveState.failures).length > 0 &&
{Object.entries(cellSaveState.failures).map(([id, failure]) => { const edit = cellSaveState.pending.find((entry) => entry.id === id); const patch = edit?.payload as SheetCellEdit | undefined; if (!patch) return null; return Object.entries(failure.cells ?? Object.fromEntries(Object.keys(patch.cells) .map((addr) => [addr, failure.message]))).map(([addr, reason]) => (
{book.sheets.find((sheet) => sheet.id === patch.tabId)?.name ?? patch.tabId}!{addr}: {reason}
)); })}
} {/* ⭐⭐ THE TAB BAR (wave-49 R7), AND IT SITS AT THE BOTTOM OF THE WORKBOOK. R7 says one rail entry is a WORKBOOK WITH TABS, so the tabs belong INSIDE the workbook and never on the rail, which lists workbooks. The bottom is also Excel's own place for them and it is the one edge of this column that no other control is competing for. ⛔⛔ `flex: 0 0 auto` COMES WITH `.sheet-ribbon` AND IT IS THE WHOLE SAFETY ARGUMENT. `.sheet-body` is a flex COLUMN whose grid child is `flex: 1 1 auto; min-height: 0`, and glide renders NO CANVAS AT ALL at a measured height of zero rather than a clipped one. A tab bar that shrank the grid would read as "the Sheet broke again", so it takes its content height and nothing more, exactly as `.sheet-fx` above it does. */} {book && (
{/* Wave 60 base kit: a hidden or very hidden sheet has no tab. */} {book.sheets.filter((t) => (t.visibility ?? "visible") === "visible").map((t) => ( ))}
{ const opened = bookRef.current; if (!opened || opened.id !== book.id || opened.rev !== revision) throw new Error("The workbook changed. Reopen checks and try again."); await flushSave(); if (!savedCleanRef.current || bookRef.current?.id !== book.id) throw new Error("Save the workbook before saving checks."); const pending = saveChainRef.current.then(async () => { const current = bookRef.current; if (!current || current.id !== book.id) throw new Error("The workbook changed."); const result = await writeWorkbookChecks(current.id, current.rev, checks); if (!result.ok) throw new Error(result.message); const live = bookRef.current; if (live?.id === current.id) { const next = { ...live, rev: result.value.rev, checks: result.value.checks } as import("./sheetApi").CheckedWorkbook; delete next.checkResults; if (!next.checks?.length) delete next.checks; applyLocal(next); } return result.value; }); saveChainRef.current = pending.then(() => {}, () => {}); return pending; }} /> { await flushSave(); if (savedCleanRef.current && bookRef.current?.id === book.id) await onRefresh(undefined, id); }} />
)}

)} {/* The tab's own acts. Same overlay vocabulary as the grid's right-click menu. */} {tabMenu && book && ( setTabMenu(null)} >
)} {/* ⚠ THE CARD CLASSES ARE `sheet-drill-error`'s, FOR THE REASON THE CONVERSION CARD BELOW already states: both sheet stylesheets are outside this ticket's fence, so this reuses the one already styled fixed card rather than shipping an unstyled panel or a literal z-index. The class name says error and none of these three are one. */} {tabRename && (

Rename this sheet

)} {/* ⛔⛔ W51-T10 / R6 — THE SAME DIALOG THE RAIL'S WORKBOOK DELETE OPENS. R6: one `ConfirmDialog` for every destructive act, workbook and tab deletes named in as many words. The panel this replaced was a positioned div with neither a focus trap nor an Escape key, and its Delete button wore the same `.sheet-refresh` chrome as its Cancel. ⚠ WHEN IT OPENS IS UNCHANGED, AND DELIBERATELY SO. `onRemoveTab` still asks only when the sheet HOLDS something (wave-50 R18: what a bound cell loses is a QUERY, not a number somebody can type back in); an empty sheet still goes on one click. R6 governs the SHAPE of the promise, not which acts earn one, and adding friction to an empty sheet is a product decision this ticket was not given. */} setTabDelete(null)} /> {/* ⛔ R18's SECOND HALF, AND THE TICKET NAMES IT: a delete that would drop a BOUND cell asks first. A bound cell is the one kind that cannot be typed back in from memory, because what is lost is a QUERY and not a number. */} {bandAt && (

Delete this {bandAt.op.axis === "row" ? "row" : "column"}?

{bandAt.message}

)} {book && editAt && (!panelTabRef.current || panelTabRef.current === tabId) && ( /* * ⛔⛔ `key={editAt}` REMOUNTS THE PANEL, AND WITHOUT IT THE SECOND CELL SHOWS THE FIRST * CELL'S PERIOD. `BindingEditor` seeds its period, lock and drag state from `initial` * through `useState(() => ...)`, which runs ONCE per mount; reconciling D9 -> E10 keeps * the old state and the panel then describes a cell it is not editing. * * ⚠ W51-T12 is what made this reachable. While the panel was a `position: fixed` sheet * over the canvas there was no way to click a second bound cell without closing it first, * so the missing key cost nothing. The panel is a COLUMN now and the grid beside it stays * clickable, which turns 'edit another cell' into an ordinary gesture. */ ) ?? null} onSave={onSaveBinding} onCancel={() => setEditAt("")} workbook={book} homeTab={tab ? { id: tab.id, name: tab.name } : undefined} readCell={(text) => { // The same reader the drag and resolve paths use, so the panel shows what a refresh // would read. A bare reference is about the tab the edited cell is on. // HOTFIX 2026-09-29: a slot may hold a FORMULA (`=DATE($E$24,1,1)`), read on this tab. if (text.trim().startsWith("=")) { const got = readFormulaSlot(book, text.trim(), tab); return { value: got.value, problem: got.problem ?? "", formula: text.trim() }; } const ref = parseRef(text); if (!ref) return null; let value = "", problem = ""; try { value = resolveFilterCell(book, text, tab?.name); } catch (error) { problem = error instanceof Error ? error.message : String(error); } const home = ref.sheet ? book.sheets.find((s) => s.name === ref.sheet) : tab; const cell = home?.cells?.[`${ref.col.toUpperCase()}${ref.row}`]; return { value, problem, formula: cell?.kind === "formula" ? String(cell.formula ?? "") : "" }; }} /> )} {/* ⛔⛔ R5 (W52-T09) RETIRED R20's CONFIRMATION DIALOG, WHICH ONCE STOOD HERE. Typing over a BOUND cell no longer asks first: `SheetGrid.tsx::onKeyDown` commits it directly through the same floating editor a fresh formula opens, dropping the binding on commit. This is also instruction 27's fix - the dialog never called `.focus()` back onto the grid canvas when it closed, so an arrow key afterwards scrolled the PAGE instead of moving the selection; removing the dialog outright removes the only surface that could ever steal that focus. */} {book && drillAt && (!panelTabRef.current || panelTabRef.current === tabId) && ( { setDrillAt(""); setDrillLoading(false); }} embedded={embedded} onNavigate={onNavigate} // ⛔ AFTER `onClose`, AND THAT IS LOAD BEARING. `verify_wiring`'s W50-W1 row matches // ``; a prop placed // before it would red a row this ticket does not own. onSettled={() => setDrillLoading(false)} // ⭐ W54-T35, and both props sit after `onClose` for the reason the note above gives. cellScope={drillScope} onFilterChange={onDrillFilterChange} // W60-T11 / C4: this prop also stays AFTER onClose; W50-W1 scans up to that prop. onDisplayChange={onDrillDisplayChange} // S66-T48: the tab the cell is on, so `Summary (SR)!F17` drills its own tab rather than // the first tab holding F17. After `onClose` for W50-W1's reason above. tab={tab?.id ?? tabId} /> )}
); } /* W60-T11 unit leg, colocated because this ticket owns no test file. Runs the actual callback and scope construction with the real binding helpers and workbook updater; no modal emitter is mocked. Run in aios-web/web: node -e 'const s=require("node:fs").readFileSync("src/sheet/SheetPage.tsx","utf8"); eval(s.split("\nW60_T11_UNIT_BEGIN\n")[1].split("\nW60_T11_UNIT_END")[0])' Exact one-line product edit that reds this leg, also exercised in memory below: return saveBindingAt(addr, withBindingDisplay(binding, display)); -> return saveBindingAt(addr, binding); W60_T11_UNIT_BEGIN const assert = require("node:assert/strict"), fs = require("node:fs"), ts = require("typescript"); const source = fs.readFileSync("src/sheet/SheetPage.tsx", "utf8"); const compile = code => ts.transpileModule(code, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, } }).outputText; require.extensions[".ts"] = (mod, file) => mod._compile(compile(fs.readFileSync(file, "utf8")), file); const { bindingDisplay, withBindingDisplay, bindingOnDrag } = require("./src/sheet/types.ts"); const { withCells } = require("./src/sheet/sheetState.ts"); const freeze = value => { if (value && typeof value === "object") { Object.values(value).forEach(freeze); Object.freeze(value); } return value; }; async function prove(code) { const ast = ts.createSourceFile("SheetPage.tsx", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); const declarations = new Map(); const visit = node => { if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) declarations.set(node.name.text, node); ts.forEachChild(node, visit); }; visit(ast); const expression = name => { assert.ok(declarations.has(name), `Missing product declaration: ${name}`); return declarations.get(name).initializer.getText(ast); }; const run = (body, env) => Function(...Object.keys(env), compile(body))(...Object.values(env)); for (const scope of [{ view_id: "shared", view_name: "Orders" }, { filter: { conj: "and", nodes: [] } }]) { const sharedView = freeze({ id: "shared", config: { display: { mode: "grid", visible: ["name", "amount"] } } }); const binding = freeze({ database: "ut_orders", scope, display: sharedView.config.display, aggregate: { fn: "sum", field: "amount" }, period: { unit: "month", start: "2026-09" } }); const cell = { kind: "bound", state: "fresh", value: 12, binding }; const original = freeze({ id: "book", sheets: [ { id: "other", cells: { A1: cell } }, { id: "active", cells: { A1: cell, B1: cell } }, ] }); const before = JSON.stringify({ original, sharedView }); const bookRef = { current: original }, tabIdRef = { current: "active" }, writes = []; const saveBindingAt = (addr, next) => { writes.push({ addr, binding: next }); bookRef.current = withCells(bookRef.current, tabIdRef.current, { [addr]: { ...cell, binding: next } }); return Promise.resolve(); }; const callback = run(`return ${expression("onDrillDisplayChange")};`, { useCallback: fn => fn, bookRef, tabIdRef, saveBindingAt, withBindingDisplay, }); await callback("A1", { mode: "grid", visible: [" name ", "name", ""] }); assert.equal(writes.length, 1, "Exactly one cell save"); assert.equal(writes[0].addr, "A1", "Save the addressed cell"); assert.deepEqual(writes[0].binding, { ...binding, display: { mode: "grid", visible: ["name"] } }, "Display change must land on the cell binding"); assert.equal(writes[0].binding.scope, binding.scope, "Scope is preserved for saved Views too"); assert.equal(bookRef.current.sheets[1].cells.B1, cell, "Another cell on the same database is untouched"); assert.equal(bookRef.current.sheets[0], original.sheets[0], "The inactive tab is untouched"); assert.equal(JSON.stringify({ original, sharedView }), before, "No input or shared View mutation"); const reopenedTab = JSON.parse(JSON.stringify(bookRef.current)).sheets[1]; const scopeNames = ["drillBinding", "drillBindingScope", "drillViewId", "drillAggregate", "drillAggregateField", "drillStep", "drillDisplay", "drillScope"]; const reopen = addr => run(scopeNames.map(name => `const ${name} = ${expression(name)};`).join("\n") + "\nreturn drillScope;", { tab: reopenedTab, drillAt: addr, bindingDisplay, bindingOnDrag }); assert.deepEqual(reopen("A1").display, { mode: "grid", visible: ["name"] }, "Reopen the saved cell display"); assert.deepEqual(reopen("B1").display, sharedView.config.display, "Reopen the other cell independently"); await callback("C1", { mode: "grid", visible: [] }); assert.equal(writes.length, 1, "An unbound cell does not save"); delete reopenedTab.cells.B1.binding.display; assert.equal(reopen("B1").display, undefined, "Legacy bindings retain the modal's default display"); } } (async () => { await prove(source); const ast = ts.createSourceFile("SheetPage.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); const write = "return saveBindingAt(addr, withBindingDisplay(binding, display));"; const mutated = source.replace(write, "return saveBindingAt(addr, binding);"); assert.notEqual(mutated, source, "The negative control must change product code"); assert.equal(ast.parseDiagnostics.length, 0, "The TSX source parses"); await assert.rejects(() => prove(mutated), /Display change must land on the cell binding/); console.log("W60-T11 PASS: cell-only save, shared View isolation, scope reload, legacy default; 1/1 negative control killed"); })().catch(error => { console.error(error); process.exitCode = 1; }); W60_T11_UNIT_END */