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: stop shadowing the global setInterval in CreateLoopForm (#5728)
Adam Eivy633b373a056c
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.mdindex 28e3a915e8..ec137b069b 100644--- a/client/src/AGENTS.md+++ b/client/src/AGENTS.md@@ -16,6 +16,7 @@ These apply to React/Vite client code. Universal constraints (functional program- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: a surface that OWNS a key spreads `noPointerFocusSurfaceProps` on its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember.- **Web Storage goes through `lib/safeStorage.js`** - `localStorage`/`sessionStorage` **throw** rather than returning null in Safari private browsing, with cookies disabled, in a sandboxed iframe, and at quota — and in several of those the object still exists, so `typeof sessionStorage === 'undefined'` is not a guard and neither is `?.` (it only covers a null base, not a throwing `getItem`). Use `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` and their `Json` and `*Session` variants. This is not a lost-preference nit: a raw read in a **render body** is a render-phase exception that unmounts the whole route, and a raw write in an effect kills the flow mid-session (#5689). Enforced tree-wide by `client/src/storageConventions.test.js`.- **Interval polling goes through `useAutoRefetch`** - a view that re-fetches on a timer uses `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` (`hooks/useAutoRefetch.js`), never a hand-rolled `useEffect` + `setInterval`. The hook skips its tick while `document.visibilityState === 'hidden'` and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate as `enabled` rather than an early `return`, and pass `immediate: false` when another effect already owns the first fetch. Enforced tree-wide by `client/src/pollingConventions.test.js`, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll).+- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback## API errors and save gatingdiff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsxindex 5eba95f6b4..22112c0f01 100644--- a/client/src/components/apps/ReferenceReposPanel.jsx+++ b/client/src/components/apps/ReferenceReposPanel.jsx@@ -63,7 +63,7 @@ export default function ReferenceReposPanel({ appId, appName }) {// failure doesn't blank the list — stale-but-valid is far better UX// than "no refs configured" appearing when the server hiccups.const [fetchError, setFetchError] = useState(null);- const fetch = useCallback(async () => {+ const loadRefs = useCallback(async () => {setRefreshing(true);const res = await api.listReferenceRepos(appId).catch((e) => ({ __error: e?.message || 'Failed to load references' }));if (res && res.__error) {@@ -77,8 +77,8 @@ export default function ReferenceReposPanel({ appId, appName }) {}, [appId]);useEffect(() => {- fetch();- }, [fetch]);+ loadRefs();+ }, [loadRefs]);useEffect(() => {let cancelled = false;@@ -93,7 +93,7 @@ export default function ReferenceReposPanel({ appId, appName }) {if (!created) return;toast.success(`Added "${created.name}"`);setShowAdd(false);- fetch();+ loadRefs();};// Two-click delete per AGENTS.md "no window.confirm". First click arms the@@ -134,13 +134,13 @@ export default function ReferenceReposPanel({ appId, appName }) {// ones (they may not be; the failed check might've been triggered// by upstream HEAD moving).setSnapshots((prev) => { const n = { ...prev }; delete n[ref.id]; return n; });- fetch();+ loadRefs();return;}setSnapshots((prev) => ({ ...prev, [ref.id]: snap }));if (snap.stale) {toast.error(`${ref.name}: latest check failed — showing the saved result from ${formatDateTime(snap.fetchedAt)}. Retry before relying on it.`);- fetch();+ loadRefs();return;}const commitMsg = `${ref.name}: ${snap.commitCount} new commit${snap.commitCount === 1 ? '' : 's'}`;@@ -155,7 +155,7 @@ export default function ReferenceReposPanel({ appId, appName }) {} else {toast.success(commitMsg);}- fetch();+ loadRefs();};const handleMarkReviewed = async (ref) => {@@ -175,7 +175,7 @@ export default function ReferenceReposPanel({ appId, appName }) {if (!ok) return;toast.success(`Marked ${ref.name} reviewed up to ${sha.slice(0, 8)}`);setSnapshots((prev) => { const n = { ...prev }; delete n[ref.id]; return n; });- fetch();+ loadRefs();};const handleSaveNotes = async (ref, nextNotes) => {@@ -187,7 +187,7 @@ export default function ReferenceReposPanel({ appId, appName }) {.catch((e) => { toast.error(e.message || 'Update failed'); return false; });if (!ok) return;setEditingNotesId(null);- fetch();+ loadRefs();};if (initialLoading) {diff --git a/client/src/globalShadowConventions.test.js b/client/src/globalShadowConventions.test.jsnew file mode 100644index 0000000000..e914866cb9--- /dev/null+++ b/client/src/globalShadowConventions.test.js@@ -0,0 +1,142 @@+// @vitest-environment node++/**+ * Repo-wide guard: no local binding shadows a global whose shadowing fails silently.+ *+ * `CreateLoopForm` held `const [interval, setInterval] = useState('10m')` (#5728),+ * and `RunnerPage` held `const [timeout, setTimeout] = useState(30)`. Either one+ * shadows the timer API for the whole component body, so a timer added to that+ * component later — a countdown, a debounce, a poll — calls the React state+ * setter with a function and a number instead of scheduling anything. Nothing+ * throws: `setTimeout(fn, 1000)` just stores `fn` as the timeout value and+ * re-renders. `ReferenceReposPanel` had the same shape with `const fetch =+ * useCallback(...)`, which turns a stray `fetch(url)` into a zero-arg reload.+ *+ * That failure mode — a call that compiles, runs, and does the wrong thing with+ * no error — is what scopes the list below. It is deliberately NOT "every+ * global": `const [open, setOpen]`, `const [status, setStatus]`, and+ * `const [name, setName]` appear in dozens of components and are idiomatic+ * React. They shadow `window.open` / `window.status` / `window.name`, but+ * nothing in this tree calls those bare, and banning them would buy an+ * allowlist longer than the rule. The names here are the ones that are+ * routinely called as bare functions in view code, so shadowing one is a live+ * trap rather than a naming quibble.+ *+ * ## What this guard CANNOT see+ *+ * It is a source scan, not an AST pass:+ * - Function parameters and `catch` bindings are not checked, only+ * `const` / `let` / `var` declarations (including destructuring).+ * - A banned name written only inside a comment or a template literal that+ * happens to match a declaration shape would count.+ * - Re-assignment of an import alias to a banned name is invisible.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { trackedSourceFiles } from './test/trackedFiles.js';++const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/**+ * Globals that view code calls bare, so a same-named local binding silently+ * redirects the call instead of failing. Keep this list to that property —+ * a global nobody calls unqualified belongs in a lint rule, not here.+ */+const BANNED = new Set([+ 'setInterval',+ 'clearInterval',+ 'setTimeout',+ 'clearTimeout',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'fetch',+]);++/** `const foo =`, `let foo`, `var foo` — a plain (non-destructured) binding. */+const PLAIN_DECL = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*[=;]/g;++/** `const [a, b] = …` / `const { a, b: c } = …` — the destructuring head. */+const DESTRUCTURED_DECL = /\b(?:const|let|var)\s*([[{][^\]}]*[\]}])\s*=/g;++/**+ * Names a destructuring pattern actually binds. For `{ a: b }` that is `b`, not+ * `a` — renaming an incoming `fetch` field to something else is the fix, not+ * the violation, so keying on the left half would report it backwards.+ */+function boundNames(pattern) {+ return pattern+ .slice(1, -1)+ .split(',')+ .map((part) => part.split(':').pop())+ .map((part) => part.replace(/=.*$/s, ''))+ .map((part) => part.replace(/^\s*\.\.\./, '').trim())+ .filter((part) => /^[A-Za-z_$][\w$]*$/.test(part));+}++/** Every banned global a source declares as a local binding. */+function shadowedGlobals(source) {+ const found = new Set();+ for (const [, name] of source.matchAll(PLAIN_DECL)) {+ if (BANNED.has(name)) found.add(name);+ }+ for (const [, pattern] of source.matchAll(DESTRUCTURED_DECL)) {+ for (const name of boundNames(pattern)) {+ if (BANNED.has(name)) found.add(name);+ }+ }+ return [...found];+}++describe('no local binding shadows a silently-failing global', () => {+ it('has no shadowed timer or fetch global in client/src', () => {+ const files = trackedSourceFiles(CLIENT_ROOT);+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise+ // make this guard pass by scanning nothing at all.+ expect(files.length).toBeGreaterThan(100);++ const violations = files+ .map((file) => [file, shadowedGlobals(readFileSync(join(CLIENT_ROOT, file), 'utf8'))])+ .filter(([, names]) => names.length > 0)+ .map(([file, names]) => `${file}: ${names.join(', ')}`);++ expect(+ violations,+ 'These files bind a global that view code calls bare, so the next call to it '+ + 'in the same scope silently hits the local instead — no error, no throw.\n'+ + 'Fix: rename the binding for what it holds (`intervalPreset` / '+ + '`timeoutMinutes` / `loadRefs`), not for the API it collides with.\n'+ + 'There is deliberately no allowlist: every one of these names has a better '+ + `local name.\nOffenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ // Guards the guard: a detector that stopped recognizing the shape would make+ // the scan above vacuously green and let the bug class walk back in.+ it('recognizes a shadowing declaration in each of its forms', () => {+ expect(shadowedGlobals("const [interval, setInterval] = useState('10m');")).toEqual(['setInterval']);+ expect(shadowedGlobals('const [timeout, setTimeout] = useState(30);')).toEqual(['setTimeout']);+ expect(shadowedGlobals('const fetch = useCallback(async () => {}, []);')).toEqual(['fetch']);+ expect(shadowedGlobals('let clearTimeout;')).toEqual(['clearTimeout']);+ expect(shadowedGlobals('const { fetch } = window;')).toEqual(['fetch']);+ // Renaming an incoming field OUT of the collision is the fix, not a violation.+ expect(shadowedGlobals('const { fetch: doFetch } = window;')).toEqual([]);+ // …and renaming one INTO the collision still is one.+ expect(shadowedGlobals('const { load: fetch } = deps;')).toEqual(['fetch']);+ });++ it('leaves non-shadowing code alone', () => {+ expect(shadowedGlobals("const [intervalPreset, setIntervalPreset] = useState('10m');")).toEqual([]);+ expect(shadowedGlobals('const [timeoutMinutes, setTimeoutMinutes] = useState(30);')).toEqual([]);+ expect(shadowedGlobals('const loadRefs = useCallback(async () => {}, []);')).toEqual([]);+ // Calling the real global is the whole point of keeping the name free.+ expect(shadowedGlobals('const t = setTimeout(run, 1000);')).toEqual([]);+ expect(shadowedGlobals('clearTimeout(t);')).toEqual([]);+ // Idiomatic React state deliberately outside the list — see the header.+ expect(shadowedGlobals('const [open, setOpen] = useState(false);')).toEqual([]);+ expect(shadowedGlobals('const [status, setStatus] = useState(null);')).toEqual([]);+ expect(shadowedGlobals('const [name, setName] = useState("");')).toEqual([]);+ });+});diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsxindex 143abecad2..ce4145fd9e 100644--- a/client/src/pages/Loops.jsx+++ b/client/src/pages/Loops.jsx@@ -43,7 +43,7 @@ function StatusBadge({ loop }) {function CreateLoopForm({ providers, onCreated, promptRef }) {const [prompt, setPrompt] = useState('');- const [interval, setIntervalPreset] = useState('10m');+ const [intervalPreset, setIntervalPreset] = useState('10m');const [customInterval, setCustomInterval] = useState('');const [name, setName] = useState('');const [providerId, setProviderId] = useState('');@@ -60,7 +60,7 @@ function CreateLoopForm({ providers, onCreated, promptRef }) {setCreating(true);const data = {prompt: prompt.trim(),- interval: customInterval || interval,+ interval: customInterval || intervalPreset,name: name.trim() || undefined,cwd: cwd.trim() || undefined,providerId: providerId || undefined,@@ -104,7 +104,7 @@ function CreateLoopForm({ providers, onCreated, promptRef }) {type="button"onClick={() => { setIntervalPreset(p.value); setCustomInterval(''); }}className={`px-2 py-1 text-xs rounded border ${- interval === p.value && !customInterval+ intervalPreset === p.value && !customInterval? 'border-port-accent bg-port-accent/20 text-port-accent': 'border-port-border text-gray-400 hover:border-gray-500'}`}diff --git a/client/src/pages/RunnerPage.jsx b/client/src/pages/RunnerPage.jsxindex bc5bd89823..15d5286aa3 100644--- a/client/src/pages/RunnerPage.jsx+++ b/client/src/pages/RunnerPage.jsx@@ -23,7 +23,7 @@ export function RunnerPage() {const [providers, setProviders] = useState([]);const [selectedProvider, setSelectedProvider] = useState('');const [selectedModel, setSelectedModel] = useState('');- const [timeout, setTimeout] = useState(30);+ const [timeoutMinutes, setTimeoutMinutes] = useState(30);const [allowedCommands, setAllowedCommands] = useState([]);const [screenshots, setScreenshots] = useState([]);const [continueContext, setContinueContext] = useState(null);@@ -190,7 +190,7 @@ ${prompt.trim()}`;// ran in the PortOS directory instead of rejecting the misconfigured app// it was pointed at (#3180).workspaceName: selectedApp?.name,- timeout: timeout * 60 * 1000, // Convert minutes to milliseconds+ timeout: timeoutMinutes * 60 * 1000, // Convert minutes to millisecondsscreenshots: screenshots.map(s => s.path) // Include screenshot paths}).catch(err => ({ error: err.message }));@@ -388,8 +388,8 @@ ${prompt.trim()}`;<Clock size={16} className="text-gray-400" /><selectaria-label="Timeout"- value={timeout}- onChange={(e) => setTimeout(Number(e.target.value))}+ value={timeoutMinutes}+ onChange={(e) => setTimeoutMinutes(Number(e.target.value))}className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"><option value={5}>5 min</option>