Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: extract shared safeStorage helper for guarded localStorage (#2387)
Adam Eivy9bb2937e8c23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex afc27db774..0fbe8ec78d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -51,7 +51,7 @@## Fixed-- **[issue-2387] Theme initialization and switching now survive unavailable localStorage.** The `useTheme` and `useCitySettings` hooks read/wrote `localStorage` directly (persisted theme, and the CyberCity settings that render on the same theme path), so a browser where storage access throws (Safari private mode, blocked cookies, disabled storage) or is absent would throw inside a `useState` initializer and crash the initial render, and a failing `setItem` could break theme switching. Both hooks now route every read/write/remove through guarded helpers that swallow access failures, and corrupt stored JSON falls back to defaults instead of throwing — so init always resolves to a valid default and in-memory switching keeps working when persistence fails. `setTheme` also applies the in-memory theme (DOM + state) before any persistence/side-effect work so a later failure can never leave the UI on the stale theme. Focused hook tests cover read-throws-on-init, corrupt/invalid stored value, and write-throws-on-switch for both hooks.+- **[issue-2387] Theme initialization and switching now survive unavailable localStorage.** The `useTheme` and `useCitySettings` hooks read/wrote `localStorage` directly (persisted theme, and the CyberCity settings that render on the same theme path), so a browser where storage access throws (Safari private mode, blocked cookies, disabled storage) or is absent would throw inside a `useState` initializer and crash the initial render, and a failing `setItem` could break theme switching. Both hooks now route every read/write/remove through a shared, guarded `safeReadStorage`/`safeWriteStorage`/`safeRemoveStorage` helper (`client/src/lib/safeStorage.js`) that swallows access failures, and corrupt stored JSON falls back to defaults instead of throwing — so init always resolves to a valid default and in-memory switching keeps working when persistence fails. `setTheme` also applies the in-memory theme (DOM + state) before any persistence/side-effect work so a later failure can never leave the UI on the stale theme. Focused hook tests cover read-throws-on-init, corrupt/invalid stored value, and write-throws-on-switch for both hooks.- **CoS agents (notably codex) now open their PR as the gh account that matches the repo owner, not gh's mutable active user.** PortOS's own `createPR` pins `GH_TOKEN` to the logged-in gh account whose login matches the repo owner (avoiding the multi-account "must be a collaborator" failure), but a spawned agent running its *own* `gh pr create` — a codex/Claude/CLI CoS agent finishing `/do:pr` — never received that pinning. TUI agents fared worst: `shell.js`'s `buildSafeEnv` strips `GH_TOKEN` from the inherited env entirely, so their `gh` fell back to whatever `hosts.yml` active user happened to be set. A new best-effort `resolveForgeTokenEnv(dir)` (in `server/services/git.js`) resolves just the owner-matched `GH_TOKEN` overlay and is injected into all three agent-spawn env paths — direct CLI (`spawnDirectly`), TUI shell session (`spawnTuiAgent`), and the CoS runner (`spawnViaRunner`). It's provider-agnostic (no codex special-case), returns `{}` when no owner-matched account exists (so single-account installs and GitLab repos are untouched), and is spread before `provider.envVars` so an explicit provider `GH_TOKEN` override still wins.diff --git a/client/src/hooks/useCitySettings.js b/client/src/hooks/useCitySettings.jsindex 481a7848e5..68e6585fa1 100644--- a/client/src/hooks/useCitySettings.js+++ b/client/src/hooks/useCitySettings.js@@ -1,4 +1,5 @@import { useEffect, useState, useCallback } from 'react';+import { safeReadStorage, safeWriteStorage, safeRemoveStorage } from '../lib/safeStorage.js';// Exported so useTheme can reset the city's time-of-day override without// re-declaring these magic strings (a typo there would silently break the reset).@@ -48,34 +49,6 @@ const DEFAULT_SETTINGS = {...QUALITY_PRESETS.high,};-// localStorage can throw (Safari private mode, blocked storage, disabled cookies)-// or be absent. These settings drive CyberCity, which also renders on the theme-// path, so guard every access — a storage failure must never crash init or a-// settings write. Persistence is best-effort; in-memory state is the source of truth.-const safeReadStorage = (key) => {- try {- return globalThis.localStorage?.getItem(key) ?? null;- } catch {- return null;- }-};--const safeWriteStorage = (key, value) => {- try {- globalThis.localStorage?.setItem(key, value);- } catch {- // Ignore — settings changes stay in memory when persistence is unavailable.- }-};--const safeRemoveStorage = (key) => {- try {- globalThis.localStorage?.removeItem(key);- } catch {- // Ignore — nothing persisted to remove when storage is unavailable.- }-};-const loadSettings = () => {const saved = safeReadStorage(STORAGE_KEY);if (!saved) return DEFAULT_SETTINGS;diff --git a/client/src/hooks/useTheme.js b/client/src/hooks/useTheme.jsindex 32b3f72eb6..a8d3dbcb2a 100644--- a/client/src/hooks/useTheme.js+++ b/client/src/hooks/useTheme.js@@ -10,33 +10,10 @@ import {STORAGE_KEY as CITY_SETTINGS_KEY,TIME_OF_DAY_AUTO_EVENT as CITY_TIME_OF_DAY_AUTO_EVENT,} from './useCitySettings';+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';const STORAGE_KEY = 'portos-theme';-// localStorage can throw (Safari private mode, blocked storage, disabled-// cookies) or be entirely absent. Guard every access so theme init/switching-// stays usable when persistence is unavailable — the in-memory theme is the-// source of truth; localStorage is best-effort. Returns null on any failure so-// callers fall through to a valid default (normalizeThemeId handles null).-const safeReadStorage = (key) => {- try {- return globalThis.localStorage?.getItem(key) ?? null;- } catch {- return null;- }-};--// Best-effort write; returns false when persistence is unavailable so callers-// can decide (they don't — theme switching continues regardless).-const safeWriteStorage = (key, value) => {- try {- globalThis.localStorage?.setItem(key, value);- return true;- } catch {- return false;- }-};-const applyTheme = (id) => {const theme = getTheme(id);const style = document.documentElement.style;diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b6d920ad65..7c269917d8 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -93,6 +93,7 @@ grep -i "what you want to do" client/src/lib/README.md| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. || `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |+| `safeStorage.js` | `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage) and treats missing storage as absent (`null`). Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme` / `useCitySettings`. || `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. || `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 12a4a52fd2..1d55ebdc76 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -64,6 +64,7 @@ export * from './manuscriptFormat.js';export * from './mediaNavigation.js';export * from './mediaSearch.js';export * from './moodBoardItemSrc.js';+export * from './safeStorage.js';export * from './sameJsonShape.js';export * from './sketchCanvas.js';export * from './unsorted.js';diff --git a/client/src/lib/safeStorage.js b/client/src/lib/safeStorage.jsnew file mode 100644index 0000000000..5125d67bda--- /dev/null+++ b/client/src/lib/safeStorage.js@@ -0,0 +1,34 @@+// Guarded localStorage access. `localStorage` can throw (Safari private mode,+// blocked storage, disabled cookies) or be entirely absent (SSR, sandboxed+// iframes). These helpers make persistence best-effort so a storage failure+// never crashes a `useState` initializer or a write path — in-memory state stays+// the source of truth. Use these instead of touching `localStorage` inline.++// Returns the stored string, or null on any failure / missing storage. Callers+// distinguish absent (null) from a legitimately-empty value and fall through to+// their own default.+export const safeReadStorage = (key) => {+ try {+ return globalThis.localStorage?.getItem(key) ?? null;+ } catch {+ return null;+ }+};++// Best-effort write; silently no-ops when storage is unavailable.+export const safeWriteStorage = (key, value) => {+ try {+ globalThis.localStorage?.setItem(key, value);+ } catch {+ // Ignore — the value stays in memory when persistence is unavailable.+ }+};++// Best-effort remove; silently no-ops when storage is unavailable.+export const safeRemoveStorage = (key) => {+ try {+ globalThis.localStorage?.removeItem(key);+ } catch {+ // Ignore — nothing persisted to remove when storage is unavailable.+ }+};diff --git a/client/src/lib/safeStorage.test.js b/client/src/lib/safeStorage.test.jsnew file mode 100644index 0000000000..d5e78880be--- /dev/null+++ b/client/src/lib/safeStorage.test.js@@ -0,0 +1,40 @@+import { describe, it, expect, afterEach, vi } from 'vitest';+import { safeReadStorage, safeWriteStorage, safeRemoveStorage } from './safeStorage.js';++afterEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+});++describe('safeStorage', () => {+ it('round-trips through a healthy localStorage', () => {+ expect(safeWriteStorage('k', 'v')).toBeUndefined();+ expect(safeReadStorage('k')).toBe('v');+ safeRemoveStorage('k');+ expect(safeReadStorage('k')).toBeNull();+ });++ it('returns null for a missing key (distinguishes absent from empty)', () => {+ expect(safeReadStorage('missing')).toBeNull();+ window.localStorage.setItem('empty', '');+ expect(safeReadStorage('empty')).toBe('');+ });++ it('returns null instead of throwing when getItem throws', () => {+ vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {+ throw new DOMException('The operation is insecure.', 'SecurityError');+ });+ expect(safeReadStorage('k')).toBeNull();+ });++ it('swallows setItem / removeItem throws', () => {+ vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');+ });+ vi.spyOn(window.localStorage.__proto__, 'removeItem').mockImplementation(() => {+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');+ });+ expect(() => safeWriteStorage('k', 'v')).not.toThrow();+ expect(() => safeRemoveStorage('k')).not.toThrow();+ });+});