diff --git a/scripts/test/local-storage-state-rekey.ts b/scripts/test/local-storage-state-rekey.ts new file mode 100644 index 000000000..29167c2d6 --- /dev/null +++ b/scripts/test/local-storage-state-rekey.ts @@ -0,0 +1,95 @@ +// useLocalStorageState must not write one key's value over another's when the +// key changes after mount. +// +// Found in the browser 2026-10-08: the terminal's tab layout/names are keyed per +// builder, the page first renders as "cloud" and switches to "local" once the +// saved source resolves; the hook hydrated once and kept writing the CURRENT +// value to the NEW key, so `tab-layout:local` was reset on every load and the +// cloud alias was copied under `tab-names:local`. +// Run: npx tsx scripts/test/local-storage-state-rekey.ts +import { readFileSync } from "fs"; +import { join } from "path"; +import { canPersist, readStored } from "@/hooks/use-local-storage-state"; + +let pass = 0; +let fail = 0; +function ok(cond: unknown, label: string) { + if (cond) pass++; + else { + fail++; + console.error(`✗ ${label}`); + } +} + +// Nothing may be written before the key's own stored value has been read. +ok(!canPersist(null, "k:local"), "no write before any hydration"); +ok(!canPersist("k:cloud", "k:local"), "no write to a key that has not been hydrated yet"); +ok(canPersist("k:local", "k:local"), "write once this key has been hydrated"); + +// Simulate the page: the stored local value must survive a cloud -> local switch. +const store = new Map([["k:local", '{"pinned":["a"]}']]); +const storage = { getItem: (k: string) => store.get(k) ?? null }; +const parse = (raw: string) => JSON.parse(raw) as { pinned: string[] }; +const empty = { pinned: [] as string[] }; + +let hydrated: string | null = null; +let value = empty; +let key = "k:cloud"; +const written: string[] = []; +const effects = () => { + // hydrate effect, then write effect, in the hook's order + if (hydrated !== key) { + value = readStored(storage, key, parse, empty); + const wasHydrated = hydrated; + hydrated = key; + void wasHydrated; // the write effect of this pass saw the OLD hydrated key + return; + } + const serialized = JSON.stringify(value); + if (store.get(key) !== serialized) { + store.set(key, serialized); + written.push(key); + } +}; +effects(); // mount on cloud +effects(); // settled on cloud +key = "k:local"; // the source resolves after mount +effects(); // re-hydrates local +effects(); // settled on local +ok(eq(value.pinned, ["a"]), "the local key's stored value is read after the key changes"); +ok(store.get("k:local") === '{"pinned":["a"]}', "the local key still holds what it held"); +ok(!written.includes("k:local"), "the cloud value was never written to the local key"); + +// A key with nothing stored reads as the default, never as the previous key's value. +ok(eq(readStored(storage, "k:none", parse, empty).pinned, []), "an unset key reads as the default"); +ok( + readStored( + { + getItem: () => { + throw new Error("blocked"); + }, + }, + "k", + parse, + empty, + ) === empty, + "unreadable storage reads as the default", +); + +function eq(a: unknown, b: unknown) { + return JSON.stringify(a) === JSON.stringify(b); +} + +// The hook is wired to the rule, not a one-shot flag. +const src = readFileSync(join(process.cwd(), "src/hooks/use-local-storage-state.ts"), "utf8"); +ok(/canPersist\(hydratedKey, key\)/.test(src), "the write effect is gated by canPersist"); +ok( + /\}, \[key\]\); \/\/ eslint-disable-line react-hooks\/exhaustive-deps/.test(src), + "hydration re-runs when the key changes", +); + +if (fail) { + console.error(`local-storage-state-rekey: ${fail} failed, ${pass} passed`); + process.exit(1); +} +console.log(`local-storage-state-rekey: ${pass} passed`); diff --git a/scripts/test/terminal-agent-truth.ts b/scripts/test/terminal-agent-truth.ts index 3041cd186..4d1baa945 100644 --- a/scripts/test/terminal-agent-truth.ts +++ b/scripts/test/terminal-agent-truth.ts @@ -93,8 +93,27 @@ const bare = renderToStaticMarkup( ); ok(!/Close loki/.test(bare) && !/New terminal/.test(bare), "without verbs the strip stays bare"); -// Wiring: the surface uses the live agent and does not swallow a failed switch. const read = (f: string) => readFileSync(join(process.cwd(), "src/components/terminal", f), "utf8"); + +// Browser-found 2026-10-08: rename swallowed Space ("main loki" -> "mainloki") +// because the tab's own key handler caught keys bubbling from the input; an +// untouched blur stored a capped alias; Cancel floated away from its card. +const stripSrc = read("TerminalTabStrip.tsx"); +ok( + /if \(e\.target !== e\.currentTarget\) return;/.test(stripSrc), + "only the tab itself handles Space/Enter, never a key typed into its rename input", +); +ok( + /next !== tab\.label\) onRename/.test(stripSrc), + "leaving the rename box untouched is not a rename", +); +const panelSrc = read("TerminalLaunchPanel.tsx"); +ok( + /relative/.test(panelSrc) && /absolute/.test(panelSrc) && !/items-start gap-2/.test(panelSrc), + "the launcher's close control sits on its card, not beside it", +); + +// Wiring: the surface uses the live agent and does not swallow a failed switch. const surface = read("TerminalSurface.tsx"); const actions = read("use-terminal-tab-actions.ts"); ok(/activeAgentFor\(/.test(surface), "TerminalSurface derives the agent from the live CLI"); diff --git a/src/components/terminal/TerminalLaunchPanel.tsx b/src/components/terminal/TerminalLaunchPanel.tsx index 65847924e..bbca75d94 100644 --- a/src/components/terminal/TerminalLaunchPanel.tsx +++ b/src/components/terminal/TerminalLaunchPanel.tsx @@ -1,22 +1,30 @@ "use client"; import type { ComponentProps } from "react"; +import { X } from "lucide-react"; import { TerminalLaunch } from "./TerminalLaunch"; /** * The strip's "+": the same start-an-agent form the empty state uses, opened in - * place under the tabs with a way to put it away again. Desktop only — the - * phone starts sessions from its sheet. + * place under the tabs with a way to put it away again. The close control sits + * on the card itself — beside it, it floated free of the thing it dismisses. + * Desktop only — the phone starts sessions from its sheet. */ export function TerminalLaunchPanel({ onCancel, ...launch }: ComponentProps & { onCancel: () => void }) { return ( -
+
-
); diff --git a/src/components/terminal/TerminalTabStrip.tsx b/src/components/terminal/TerminalTabStrip.tsx index 7cd1886b3..5c3ec0a1b 100644 --- a/src/components/terminal/TerminalTabStrip.tsx +++ b/src/components/terminal/TerminalTabStrip.tsx @@ -168,6 +168,10 @@ export function TerminalTabStrip({ onMouseDown={() => onSelect(tab.id)} onDoubleClick={() => onRename && setEditingId(tab.id)} onKeyDown={(e) => { + // Only the tab itself selects. A key typed into the rename + // input bubbles up here, and swallowing its Space made + // "main loki" come out as "mainloki". + if (e.target !== e.currentTarget) return; if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onSelect(tab.id); @@ -205,7 +209,9 @@ export function TerminalTabStrip({ aria-label={`Rename ${tab.label}`} onBlur={(e) => { const next = e.target.value.trim(); - if (next) onRename(tab.id, next); + // Leaving the box untouched is not a rename: it used to + // store the (possibly capped) label as a permanent alias. + if (next && next !== tab.label) onRename(tab.id, next); setEditingId(null); }} onKeyDown={(e) => { diff --git a/src/hooks/use-local-storage-state.ts b/src/hooks/use-local-storage-state.ts index c471acaae..de624d8cc 100644 --- a/src/hooks/use-local-storage-state.ts +++ b/src/hooks/use-local-storage-state.ts @@ -2,10 +2,40 @@ import { useState, useEffect, useCallback } from "react"; +/** + * May the state be written to `key` yet? Only once the stored value FOR THAT + * KEY has been read. The hook used to remember a single "initialized" flag, so + * when the key changed after mount (the terminal's per-builder keys switch from + * cloud to local once the saved source resolves) the previous key's value was + * written over the new key's stored one — a reload silently reset the tab + * layout and names, and the cloud value leaked into the local key. + */ +export function canPersist(hydratedKey: string | null, key: string): boolean { + return hydratedKey === key; +} + +/** What `key` holds, or `fallback` when it holds nothing or cannot be read. A + * key with nothing stored must read as the default — not as whatever the + * previous key held. */ +export function readStored( + storage: Pick, + key: string, + deserialize: (raw: string) => T, + fallback: T, +): T { + try { + const raw = storage.getItem(key); + return raw === null ? fallback : deserialize(raw); + } catch { + return fallback; + } +} + /** * SSR-safe localStorage state hook. Defers hydration to a client-side effect * so the server-rendered default never overwrites stored values on first mount. - * Syncs changes across windows via the `storage` event. + * Re-hydrates when `key` changes. Syncs changes across windows via the + * `storage` event. */ export function useLocalStorageState( key: string, @@ -13,25 +43,20 @@ export function useLocalStorageState( serialize: (v: T) => string, deserialize: (raw: string) => T, ): [T, (updater: T | ((prev: T) => T)) => void] { - const [initialized, setInitialized] = useState(false); + const [hydratedKey, setHydratedKey] = useState(null); const [value, setValue] = useState(defaultValue); - // Hydrate from localStorage once on mount (client-only). + // Hydrate from localStorage on mount and whenever the key changes (client-only). useEffect(() => { - try { - const raw = localStorage.getItem(key); - if (raw !== null) setValue(deserialize(raw)); // eslint-disable-line react-hooks/set-state-in-effect - } catch { - /* ignore */ - } - setInitialized(true); - }, []); // eslint-disable-line react-hooks/exhaustive-deps + setValue(readStored(localStorage, key, deserialize, defaultValue)); // eslint-disable-line react-hooks/set-state-in-effect + setHydratedKey(key); + }, [key]); // eslint-disable-line react-hooks/exhaustive-deps - // Write to localStorage only after initial hydration read. + // Write to localStorage only after this key's hydration read. // Guard: skip write if the stored value already matches — prevents ping-pong // between windows when storage events cause each window to re-write the same value. useEffect(() => { - if (!initialized) return; + if (!canPersist(hydratedKey, key)) return; try { const serialized = serialize(value); if (localStorage.getItem(key) !== serialized) { @@ -40,7 +65,7 @@ export function useLocalStorageState( } catch { /* ignore */ } - }, [initialized, value, key, serialize]); + }, [hydratedKey, value, key, serialize]); // Sync changes from other windows. useEffect(() => {