Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(renderer): survive a method-less localStorage global

Erik Zwep3c4336be71eb
diff --git a/package-lock.json b/package-lock.json
index 2d9f21668..5a5c64123 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -53,6 +53,9 @@
"typescript": "^7.0.2",
"vite": "^7.3.6",
"vitest": "^4.1.10"
+ },
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/css-color": {
diff --git a/package.json b/package.json
index 7228890b7..d26c293e4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,9 @@
{
"name": "node-terminal",
"version": "0.3.2",
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
+ },
"description": "node-based terminal manager — multiple draggable, zoomable terminals on a single canvas.",
"author": {
"name": "enes",
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index c958099b7..b13132d88 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -56,6 +56,7 @@ import { createCanvasRasterizer, type AtlasPageHealth } from '../glyphgrid/raste
import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useViewMode, viewFor } from '../state/viewMode'
+import { readLocal } from '../lib/localStore'
/** Atlas page edge, in DEVICE pixels. 2048 (not Phase 0's 1024) because the atlas cells are
* device-sized AND the page is now keyed by COLOUR: at dpr 2 a 13px terminal font is roughly a
@@ -753,7 +754,7 @@ function usableCell(cell: DeviceCell | undefined): DeviceCell | null {
*/
function glyphDebugOn(): boolean {
try {
- return typeof localStorage !== 'undefined' && localStorage.getItem('nodeterm.glyphgridDebug') === '1'
+ return readLocal('nodeterm.glyphgridDebug') === '1'
} catch {
// Storage can throw outright (Safari private mode, a locked-down embedder). Debug off is
// always a safe answer.
diff --git a/src/renderer/lib/localStore.guard.test.ts b/src/renderer/lib/localStore.guard.test.ts
new file mode 100644
index 000000000..e7bb21997
--- /dev/null
+++ b/src/renderer/lib/localStore.guard.test.ts
@@ -0,0 +1,132 @@
+// One rule, invisible for the life of the project: nothing outside `lib/localStore.ts` decides for
+// itself whether `localStorage` is usable.
+//
+// Five files did, all with `typeof localStorage === 'undefined'`, and every one of them read
+// correctly to a reviewer — on a browser it IS correct. What it cannot see is a global that exists
+// with no methods, which is what recent Node hands you unless `--localstorage-file` is passed. Three
+// of the five read at module level to seed a store, so the TypeError fired on IMPORT and took twelve
+// renderer suites down at once, none of them named after the store that failed (#412).
+//
+// So the rule is enforced by scan rather than by memory: a store added next year gets the working
+// check because this test refuses the alternative, not because its author read #412.
+//
+// Deliberately NOT "must import localStore": the try/catch-only sites (`state/explorer.ts`,
+// `state/presence.ts`, `state/agentStatus.ts` and friends) are already safe — the method-missing
+// TypeError lands in their catch. The hazard is the typeof guard specifically, because it is the
+// one spelling that looks like a check and answers the wrong question.
+
+import { describe, expect, it } from 'vitest'
+import { readFileSync, readdirSync, statSync } from 'fs'
+import { join, relative } from 'path'
+
+const SOURCE_ROOT = join(__dirname, '..', '..')
+const ROOTS = [join(SOURCE_ROOT, 'renderer')]
+
+/** Guard comparisons use one separator regardless of the host running Vitest. */
+function normalizedSourcePath(value: string): string {
+ return value.replace(/\\/g, '/')
+}
+
+function sourceRelativePath(file: string): string {
+ return normalizedSourcePath(relative(SOURCE_ROOT, file))
+}
+
+function sources(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry)
+ if (statSync(p).isDirectory()) {
+ if (entry !== 'node_modules') sources(p, out)
+ } else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) {
+ out.push(p)
+ }
+ }
+ return out
+}
+
+/**
+ * Files allowed to test the `localStorage` global directly, each with the reason.
+ *
+ * Kept deliberately short. An entry here means "the check belongs here", not "nobody got round to
+ * it yet" — the latter belongs in an issue.
+ */
+const GUARD_ALLOWED = new Map<string, string>([
+ ['renderer/lib/localStore.ts', 'the helper; this is where the one real check lives']
+])
+
+function isGuardAllowed(relativeFile: string): boolean {
+ return GUARD_ALLOWED.has(normalizedSourcePath(relativeFile))
+}
+
+/**
+ * Every spelling of "ask whether the global exists" — the question that cannot distinguish a
+ * method-less global from a working one. Comments are stripped first: this file and `localStore.ts`
+ * both discuss the banned pattern in prose, and a guard that flags its own explanation trains people
+ * to add exemptions.
+ */
+function typeofGuardHits(text: string): string[] {
+ const code = text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')
+ return [
+ ...code.matchAll(
+ /typeof\s*\(?\s*(?:(?:globalThis|window|self)\s*(?:\.\s*|\[\s*['"]))?localStorage\b/g
+ )
+ ].map((m) => m[0].replace(/\s+/g, ' '))
+}
+
+describe('only localStore.ts decides whether localStorage is usable', () => {
+ const files = ROOTS.flatMap((r) => sources(r))
+
+ it('finds the source tree (a zero-file scan would pass silently)', () => {
+ // The failure mode this whole file guards against, one level up: a scan matching nothing
+ // reports clean. If a directory moves and this drops to nothing, it must go red, not quiet.
+ expect(files.length).toBeGreaterThan(100)
+ })
+
+ it('no bare typeof-localStorage guard outside the helper', () => {
+ const offenders: string[] = []
+ for (const f of files) {
+ const rel = sourceRelativePath(f)
+ if (isGuardAllowed(rel)) continue
+ const hits = typeofGuardHits(readFileSync(f, 'utf8'))
+ if (hits.length) offenders.push(`${rel} [${hits.join(', ')}]`)
+ }
+ expect(
+ offenders,
+ 'these ask whether the localStorage global EXISTS, which is true for the method-less global ' +
+ 'recent Node provides — the next call then throws. Use readLocal/writeLocal/localStoreUsable ' +
+ 'from renderer/lib/localStore.ts'
+ ).toEqual([])
+ })
+
+ it('the guard would actually catch each spelling', () => {
+ // Proving the needle bites, on strings rather than by breaking real files.
+ expect(typeofGuardHits("if (typeof localStorage === 'undefined') return null")).not.toEqual([])
+ expect(typeofGuardHits("if (typeof localStorage !== 'undefined') save(v)")).not.toEqual([])
+ expect(typeofGuardHits('typeof localStorage === "undefined"')).not.toEqual([])
+ expect(typeofGuardHits("typeof window.localStorage === 'undefined'")).not.toEqual([])
+ expect(typeofGuardHits("typeof globalThis.localStorage === 'undefined'")).not.toEqual([])
+ // Parenthesised and bracket spellings: the first version of this needle knew only the bare
+ // identifier, which is exactly how a guard turns "nobody checked" into "this was checked".
+ expect(typeofGuardHits("typeof(localStorage) === 'undefined'")).not.toEqual([])
+ expect(typeofGuardHits("typeof (localStorage) === 'undefined'")).not.toEqual([])
+ expect(typeofGuardHits("typeof globalThis['localStorage'] === 'undefined'")).not.toEqual([])
+ expect(typeofGuardHits('typeof window["localStorage"] === "undefined"')).not.toEqual([])
+ // …and does NOT flag the replacements, nor a name that merely contains it.
+ expect(typeofGuardHits("readLocal('k') === '1'")).toEqual([])
+ expect(typeofGuardHits('if (!localStoreUsable()) return true')).toEqual([])
+ expect(typeofGuardHits("typeof localStorageMirror === 'undefined'")).toEqual([])
+ expect(typeofGuardHits("typeof myLocalStorage === 'undefined'")).toEqual([])
+ expect(typeofGuardHits("typeof sessionStorage === 'undefined'")).toEqual([])
+ // The prose exemption: discussion in comments is not an offence, or this file fails itself.
+ expect(typeofGuardHits("// typeof localStorage === 'undefined' was the old guard")).toEqual([])
+ expect(typeofGuardHits("/* typeof localStorage is not enough */")).toEqual([])
+ })
+
+ it('normalizes the helper exemption on both POSIX and Windows-shaped paths', () => {
+ expect(isGuardAllowed('renderer/lib/localStore.ts')).toBe(true)
+ expect(isGuardAllowed(String.raw`renderer\lib\localStore.ts`)).toBe(true)
+ expect(isGuardAllowed('renderer/lib/localStore.ts.bak')).toBe(false)
+ expect(isGuardAllowed('nested/renderer/lib/localStore.ts')).toBe(false)
+ const scanned = new Set(files.map(sourceRelativePath))
+ for (const allowed of GUARD_ALLOWED.keys()) expect(scanned.has(allowed)).toBe(true)
+ })
+})
diff --git a/src/renderer/lib/localStore.test.ts b/src/renderer/lib/localStore.test.ts
new file mode 100644
index 000000000..fca93f75c
--- /dev/null
+++ b/src/renderer/lib/localStore.test.ts
@@ -0,0 +1,135 @@
+// The bug this file exists for: a `localStorage` global that EXISTS but has no methods. Recent Node
+// ships exactly that unless `--localstorage-file` is passed, so `typeof localStorage === 'undefined'`
+// — the guard five call sites used — reports 'object' and lets the call through. See #412.
+//
+// Each case installs a different broken shape on globalThis and asserts the helper survives it. The
+// method-less one is the real regression; the others are the browser failures that were already
+// handled and must stay handled.
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { readLocal, writeLocal } from './localStore'
+
+const KEY = 'nodeterm.test.key'
+
+function install(value: unknown): void {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value,
+ configurable: true,
+ writable: true
+ })
+}
+
+afterEach(() => {
+ Reflect.deleteProperty(globalThis as object, 'localStorage')
+ vi.restoreAllMocks()
+})
+
+describe('readLocal', () => {
+ it('returns the stored string when storage works', () => {
+ install({ getItem: (k: string) => (k === KEY ? 'stored' : null), setItem: () => {} })
+ expect(readLocal(KEY)).toBe('stored')
+ })
+
+ it('returns null for a key that is not set', () => {
+ install({ getItem: () => null, setItem: () => {} })
+ expect(readLocal(KEY)).toBeNull()
+ })
+
+ // THE regression: the object is there, `typeof` says 'object', and the method is not.
+ it('survives a method-less global (Node without --localstorage-file)', () => {
+ install({})
+ expect(() => readLocal(KEY)).not.toThrow()
+ expect(readLocal(KEY)).toBeNull()
+ })
+
+ it('survives a global whose getItem is not callable', () => {
+ install({ getItem: 'nope' })
+ expect(readLocal(KEY)).toBeNull()
+ })
+
+ it('survives storage that throws on access (private mode, locked-down embedder)', () => {
+ install({
+ getItem: () => {
+ throw new Error('SecurityError')
+ }
+ })
+ expect(readLocal(KEY)).toBeNull()
+ })
+
+ it('survives the global being absent entirely', () => {
+ Reflect.deleteProperty(globalThis as object, 'localStorage')
+ expect(readLocal(KEY)).toBeNull()
+ })
+})
+
+describe('writeLocal', () => {
+ it('writes through when storage works', () => {
+ const setItem = vi.fn()
+ install({ getItem: () => null, setItem })
+ writeLocal(KEY, 'v')
+ expect(setItem).toHaveBeenCalledWith(KEY, 'v')
+ })
+
+ it('is silent on a method-less global', () => {
+ install({})
+ expect(() => writeLocal(KEY, 'v')).not.toThrow()
+ })
+
+ it('is silent when the write throws (quota exceeded)', () => {
+ install({
+ setItem: () => {
+ throw new Error('QuotaExceededError')
+ }
+ })
+ expect(() => writeLocal(KEY, 'v')).not.toThrow()
+ })
+
+ it('is silent when the global is absent entirely', () => {
+ Reflect.deleteProperty(globalThis as object, 'localStorage')
+ expect(() => writeLocal(KEY, 'v')).not.toThrow()
+ })
+})
+
+describe('readLocal fallback — the distinction the copy hint depends on', () => {
+ // These four cases ARE `hintSeen()`. It reads `readLocal(KEY, '1') === '1'`, so the fallback is
+ // the whole behaviour: unreadable storage must count as seen (or the hint returns on every copy),
+ // while a key that is merely unset must not.
+ it('an UNSET key returns null, not the fallback — still "not seen"', () => {
+ install({ getItem: () => null, setItem: () => {} })
+ expect(readLocal(KEY, '1')).toBeNull()
+ })
+
+ it('a method-less global returns the fallback — "seen"', () => {
+ install({})
+ expect(readLocal(KEY, '1')).toBe('1')
+ })
+
+ it('storage that THROWS returns the fallback — "seen"', () => {
+ // The regression an earlier draft of this change shipped: a callable getItem that throws left
+ // the hint showing on every copy, because the throw was collapsed into "no value".
+ install({
+ getItem: () => {
+ throw new Error('SecurityError')
+ }
+ })
+ expect(readLocal(KEY, '1')).toBe('1')
+ })
+
+ it('a stored value still wins over the fallback', () => {
+ install({ getItem: () => '1', setItem: () => {} })
+ expect(readLocal(KEY, '1')).toBe('1')
+ install({ getItem: () => 'other', setItem: () => {} })
+ expect(readLocal(KEY, '1')).toBe('other')
+ })
+})
+
+describe('the old guard would NOT have caught this', () => {
+ // Mutation-testing the fix from the other side: pin that the pattern being banned is genuinely
+ // broken on the shape that broke it, so this suite fails if someone "simplifies" the helper back.
+ it('typeof localStorage === undefined passes a method-less global', () => {
+ install({})
+ expect(typeof localStorage).toBe('object')
+ expect(typeof localStorage === 'undefined').toBe(false)
+ expect(() => (localStorage as Storage).getItem(KEY)).toThrow(TypeError)
+ })
+})
diff --git a/src/renderer/lib/localStore.ts b/src/renderer/lib/localStore.ts
new file mode 100644
index 000000000..bf640c975
--- /dev/null
+++ b/src/renderer/lib/localStore.ts
@@ -0,0 +1,55 @@
+/**
+ * The one way this codebase touches `localStorage`.
+ *
+ * `typeof localStorage === 'undefined'` was the guard at five sites, and it is not enough. Recent
+ * Node exposes a `localStorage` GLOBAL THAT IS METHOD-LESS unless `--localstorage-file` is passed:
+ * `typeof localStorage` answers `'object'`, the guard lets the call through, and `.getItem` throws
+ * `TypeError: localStorage.getItem is not a function`. Three of those sites read at MODULE level to
+ * seed a zustand store, so the throw happens on import and takes down every suite that transitively
+ * imports them — twelve renderer test files on Node 25, none of them named after the store that
+ * failed. See #412.
+ *
+ * Two properties, both load-bearing:
+ *
+ * 1. The feature check asks whether the METHOD is callable, not whether the object exists. That is
+ * the distinction the old guard could not make.
+ * 2. It sits inside the try/catch with the call. `typeof localStorage?.getItem` looks like it
+ * cannot throw, but `typeof` only shields a BARE identifier — the operand here is a member
+ * expression, so an environment with no `localStorage` binding at all raises ReferenceError
+ * before `typeof` sees anything. The catch is what makes the optional chain safe, not decoration
+ * around it. Storage can also throw once it exists (Safari private mode, a locked-down embedder,
+ * quota on write), and both failures want the same answer.
+ *
+ * Everything persisted through here is a nicety — a remembered panel, a view choice, a hint already
+ * shown. None of it may fail the UI, so a read that cannot happen is `null` and a write that cannot
+ * happen is silence.
+ */
+
+/**
+ * The stored string, or `whenUnreadable` when storage is absent, method-less, or throws.
+ *
+ * The default collapses "storage is broken" into "no value", which is what every caller that just
+ * wants a remembered nicety means. One caller needs them apart: the copy hint passes its own
+ * fallback so that UNREADABLE storage counts as "already seen" — a hint that can never be
+ * remembered would otherwise reappear on every single copy — while an UNSET key still means not
+ * seen. Keeping that distinction in the argument rather than in a second predicate is what stops
+ * the two cases drifting apart at the call site.
+ */
+export function readLocal(key: string, whenUnreadable: string | null = null): string | null {
+ try {
+ if (typeof localStorage?.getItem !== 'function') return whenUnreadable
+ return localStorage.getItem(key)
+ } catch {
+ return whenUnreadable
+ }
+}
+
+/** Persist a string, or do nothing when storage is absent, method-less, full, or throws. */
+export function writeLocal(key: string, value: string): void {
+ try {
+ if (typeof localStorage?.setItem !== 'function') return
+ localStorage.setItem(key, value)
+ } catch {
+ /* quota, private mode, disabled storage — never fail the UI over a remembered nicety */
+ }
+}
diff --git a/src/renderer/state/cardModalSize.ts b/src/renderer/state/cardModalSize.ts
index 842b6991a..57bbaa53e 100644
--- a/src/renderer/state/cardModalSize.ts
+++ b/src/renderer/state/cardModalSize.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { readLocal, writeLocal } from '../lib/localStore'
// Remembered size of the kanban card modal — PERSONAL, per machine (localStorage), never in the
// git-shared .nodeterm/project.json (same rule as the view mode and the comments panel). The modal
@@ -82,7 +83,7 @@ export function parseCardModalSize(raw: string | null): CardModalSize {
function save(size: CardModalSize): void {
try {
- localStorage.setItem(CARD_MODAL_SIZE_KEY, JSON.stringify(size))
+ writeLocal(CARD_MODAL_SIZE_KEY, JSON.stringify(size))
} catch {
/* quota/private-mode: a remembered size is a nicety, never fail the UI */
}
@@ -95,16 +96,15 @@ interface CardModalSizeState extends CardModalSize {
}
export const useCardModalSize = create<CardModalSizeState>((set, get) => ({
- // localStorage guard: this module is also imported by node-environment vitest suites.
- ...parseCardModalSize(typeof localStorage === 'undefined' ? null : localStorage.getItem(CARD_MODAL_SIZE_KEY)),
+ ...parseCardModalSize(readLocal(CARD_MODAL_SIZE_KEY)),
remember: (width, height) => {
const next = { width, height, maximized: false }
- if (typeof localStorage !== 'undefined') save(next)
+ save(next)
set(next)
},
setMaximized: (maximized) => {
const next = { width: get().width, height: get().height, maximized }
- if (typeof localStorage !== 'undefined') save(next)
+ save(next)
set({ maximized })
}
}))
diff --git a/src/renderer/state/cardPanel.ts b/src/renderer/state/cardPanel.ts
index 6016f03c4..501d089ed 100644
--- a/src/renderer/state/cardPanel.ts
+++ b/src/renderer/state/cardPanel.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { readLocal, writeLocal } from '../lib/localStore'
// Whether the kanban card modal opens with its comments & activity panel expanded — PERSONAL,
// per machine: persisted in localStorage, deliberately never in the git-shared
@@ -17,7 +18,7 @@ export function parseCardPanelOpen(raw: string | null): boolean {
function save(open: boolean): void {
try {
- localStorage.setItem(CARD_PANEL_KEY, open ? 'true' : 'false')
+ writeLocal(CARD_PANEL_KEY, open ? 'true' : 'false')
} catch {
/* quota/private-mode: the panel state is a nicety, never fail the UI */
}
@@ -30,12 +31,9 @@ interface CardPanelState {
}
export const useCardPanel = create<CardPanelState>((set, get) => ({
- // localStorage guard: this module is also imported by node-environment vitest suites.
- open: parseCardPanelOpen(
- typeof localStorage === 'undefined' ? null : localStorage.getItem(CARD_PANEL_KEY)
- ),
+ open: parseCardPanelOpen(readLocal(CARD_PANEL_KEY)),
setOpen: (open) => {
- if (typeof localStorage !== 'undefined') save(open)
+ save(open)
set({ open })
},
toggle: () => get().setOpen(!get().open)
diff --git a/src/renderer/state/viewMode.ts b/src/renderer/state/viewMode.ts
index b5115c80c..8145c7cb0 100644
--- a/src/renderer/state/viewMode.ts
+++ b/src/renderer/state/viewMode.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { readLocal, writeLocal } from '../lib/localStore'
// Which view each project shows (canvas or kanban) — PERSONAL, per machine: persisted in
// localStorage, deliberately never in the git-shared .nodeterm/project.json (spec rule).
@@ -26,7 +27,7 @@ export function parseViewMap(raw: string | null): Record<string, ProjectView> {
function save(v: Record<string, ProjectView>): void {
try {
- localStorage.setItem(PROJECT_VIEW_KEY, JSON.stringify(v))
+ writeLocal(PROJECT_VIEW_KEY, JSON.stringify(v))
} catch {
/* quota/private-mode: the view choice is a nicety, never fail the UI */
}
@@ -58,10 +59,7 @@ export function viewFor(s: Pick<ViewModeState, 'viewByProject' | 'defaultView'>,
}
export const useViewMode = create<ViewModeState>((set) => ({
- // localStorage guard: this module is also imported by node-environment vitest suites.
- viewByProject: parseViewMap(
- typeof localStorage === 'undefined' ? null : localStorage.getItem(PROJECT_VIEW_KEY)
- ),
+ viewByProject: parseViewMap(readLocal(PROJECT_VIEW_KEY)),
defaultView: 'canvas',
setDefaultView: (v) => set((s) => (s.defaultView === v ? s : { defaultView: v })),
requestedCardNodeId: null,
@@ -75,7 +73,7 @@ export const useViewMode = create<ViewModeState>((set) => ({
...s.viewByProject,
[projectId]: cur === 'kanban' ? 'canvas' : 'kanban'
}
- if (typeof localStorage !== 'undefined') save(next)
+ save(next)
// Leaving the board (or entering it) drops any unconsumed request — it belonged to the view
// the user just left, and firing it later would pop a card out of nowhere.
return { viewByProject: next, requestedCardNodeId: null }
diff --git a/src/renderer/terminal/useCopyFeedback.ts b/src/renderer/terminal/useCopyFeedback.ts
index 3dadfabb1..18542936e 100644
--- a/src/renderer/terminal/useCopyFeedback.ts
+++ b/src/renderer/terminal/useCopyFeedback.ts
@@ -14,24 +14,17 @@ import {
decideDragOutcome,
type CopyFeedback
} from './copy-feedback'
+import { readLocal, writeLocal } from '../lib/localStore'
-/** Guarded both ways: this module is imported by node-environment vitest suites, and a browser
- * with storage disabled must not break copying. */
+/** Unreadable storage means "already seen" — a hint that can never be remembered would otherwise
+ * reappear on every copy — while an UNSET key means not seen. Hence the fallback argument: a null
+ * check alone cannot tell those two apart. */
function hintSeen(): boolean {
- try {
- if (typeof localStorage === 'undefined') return true
- return localStorage.getItem(HINT_STORAGE_KEY) === '1'
- } catch {
- return true
- }
+ return readLocal(HINT_STORAGE_KEY, '1') === '1'
}
function markHintSeen(): void {
- try {
- if (typeof localStorage !== 'undefined') localStorage.setItem(HINT_STORAGE_KEY, '1')
- } catch {
- // A hint we cannot remember is better shown once too often than not at all — but never fatal.
- }
+ writeLocal(HINT_STORAGE_KEY, '1')
}
export interface CopyFeedbackApi {