Skip to content

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

fix: guard useCitySettings localStorage on the theme-switch path (#2387)

Adam Eivy4f64c29fb5d6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9dccfcc4c1..afc27db774 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` 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.
+- **[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.
- **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.js
index 65cf438185..481a7848e5 100644
--- a/client/src/hooks/useCitySettings.js
+++ b/client/src/hooks/useCitySettings.js
@@ -48,10 +48,45 @@ 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 = localStorage.getItem(STORAGE_KEY);
+ const saved = safeReadStorage(STORAGE_KEY);
if (!saved) return DEFAULT_SETTINGS;
- return { ...DEFAULT_SETTINGS, ...JSON.parse(saved) };
+ let parsed;
+ try {
+ parsed = JSON.parse(saved);
+ } catch {
+ return DEFAULT_SETTINGS; // Corrupt stored JSON — fall back to defaults.
+ }
+ if (!parsed || typeof parsed !== 'object') return DEFAULT_SETTINGS;
+ return { ...DEFAULT_SETTINGS, ...parsed };
};
export { QUALITY_PRESETS };
@@ -64,7 +99,7 @@ export default function useCitySettings() {
setSettings(prev => {
if (prev.timeOfDay === 'auto') return prev;
const next = { ...prev, timeOfDay: 'auto' };
- localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
return next;
});
};
@@ -77,17 +112,17 @@ export default function useCitySettings() {
// If changing quality preset, apply bulk changes
if (key === 'qualityPreset' && QUALITY_PRESETS[value]) {
const next = { ...prev, qualityPreset: value, ...QUALITY_PRESETS[value] };
- localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
return next;
}
const next = { ...prev, [key]: value };
- localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
return next;
});
}, []);
const resetSettings = useCallback(() => {
- localStorage.removeItem(STORAGE_KEY);
+ safeRemoveStorage(STORAGE_KEY);
setSettings(DEFAULT_SETTINGS);
}, []);
diff --git a/client/src/hooks/useCitySettings.test.jsx b/client/src/hooks/useCitySettings.test.jsx
new file mode 100644
index 0000000000..0c7837139f
--- /dev/null
+++ b/client/src/hooks/useCitySettings.test.jsx
@@ -0,0 +1,72 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import useCitySettings, { TIME_OF_DAY_AUTO_EVENT } from './useCitySettings.js';
+
+const STORAGE_KEY = 'portos-city-settings';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ window.localStorage.clear();
+});
+
+describe('useCitySettings localStorage resilience', () => {
+ it('initializes to defaults when reads throw (blocked storage)', () => {
+ vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {
+ throw new DOMException('The operation is insecure.', 'SecurityError');
+ });
+
+ let result;
+ expect(() => {
+ ({ result } = renderHook(() => useCitySettings()));
+ }).not.toThrow();
+
+ const [settings] = result.current;
+ expect(settings.timeOfDay).toBe('auto');
+ expect(settings.qualityPreset).toBe('high');
+ });
+
+ it('initializes to defaults when stored JSON is corrupt', () => {
+ window.localStorage.setItem(STORAGE_KEY, '{ not valid json');
+ const { result } = renderHook(() => useCitySettings());
+ const [settings] = result.current;
+ expect(settings.qualityPreset).toBe('high');
+ });
+
+ it('keeps in-memory setting updates working when writes throw', () => {
+ vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');
+ });
+
+ const { result } = renderHook(() => useCitySettings());
+
+ expect(() => {
+ act(() => {
+ const [, updateSetting] = result.current;
+ updateSetting('timeOfDay', 'night');
+ });
+ }).not.toThrow();
+
+ const [settings] = result.current;
+ expect(settings.timeOfDay).toBe('night');
+ });
+
+ it('handles the time-of-day-auto event without throwing when writes fail', () => {
+ // This is the listener fired by useTheme.setTheme; with storage blocked its
+ // write must not surface an unhandled error on the theme-switch path.
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ timeOfDay: 'night' }));
+ vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');
+ });
+
+ const { result } = renderHook(() => useCitySettings());
+
+ expect(() => {
+ act(() => {
+ window.dispatchEvent(new Event(TIME_OF_DAY_AUTO_EVENT));
+ });
+ }).not.toThrow();
+
+ const [settings] = result.current;
+ expect(settings.timeOfDay).toBe('auto');
+ });
+});
diff --git a/client/src/hooks/useTheme.js b/client/src/hooks/useTheme.js
index c7a6408ad0..32b3f72eb6 100644
--- a/client/src/hooks/useTheme.js
+++ b/client/src/hooks/useTheme.js
@@ -91,10 +91,12 @@ export default function useTheme() {
const serverTheme = settings?.theme ? normalizeThemeId(settings.theme) : null;
const currentSaved = normalizeThemeId(safeReadStorage(STORAGE_KEY));
if (serverTheme && serverTheme !== currentSaved) {
- safeWriteStorage(STORAGE_KEY, serverTheme);
- resetCityTimeOfDayOverride();
+ // Apply the in-memory theme first so a failing persistence/side-effect
+ // path can't leave the UI on the stale theme.
applyTheme(serverTheme);
setThemeId(serverTheme);
+ safeWriteStorage(STORAGE_KEY, serverTheme);
+ resetCityTimeOfDayOverride();
}
})
.catch((err) => {
@@ -107,10 +109,12 @@ export default function useTheme() {
const setTheme = useCallback((id) => {
userPickedRef.current = true;
const normalized = normalizeThemeId(id);
- safeWriteStorage(STORAGE_KEY, normalized);
- resetCityTimeOfDayOverride();
+ // Apply the in-memory theme (DOM + state) first so persistence or side-effect
+ // failures never leave switching non-functional (issue #2387).
applyTheme(normalized);
setThemeId(normalized);
+ safeWriteStorage(STORAGE_KEY, normalized);
+ resetCityTimeOfDayOverride();
fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },