fix(terminal): tab layout and names survive reload; rename keeps spaces; launcher closes on its card (#1101)

Found by driving the live page in a browser after #1093:

- useLocalStorageState hydrated once but kept writing the CURRENT value to the
  CURRENT key. The terminal keys tab layout and names per builder and first
  renders as "cloud" before the saved source resolves to "local", so every load
  reset loki:terminal-tab-layout:local and copied the cloud alias under the
  local key. Persisting is now allowed only for a key whose own stored value has
  been read, and hydration re-runs when the key changes (canPersist/readStored,
  tested, mutation-checked).
- Renaming a tab swallowed spaces ("main loki" -> "mainloki"): a key typed into
  the rename input bubbled to the tab's own Space-to-select handler. Only the
  tab itself handles it now.
- Leaving the rename box untouched stored the (capped) label as a permanent alias.
- The "Start an agent" panel's Cancel floated detached to the right of its card;
  the close control now sits on the card.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
CatoandClaude Sonnet 5.5 authored and GitHub committed 2026-10-08 09:51:47 -07:00
1 parent 61c240ea24
commit fa8dbfe140
5 files changed
+174 -21

No files matched your search

+95
View File
@@ -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<string, string>([["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`);
+20 -1
View File
@@ -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");
@@ -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<typeof TerminalLaunch> & { onCancel: () => void }) {
return (
<div className="hidden items-start gap-2 md:flex">
<div className="relative hidden w-full max-w-xl md:block">
<TerminalLaunch {...launch} />
<button type="button" className="ui-btn-secondary" onClick={onCancel}>
Cancel
<button
type="button"
className="ui-btn-icon absolute right-2 top-5"
aria-label="Close"
title="Close"
onClick={onCancel}
>
<X className="h-3.5 w-3.5" />
</button>
</div>
);
+7 -1
View File
@@ -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) => {
+39 -14
View File
@@ -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<T>(
storage: Pick<Storage, "getItem">,
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<T>(
key: string,
@@ -13,25 +43,20 @@ export function useLocalStorageState<T>(
serialize: (v: T) => string,
deserialize: (raw: string) => T,
): [T, (updater: T | ((prev: T) => T)) => void] {
const [initialized, setInitialized] = useState(false);
const [hydratedKey, setHydratedKey] = useState<string | null>(null);
const [value, setValue] = useState<T>(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<T>(
} catch {
/* ignore */
}
}, [initialized, value, key, serialize]);
}, [hydratedKey, value, key, serialize]);
// Sync changes from other windows.
useEffect(() => {