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(test): wrap out-of-act state updates to clear CI React act() warnings
Adam Eivyc613e1560339
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 37f79d661a..c411609cf2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Fixed+- **Client test suite no longer floods CI with React "not wrapped in act(...)" warnings.** Across eight component/page suites, state updates were being driven outside `act()` — hand-fired mock-EventSource frames (`emit`/`fail`), raw DOM `.blur()` calls, manually-invoked tracker callbacks, and resolved in-flight gates whose follow-up `setState` landed after the test body returned (plus a few synchronous tests whose mount-time fetches resolved late). These surfaced only under CI's verbose reporter (the default reporter hides console output), so they were invisible locally. Each driving call is now wrapped in `act()` (or switched to `fireEvent`, which wraps internally), and synchronous tests that mount components with async effects now flush inside `act()`. The full client suite (2497 tests) runs clean with zero act warnings. (`PipelineManuscriptEditor`, `Layout`, `WidgetSuggestions`, `ApiAccessTab`, `PitchTuner`, `SongTraining`, `AudioStage`, `LocalLlmPlayground` test suites)- **Codex TUI CoS agents no longer get stuck in the sandbox.** The shipped Codex TUI provider pinned `--ask-for-approval never`, which silences approval prompts but leaves Codex's *sandbox* at its default (`workspace-write`) — so headless agents couldn't reach the network (`gh`/`npm`/`git fetch` failed) and could still hit surprise escalation prompts mid-run. Because an explicit `--ask-for-approval` flag also suppressed the auto-injected full-bypass, the shipped default actively defeated the headless posture the CLI codex path already uses. The default now ships `--dangerously-bypass-approvals-and-sandbox` (approvals off + sandbox off + network on), and migration 121 rewrites existing installs whose args still match the old default — custom Codex flags are left untouched.- AI provider context-window planning is now model-aware: known Claude model windows are used after explicit provider overrides and before local `num_ctx`, and the provider settings UI shows/edits the planning window so mixed-model providers no longer collapse to one blunt 128K budget.- **AI fixers can no longer take down the whole server with `pm2 kill`.** PortOS runs every managed app under one shared pm2 daemon, so `pm2 kill` / `pm2 delete all` stops *everything* — including PortOS itself. A "Fix with AI" / autofixer agent (which runs its CLI fully unrestricted) could be talked into running one while trying to "restart the app." Three layers now block this: (1) the shell-command allowlist (`validateCommand`) rejects `pm2 kill`/`startup`/`unstartup` and any `pm2 <verb> all` for the manual command runner and autonomous jobs; (2) spawned AI agents (CoS tasks, the autofixer app) get a guarded `pm2` shim prepended to their PATH that intercepts those same destructive subcommands before they reach the real pm2 — a hard guard that holds even under `--dangerously-skip-permissions`; (3) every agent prompt now states the shared-daemon rule and to only `pm2 restart <its-own-process>`. Scoped commands (`pm2 restart my-app`, `pm2 logs my-app`, `pm2 list`) still work.diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex a9c79ce648..17490a80b9 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { render, screen, within } from '@testing-library/react';+import { render, screen, within, act } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';import { PINNED_KEY } from '../utils/navWorkingSet.js';@@ -60,12 +60,19 @@ vi.mock('../services/api', () => ({import Layout from './Layout';-const renderLayout = (initialPath = '/brain/inbox') =>- render(+const renderLayout = async (initialPath = '/brain/inbox') => {+ const utils = render(<MemoryRouter initialEntries={[initialPath]}><Layout /></MemoryRouter>,);+ // The sidebar's dynamic sections fire async fetches (all mocked empty here).+ // Flush their resolution inside act() so the resulting setState lands within+ // the React lifecycle instead of after the test body returns (which warns+ // "update … not wrapped in act").+ await act(async () => {});+ return utils;+};// The Pinned region carries a stable `data-testid` so assertions scope to it// without depending on the heading's DOM nesting (a benign style refactor of the@@ -83,9 +90,9 @@ afterEach(() => {});describe('Layout — pinned single nav rows', () => {- it('renders a pinned top-level single row (Dashboard) in the Pinned section', () => {+ it('renders a pinned top-level single row (Dashboard) in the Pinned section', async () => {localStorage.setItem(PINNED_KEY, JSON.stringify(['/']));- renderLayout();+ await renderLayout();const pinned = pinnedSection();expect(pinned).toBeTruthy();@@ -96,9 +103,9 @@ describe('Layout — pinned single nav rows', () => {expect(within(pinned).getByRole('button', { name: /^Unpin Dashboard$/i })).toBeTruthy();});- it('resolves every top-level single row by path into the Pinned section', () => {+ it('resolves every top-level single row by path into the Pinned section', async () => {localStorage.setItem(PINNED_KEY, JSON.stringify(['/', '/review', '/city', '/goals/list']));- renderLayout();+ await renderLayout();const pinned = pinnedSection();expect(within(pinned).getByRole('link', { name: /Dashboard/i })).toHaveAttribute('href', '/');@@ -107,18 +114,18 @@ describe('Layout — pinned single nav rows', () => {expect(within(pinned).getByRole('link', { name: /Goals/i })).toHaveAttribute('href', '/goals/list');});- it('omits the Pinned section entirely when nothing is pinned', () => {- renderLayout();+ it('omits the Pinned section entirely when nothing is pinned', async () => {+ await renderLayout();expect(pinnedSection()).toBeNull();});- it('filters out an unknown pinned path while keeping the known one', () => {+ it('filters out an unknown pinned path while keeping the known one', async () => {// A stored path that maps to no nav leaf and no manifest entry resolves to// null and is dropped by resolveNavEntry; a known path beside it still renders.// Asserting the survivor (not just absence) proves the filter, not merely that// the section failed to render.localStorage.setItem(PINNED_KEY, JSON.stringify(['/this/path/does/not/exist', '/city']));- renderLayout();+ await renderLayout();const pinned = pinnedSection();expect(pinned).toBeTruthy();diff --git a/client/src/components/dashboard/WidgetSuggestions.test.jsx b/client/src/components/dashboard/WidgetSuggestions.test.jsxindex e00289ff6c..6a283b0cbd 100644--- a/client/src/components/dashboard/WidgetSuggestions.test.jsx+++ b/client/src/components/dashboard/WidgetSuggestions.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, act } from '@testing-library/react';import WidgetSuggestions from './WidgetSuggestions';// `quick-stats` ships with gate: (s) => s.apps.length > 0 — a deterministic@@ -36,13 +36,16 @@ describe('WidgetSuggestions', () => {expect(screen.getByText(/Quick Stats/)).toBeDefined();});- it('calls onAdd with only the widget id — no layout shape passed', () => {+ it('calls onAdd with only the widget id — no layout shape passed', async () => {const onAdd = vi.fn().mockResolvedValue();render(<WidgetSuggestions presentWidgetIds={['cos']} dashboardState={populatedState} onAdd={onAdd} />);fireEvent.click(screen.getByLabelText('Add Quick Stats to layout'));expect(onAdd).toHaveBeenCalledTimes(1);expect(onAdd).toHaveBeenCalledWith('quick-stats');expect(onAdd.mock.calls[0]).toHaveLength(1);+ // add() clears `submitting` in a .finally() microtask after onAdd resolves —+ // flush it inside act() so that setState doesn't land after the test returns.+ await act(async () => {});});it('dismissing a suggestion hides it for the lifetime of the mount', () => {@@ -64,7 +67,8 @@ describe('WidgetSuggestions', () => {// first added widget.expect(onAdd).toHaveBeenCalledTimes(1);expect(onAdd).toHaveBeenCalledWith('quick-stats');- resolveFirst();- await Promise.resolve();+ // Resolving the in-flight add clears `submitting` in a .finally() microtask;+ // flush it inside act() so the setState is wrapped.+ await act(async () => { resolveFirst(); });});});diff --git a/client/src/components/pipeline/stages/AudioStage.test.jsx b/client/src/components/pipeline/stages/AudioStage.test.jsxindex 971bebd5d0..079d6b00f0 100644--- a/client/src/components/pipeline/stages/AudioStage.test.jsx+++ b/client/src/components/pipeline/stages/AudioStage.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, within } from '@testing-library/react';+import { render, screen, waitFor, within, fireEvent, act } from '@testing-library/react';import userEvent from '@testing-library/user-event';vi.mock('../../../services/api', () => ({@@ -97,11 +97,14 @@ describe('AudioStage — whole-episode audio (#863)', () => {await waitFor(() => expect(onStageUpdate).toHaveBeenCalledWith('audio', updated.stages.audio, updated));});- it('shows the cue panel only in generated mode', () => {+ it('shows the cue panel only in generated mode', async () => {const { rerender } = render(<AudioStage issue={makeIssue()} onStageUpdate={() => {}} />);expect(screen.queryByText('Music cues')).not.toBeInTheDocument();rerender(<AudioStage issue={makeIssue({ audioMode: 'generated' })} onStageUpdate={() => {}} />);expect(screen.getByText('Music cues')).toBeInTheDocument();+ // The mount-time music-engine status fetch resolves asynchronously; flush it+ // inside act() so its setState doesn't land after the test returns.+ await act(async () => {});});it('derives cues via the generate route', async () => {@@ -177,11 +180,11 @@ describe('AudioStage — whole-episode audio (#863)', () => {const ta0 = within(screen.getByText('Act I').closest('li')).getByRole('textbox');await userEvent.clear(ta0);await userEvent.type(ta0, 'a1');- ta0.blur();+ fireEvent.blur(ta0); // fireEvent wraps in act; raw ta0.blur() would notconst ta1 = within(screen.getByText('Act II').closest('li')).getByRole('textbox');await userEvent.clear(ta1);await userEvent.type(ta1, 'b1');- ta1.blur();+ fireEvent.blur(ta1);// Drive the lifted issue back in so the second save's tail reads it.await waitFor(() => expect(updatePipelineIssue).toHaveBeenCalledTimes(2));@@ -237,7 +240,7 @@ describe('AudioStage — whole-episode audio (#863)', () => {// trackFilename, proving the save merged against the post-render array.const ta = within(cueItem).getByRole('textbox');await userEvent.type(ta, ' more');- ta.blur();+ fireEvent.blur(ta);await waitFor(() => expect(updatePipelineIssue).toHaveBeenCalled());const savedCues = updatePipelineIssue.mock.calls.at(-1)[1].stages.audio.cues;expect(savedCues[0].trackFilename).toBe('cue.wav');diff --git a/client/src/components/settings/ApiAccessTab.test.jsx b/client/src/components/settings/ApiAccessTab.test.jsxindex 9b95000fc2..c5c2c2d42b 100644--- a/client/src/components/settings/ApiAccessTab.test.jsx+++ b/client/src/components/settings/ApiAccessTab.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';vi.mock('../../services/apiSystem', () => ({getSettings: vi.fn(),@@ -84,7 +84,9 @@ describe('ApiAccessTab', () => {expect(toggles[1].disabled).toBe(true);});- resolveSave({}); // let the save settle so the test exits cleanly+ // Let the save settle inside act() so the post-save setState (clearing the+ // in-flight flag) is wrapped rather than firing after the test returns.+ await act(async () => { resolveSave({}); });});it('reverts optimistic state when the save fails', async () => {diff --git a/client/src/components/songs/PitchTuner.test.jsx b/client/src/components/songs/PitchTuner.test.jsxindex be075e7179..18d3cd3fba 100644--- a/client/src/components/songs/PitchTuner.test.jsx+++ b/client/src/components/songs/PitchTuner.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';// Web Audio doesn't exist in jsdom, so mock the two lib seams the tuner uses:// `createStreamAnalyser` (graph off a stream) and `createPitchTracker` (the rAF@@ -51,7 +51,8 @@ describe('PitchTuner', () => {it('renders the detected note + cents from a tracker update', async () => {render(<PitchTuner stream={fakeStream()} />);- lastOnUpdate({ note: { letter: 'A', accidental: '', octave: 4 }, cents: 3 });+ // The tracker's onUpdate callback drives setState; invoke it inside act().+ act(() => lastOnUpdate({ note: { letter: 'A', accidental: '', octave: 4 }, cents: 3 }));await waitFor(() => expect(screen.getByText('A4')).toBeTruthy());expect(screen.getByText(/\+3¢ · In tune/)).toBeTruthy();});diff --git a/client/src/components/songs/SongTraining.test.jsx b/client/src/components/songs/SongTraining.test.jsxindex 2f1e475dde..8a476c30c3 100644--- a/client/src/components/songs/SongTraining.test.jsx+++ b/client/src/components/songs/SongTraining.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, act } from '@testing-library/react';// Drive the component off a mocked training hook so we don't need a real mic /// AudioContext (neither exists in jsdom). The hook + the pure progress math are@@ -44,7 +44,7 @@ describe('SongTraining', () => {expect(options.some((o) => /Chorus/.test(o))).toBe(true);});- it('shows a Start button that triggers a run after the mic opens', () => {+ it('shows a Start button that triggers a run after the mic opens', async () => {// getUserMedia isn't in jsdom — provide a stub the component awaits.const getUserMedia = vi.fn().mockResolvedValue({ getTracks: () => [] });Object.defineProperty(global.navigator, 'mediaDevices', {@@ -53,6 +53,9 @@ describe('SongTraining', () => {render(<SongTraining score={SCORE} />);fireEvent.click(screen.getByRole('button', { name: /start/i }));expect(getUserMedia).toHaveBeenCalled();+ // The Start handler awaits getUserMedia then arms the run via setState —+ // flush that resolution inside act() so it doesn't fire after the test returns.+ await act(async () => {});});it('renders progress for trained scopes', () => {diff --git a/client/src/pages/LocalLlmPlayground.test.jsx b/client/src/pages/LocalLlmPlayground.test.jsxindex 71b9b6c934..25266e3b38 100644--- a/client/src/pages/LocalLlmPlayground.test.jsx+++ b/client/src/pages/LocalLlmPlayground.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';vi.mock('../services/api', () => ({@@ -117,7 +117,9 @@ describe('LocalLlmPlayground', () => {await waitFor(() => expect(screen.getByText('Processing')).toBeTruthy());expect(screen.queryByText(/In memory/)).toBeNull();- releaseRun();+ // Releasing the run resolves the stream promise, which settles the result+ // state — flush it inside act() so that update is wrapped.+ await act(async () => { releaseRun(); });});it('renders a live "Thinking" block for streamed reasoning, separate from the answer', async () => {@@ -147,6 +149,8 @@ describe('LocalLlmPlayground', () => {// The streaming answer renders the content channel only — reasoning isn't mixed in.await waitFor(() => expect(screen.getByText('Final answer.')).toBeTruthy());- releaseRun();+ // Releasing the run resolves the stream promise, which settles the result+ // state — flush it inside act() so that update is wrapped.+ await act(async () => { releaseRun(); });});});diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsxindex cb7f6ad41e..bb8984bbc7 100644--- a/client/src/pages/PipelineManuscriptEditor.test.jsx+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';+import { render, screen, waitFor, fireEvent, within, act } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router-dom';import { MockEventSource, lastEventSource as lastEs } from '../test/mockEventSource';@@ -381,7 +381,10 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {// Let the deferred SSE-open effect flush + close inside the test (while the// EventSource stub is live) so it can't throw during teardown.await waitFor(() => expect(MockEventSource.instances.length).toBeGreaterThan(0));- lastEs().emit({ type: 'canceled' });+ // Driving the mock stream by hand fires the EventSource handlers synchronously,+ // which call setState in useSseProgress — wrap in act() so those updates flush+ // inside the React lifecycle (no "not wrapped in act" warning).+ act(() => lastEs().emit({ type: 'canceled' }));});it('on the complete frame, re-fetches the review so comments arrive with fixes (diff + Accept, no Generate fix)', async () => {@@ -404,7 +407,7 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {await waitFor(() => expect(MockEventSource.instances.length).toBeGreaterThan(0));// Drive the terminal frame; the editor re-fetches the review.- lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 });+ act(() => lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 }));await waitFor(() => expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(2));// The comment now carries a fix → the in-context card shows Accept, not "Generate fix".@@ -424,7 +427,7 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {fireEvent.click(screen.getByLabelText(/Generate edits for every finding/i));fireEvent.click(screen.getByText('Run editorial review'));await waitFor(() => expect(MockEventSource.instances.length).toBe(1));- lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 });+ act(() => lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 }));await waitFor(() => expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(2));// Run 1's button is back to idle.await screen.findByText('Run editorial review');@@ -441,7 +444,7 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(2);// Run 2's own complete frame drives the real re-fetch (3rd call).- lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 });+ act(() => lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 }));await waitFor(() => expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(3));});@@ -458,7 +461,7 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {await screen.findByText(/Starting editorial review|Drafting edits/);// Connection drops with no complete/canceled/error frame.- lastEs().fail();+ act(() => lastEs().fail());// Recovery: button re-enables (no longer stuck) and the review is re-fetched.expect(await screen.findByText('Run editorial review')).toBeInTheDocument();