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([high-tests-add-coverage-for-server-services-shell]): address codex review
[._.]/ Adam Eivy1d27827d2214
diff --git a/DONE.md b/DONE.mdindex b245f2b6c5..d935aedf4d 100644--- a/DONE.md+++ b/DONE.md@@ -10,7 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-19-- **[high-tests-add-coverage-for-server-services-shell] Add coverage for `server/services/shell.js` and `server/services/feeds.js`.** Both services had exported functions but no sibling test. New `shell.test.js` (36 cases) pins the full PTY-session lifecycle: `createShellSession` (allow-listed env filtering with caller opt-in, defaults, max-session cap with + without socket, spawn-failure path, PTY output → socket emit + onData hook, 50KB ring-buffer trim, hook sync-error logging path, PTY exit cleanup, deferred `initialCommand` write); `attachSession` (unknown id, socket swap + bufferedOutput replay, `shell:detached` emit on displaced socket, claim-true displacement reject + same-socket re-attach + unbound take-over); `listAllSessions` (recipient-relative `attached` true/false/global view, metadata fields); `subscribeSessionList`/`unsubscribeSessionList` broadcast wiring; `writeToSession`/`resizeSession`/`killSession` happy + miss paths; `detachSocketSessions` count + list-subscriber unsubscribe; `getSession`/`getSessionProcess`/`getSessionCount`. Uses a captured PTY fake (records `onData`/`onExit` handlers so tests can fire them) and `vi.resetModules()` per case so the module-level `shellSessions` map starts empty. New `feeds.test.js` (29 cases) covers `parseRSS` + `parseAtom` paths through `addFeed` (RSS title + CDATA strip + `dc:creator` fallback, Atom `rel="alternate"` link preference, hostname fallback when feed `<title>` empty), SSRF guards (non-http(s) protocols, literal private IPv4 — `127.0.0.1`/`10.x`/`172.16-31.x`/`192.168.x`/`169.254.x`/`0.0.0.0` — assert without DNS lookup, DNS-resolved private IP rejection, empty DNS records rejection), redirect handling (single safe redirect followed, private-IP redirect rejected), CRUD + lifecycle (`removeFeed`, `refreshFeed` dedupe + lastFetched update + missing/unfetchable errors, `refreshAllFeeds` parallel-fetch + failure counting), and read paths (`getItems` feedId/unreadOnly/limit+offset/newest-first invariant, `markItemRead` + `markAllRead` scoped + unscoped, `getFeeds` unread counts, `getFeedStats`). Reuses `mockPathsDataRoot` from `server/lib/` for the temp-dir/PATHS.data redirect; mocks `fetchWithTimeout` for canned XML and `dns.resolve4` for SSRF paths. One real-world SSRF gap surfaced while writing tests — `http://[::1]/feed` slips past `isHostSafe` because `URL.hostname` returns the bracketed form, captured in PLAN.md as `[feeds-ssrf-ipv6-bracket-hostname-gap]`. All 65 new tests pass.+- **[high-tests-add-coverage-for-server-services-shell] Add coverage for `server/services/shell.js` and `server/services/feeds.js`.** Both services had exported functions but no sibling test. New `shell.test.js` (36 cases) pins the full PTY-session lifecycle: `createShellSession` (allow-listed env filtering with caller opt-in, defaults, max-session cap with + without socket, spawn-failure path, PTY output → socket emit + onData hook, 50KB ring-buffer trim with newest-retained assertion, hook sync-error logging path, PTY exit cleanup, deferred `initialCommand` write); `attachSession` (unknown id, socket swap + bufferedOutput replay, `shell:detached` emit on displaced socket, claim-true displacement reject + same-socket re-attach + unbound take-over); `listAllSessions` (recipient-relative `attached` true/false/global view, metadata fields); `subscribeSessionList`/`unsubscribeSessionList` broadcast wiring; `writeToSession`/`resizeSession`/`killSession` happy + miss paths; `detachSocketSessions` count + list-subscriber unsubscribe; `getSession`/`getSessionProcess`/`getSessionCount`. Uses a captured PTY fake (records `onData`/`onExit` handlers so tests can fire them) and `vi.resetModules()` per case so the module-level `shellSessions` map starts empty. New `feeds.test.js` (35 cases) covers `parseRSS` + `parseAtom` paths through `addFeed` (RSS title + CDATA strip + `dc:creator` fallback, Atom `rel="alternate"` preference verified against a sibling `rel="self"` link, hostname fallback when feed `<title>` empty), SSRF guards (non-http(s) protocols, literal private IPv4 — `127.0.0.1`/`10.x`/`172.16-31.x`/`192.168.x`/`169.254.x`/`0.0.0.0` — assert without DNS lookup, DNS-resolved private IP rejection, empty DNS records rejection), redirect handling (safe redirect followed to the named URL with `redirect: 'error'`, private-IP redirect rejected before the second fetch fires), CRUD + lifecycle (`removeFeed`, `refreshFeed` dedupe + `lastFetched` bump via fake timers + missing/unfetchable errors, `refreshAllFeeds` parallel-fetch + failure counting), and read paths (`getItems` feedId/unreadOnly/limit+offset/newest-first invariant, `markItemRead` + `markAllRead` scoped + unscoped, `getFeeds` unread counts, `getFeedStats`). Reuses `makePathsProxy` from `server/lib/mockPathsDataRoot.js` (function-form `dataRoot` so each test gets a fresh tmpdir for isolation); mocks `fetchWithTimeout` for canned XML and `dns.resolve4` for SSRF paths. Per-file `console.log`/`console.warn` suppression drops the feeds suite from ~6s to ~90ms. One real-world SSRF gap surfaced while writing tests — `http://[::1]/feed` slips past `isHostSafe` because `URL.hostname` returns the bracketed form, captured in PLAN.md as `[feeds-ssrf-ipv6-bracket-hostname-gap]`. All 71 new tests pass.- **[codex5-network-exposure-ui] Network Exposure dashboard widget.** New `server/lib/networkExposure.js` snapshots boot-frozen exposure state (scheme + bind + cert mode from `meta.json` + Tailscale hostname + loopback mirror port) and a new `GET /api/network-exposure/status` route surfaces it. New `client/src/components/NetworkExposureWidget.jsx` renders an at-a-glance HTTPS/HTTP badge, bind audience (loopback-only / all-interfaces / specific-interface), Tailscale-trusted cert vs. self-signed pill, loopback HTTP mirror link, and a mic-availability hint computed client-side from `window.location.protocol` + loopback-host check. Flags an actionable warning when the server is bound on all interfaces over plain HTTP. Registered in `widgetRegistry.jsx` with `MicroGlyph` chrome and seeded into the `default` (Everything) and `ops` built-in layouts so the security posture is visible product UX, not a docs-only invariant. Two `/simplify` follow-ups deferred to PLAN: extract a shared `readCertMeta()` helper (third independent meta.json reader landed) and hoist `isLoopbackHost` to `client/src/lib/loopbackHost.js`.- **[extract-requiretoolkit-pattern-to-runner-js] Extend `requireToolkit()` pattern to `server/services/runner.js` + `promptService.js`.** The 13 inlined `if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized')` sites in `runner.js` (across `createRun`, `finalizeRunRecord`, `executeCliRun`, `executeApiRun`, `registerActiveRun`, `stopRun`, `getRun`, `getRunOutput`, `getRunPrompt`, `listRuns`, `deleteRun`, `deleteFailedRuns`, `isRunActive`) plus 12 sibling sites in `promptService.js` (across `loadPrompts`, `getStages`, `getStage`, `getStageTemplate`, `updateStageTemplate`, `updateStageConfig`, `getVariables`, `getVariable`, `updateVariable`, `createVariable`, `deleteVariable`, `buildPrompt`) now go through a private `requireToolkit()` helper that throws `new ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — mirroring the helper `providers.js` already exports. Promoting `promptService.js` to the typed-error shape too was a /simplify finding from this PR — leaving prompt-service failures on the untyped string-throw while runner + providers were typed would have left callers (e.g. `visionTest.js`'s `err.code === 'AI_TOOLKIT_NOT_INITIALIZED'` gate) unable to discriminate by source. In runner.js, multi-use callsites (`finalizeRunRecord`, `executeCliRun`, `stopRun`, `registerActiveRun`) hoist `const toolkit = requireToolkit()` once so the `aiToolkitInstance.services.X` chains collapse to `toolkit.services.X` without re-checking. `unregisterActiveRun` is unchanged — its optional-chained `.delete` is deliberately best-effort cleanup that runs from child-process teardown callbacks and must not throw. Error message string preserved verbatim so `server/lib/promptRunner.test.js`'s `rejects.toThrow(/AI Toolkit not initialized/)` regex still matches. Follow-up deferred to PLAN.md as `[extract-shared-requiretoolkit-helper]` — three copies of the 8-line helper now exist; extract to `server/lib/aiToolkitState.js` when a 4th caller appears or somebody wants to consolidate. All 5832 server tests pass.- **[move-usenextevalcountdown-to-hooks] Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** Relocated `client/src/components/cos/useNextEvalCountdown.js` (1s-tick countdown to the next CoS evaluation) to `client/src/hooks/useNextEvalCountdown.js` to conform to the CLAUDE.md "Module Organization" rule that `useX` hooks live exclusively under `client/src/hooks/`. Dropped the re-export from `components/cos/index.js`, added the catalog row to `client/src/hooks/README.md` (Apps / Sessions / Domain), and added the barrel re-export to `client/src/hooks/index.js`. Only consumer (`client/src/pages/ChiefOfStaff.jsx`) now imports the hook directly from `../hooks/useNextEvalCountdown`, matching the existing direct-import pattern it already uses for `useSocket` and `useLocalStorageBool`. Pure relocation — no behavioral changes. All 154 client tests pass (the `hooks/index.test.js` barrel-shape invariant test confirms the move is correctly wired).diff --git a/server/services/feeds.test.js b/server/services/feeds.test.jsindex db2afd4cbe..bbf2fbe75c 100644--- a/server/services/feeds.test.js+++ b/server/services/feeds.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -29,6 +29,10 @@ beforeAll(() => {vi.spyOn(console, 'warn').mockImplementation(() => {});});+afterAll(() => {+ vi.restoreAllMocks();+});+beforeEach(async () => {tmpRoot = mkdtempSync(join(tmpdir(), 'portos-feeds-test-'));vi.resetModules();@@ -38,6 +42,7 @@ beforeEach(async () => {});afterEach(() => {+ vi.useRealTimers();rmSync(tmpRoot, { recursive: true, force: true });});@@ -72,6 +77,7 @@ const ATOM_FIXTURE = `<?xml version="1.0"?><title>Atom Source</title><entry><title>Entry One</title>+ <link rel="self" href="https://example.com/atom/1.self"/><link rel="alternate" href="https://example.com/atom/1"/><summary>summary one</summary><updated>2026-05-18T12:00:00Z</updated>@@ -174,20 +180,24 @@ describe('addFeed', () => {expect(fetchMock).not.toHaveBeenCalled();});- it('follows a single safe redirect', async () => {+ it('follows a single safe redirect to the new URL', async () => {fetchMock.mockResolvedValueOnce(makeResponse({ status: 302, headers: { location: 'https://example.com/final.xml' } })).mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));const result = await feeds.addFeed('https://example.com/redirect');expect(result.error).toBeUndefined();expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1][0]).toBe('https://example.com/final.xml');+ expect(fetchMock.mock.calls[1][1].redirect).toBe('error');});- it('rejects redirects to private IPs', async () => {+ it('rejects redirects to private IPs without making the second fetch', async () => {dnsResolveMock.mockImplementation(async (host) => host === 'evil.example.com' ? ['10.0.0.1'] : ['93.184.216.34']);fetchMock.mockResolvedValueOnce(makeResponse({ status: 302, headers: { location: 'https://evil.example.com/x' } }));const result = await feeds.addFeed('https://example.com/redirect');expect(result).toEqual({ error: FETCH_ERROR });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(dnsResolveMock).toHaveBeenCalledWith('evil.example.com');});it('falls back to the URL hostname when the feed has no <title>', async () => {@@ -232,7 +242,6 @@ describe('refreshFeed', () => {expect(result.feed.itemCount).toBe(3);expect(result.feed.lastFetched).not.toBe(before);expect((await feeds.getItems({ feedId: feed.id })).map(i => i.title)).toContain('Third');- vi.useRealTimers();});it('returns an error when the feed id is unknown', async () => {diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex f428a71216..5f15222645 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -42,6 +42,7 @@ beforeEach(async () => {});afterEach(() => {+ vi.useRealTimers();vi.restoreAllMocks();});@@ -130,15 +131,19 @@ describe('createShellSession', () => {it('buffers output and trims oldest chunks past 50KB', () => {const id = shell.createShellSession(makeSocket());- const big = 'x'.repeat(20 * 1024);- ptyInstances[0].emitData(big);- ptyInstances[0].emitData(big);- ptyInstances[0].emitData(big);+ const oldest = 'A'.repeat(20 * 1024);+ const middle = 'B'.repeat(20 * 1024);+ const newest = 'C'.repeat(20 * 1024);+ ptyInstances[0].emitData(oldest);+ ptyInstances[0].emitData(middle);+ ptyInstances[0].emitData(newest);const session = shell.getSession(id);expect(session.bufferSize()).toBeLessThanOrEqual(50 * 1024);const result = shell.attachSession(id, makeSocket('sock-B'));- expect(result.bufferedOutput.length).toBeLessThanOrEqual(50 * 1024);+ expect(result.bufferedOutput).not.toContain('A');+ expect(result.bufferedOutput).toContain(middle);+ expect(result.bufferedOutput).toContain(newest);});it('catches synchronous errors from the onData hook without crashing', async () => {