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
fix: make theme persistence resilient to unavailable localStorage (#2387)
Adam Eivyb55ea579241b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 97620dc070..9dccfcc4c1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -51,6 +51,8 @@## Fixed+- **[issue-2387] Theme initialization and switching now survive unavailable localStorage.** The `useTheme` hook read and wrote `localStorage` directly for the persisted theme (and the city time-of-day reset), so a browser where storage access throws (Safari private mode, blocked cookies, disabled storage) or is absent would throw inside the `useState` initializer and crash the initial render, and a failing `setItem` could break theme switching. Reads and writes now go through guarded `safeReadStorage`/`safeWriteStorage` helpers that swallow access failures and return null/false, so init always falls back to a valid default theme and in-memory switching keeps working when persistence fails. Corrupt city-settings JSON no longer aborts the time-of-day reset either. Focused hook tests cover read-throws-on-init, invalid stored value, and write-throws-on-switch.+- **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.- **Codex CoS agents no longer die `paste-not-rendered` while codex boots its MCP servers.** Codex boots any MCP servers configured in the user's global `~/.codex/config.toml` on every headless spawn — including heavyweight interactive ones like `playwright` (fetched via `npx`) or a `node_repl` with `startup_timeout_sec = 120`. That boot can run for tens of seconds up to ~2 minutes, during which codex swallows pastes, renders no `[Pasted Content N chars]` commit marker, and shows only the *tail* of a long paste in its input viewport (never the verified prefix) — so PortOS's paste-verify retry could not confirm delivery and killed the agent after only 3 short attempts (~19s), long before the boot finished (real incident 2026-07-10: `agent-c5a26b40` / `agent-3f4ae3b1`, both on gpt-5.6-sol; the same prompt succeeded days earlier when no MCP servers were configured and codex was ready in <10s). The spawner now detects codex's MCP-boot banner (`Booting MCP server` / `Starting MCP servers`) and extends the paste-retry budget from the fixed 3 attempts to a time budget (150s, covering `node_repl`'s 120s startup plus an `npx` cold download while staying under the idle-reap window), so a slow boot completes and the paste finally lands. If the boot genuinely never finishes, the failure now names the MCP-boot cause and points at the codex config instead of a misleading "still initializing" message. Non-codex TUIs and codex installs without MCP servers are unchanged.diff --git a/client/src/hooks/useTheme.js b/client/src/hooks/useTheme.jsindex 237a191bc4..c7a6408ad0 100644--- a/client/src/hooks/useTheme.js+++ b/client/src/hooks/useTheme.js@@ -13,6 +13,30 @@ import {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;@@ -29,21 +53,25 @@ const applyTheme = (id) => {};const loadTheme = () => {- const saved = localStorage.getItem(STORAGE_KEY);+ const saved = safeReadStorage(STORAGE_KEY);const normalized = normalizeThemeId(saved);- if (saved && saved !== normalized) localStorage.setItem(STORAGE_KEY, normalized);+ if (saved && saved !== normalized) safeWriteStorage(STORAGE_KEY, normalized);return normalized;};const resetCityTimeOfDayOverride = () => {- try {- const raw = localStorage.getItem(CITY_SETTINGS_KEY);- const citySettings = raw ? JSON.parse(raw) : {};- localStorage.setItem(CITY_SETTINGS_KEY, JSON.stringify({ ...citySettings, timeOfDay: 'auto' }));- window.dispatchEvent(new Event(CITY_TIME_OF_DAY_AUTO_EVENT));- } catch {- // Theme switching should still work if city settings are unavailable/corrupt.+ const raw = safeReadStorage(CITY_SETTINGS_KEY);+ let citySettings = {};+ if (raw) {+ try {+ const parsed = JSON.parse(raw);+ if (parsed && typeof parsed === 'object') citySettings = parsed;+ } catch {+ // Corrupt city settings — start from an empty object rather than bail.+ }}+ safeWriteStorage(CITY_SETTINGS_KEY, JSON.stringify({ ...citySettings, timeOfDay: 'auto' }));+ window.dispatchEvent(new Event(CITY_TIME_OF_DAY_AUTO_EVENT));};export default function useTheme() {@@ -61,9 +89,9 @@ export default function useTheme() {.then(settings => {if (userPickedRef.current) return;const serverTheme = settings?.theme ? normalizeThemeId(settings.theme) : null;- const currentSaved = normalizeThemeId(localStorage.getItem(STORAGE_KEY));+ const currentSaved = normalizeThemeId(safeReadStorage(STORAGE_KEY));if (serverTheme && serverTheme !== currentSaved) {- localStorage.setItem(STORAGE_KEY, serverTheme);+ safeWriteStorage(STORAGE_KEY, serverTheme);resetCityTimeOfDayOverride();applyTheme(serverTheme);setThemeId(serverTheme);@@ -79,7 +107,7 @@ export default function useTheme() {const setTheme = useCallback((id) => {userPickedRef.current = true;const normalized = normalizeThemeId(id);- localStorage.setItem(STORAGE_KEY, normalized);+ safeWriteStorage(STORAGE_KEY, normalized);resetCityTimeOfDayOverride();applyTheme(normalized);setThemeId(normalized);diff --git a/client/src/hooks/useTheme.test.jsx b/client/src/hooks/useTheme.test.jsxnew file mode 100644index 0000000000..b62dc16f06--- /dev/null+++ b/client/src/hooks/useTheme.test.jsx@@ -0,0 +1,65 @@+import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import useTheme from './useTheme.js';+import { DEFAULT_THEME_ID, THEME_IDS } from '../themes/portosThemes.js';++// Pick any non-default valid theme to prove in-memory switching still works.+const OTHER_THEME_ID = THEME_IDS.find((id) => id !== DEFAULT_THEME_ID);++beforeEach(() => {+ // Neutralize the server-sync effect so tests exercise localStorage paths only.+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false, json: async () => ({}) });+});++afterEach(() => {+ vi.restoreAllMocks();+ document.documentElement.removeAttribute('style');+ document.documentElement.removeAttribute('data-port-theme');+ window.localStorage.clear();+});++describe('useTheme localStorage resilience', () => {+ it('initializes to the default theme when reads throw (blocked storage)', () => {+ vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {+ throw new DOMException('The operation is insecure.', 'SecurityError');+ });++ let result;+ // Initial render must not throw even though getItem throws.+ expect(() => {+ ({ result } = renderHook(() => useTheme()));+ }).not.toThrow();++ expect(result.current.themeId).toBe(DEFAULT_THEME_ID);+ });++ it('falls back to the default theme when stored value is invalid', () => {+ window.localStorage.setItem('portos-theme', 'not-a-real-theme');+ const { result } = renderHook(() => useTheme());+ expect(result.current.themeId).toBe(DEFAULT_THEME_ID);+ });++ it('keeps in-memory theme switching functional when writes throw', () => {+ vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');+ });++ const { result } = renderHook(() => useTheme());++ // setTheme writes to localStorage (which throws) but must still update state.+ expect(() => {+ act(() => {+ result.current.setTheme(OTHER_THEME_ID);+ });+ }).not.toThrow();++ expect(result.current.themeId).toBe(OTHER_THEME_ID);+ expect(result.current.theme.id).toBe(OTHER_THEME_ID);+ });++ it('applies a valid stored theme on init when storage is healthy', () => {+ window.localStorage.setItem('portos-theme', OTHER_THEME_ID);+ const { result } = renderHook(() => useTheme());+ expect(result.current.themeId).toBe(OTHER_THEME_ID);+ });+});