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

test([high-tests-add-coverage-for-server-services-shell]): cover server/services/shell.js + feeds.js

[._.]/ Adam Eivy6e27224b4fd4
diff --git a/DONE.md b/DONE.md
index 84eeafaeaf..b245f2b6c5 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +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.
- **[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/PLAN.md b/PLAN.md
index c22a8c8a45..782dc4e5fc 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -56,8 +56,8 @@ _Nothing currently parked — pick the next item from the Backlog._
### Better-audit residue
-- [ ] [high-tests-add-coverage-for-server-services-shell] **[HIGH][TESTS]** Add coverage for `server/services/shell.js` and `server/services/feeds.js` — both have exported functions but no sibling test. Shell drives all terminal sessions; feeds manages subscriptions. (New — surfaced 2026-05-16 replan.)
- [ ] [extract-shared-requiretoolkit-helper] **[LOW][CODE]** Three services now carry an identical private `requireToolkit()` helper that throws `ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — `server/services/providers.js`, `server/services/runner.js`, `server/services/promptService.js`. Three module-level `let aiToolkitInstance = null` declarations all receive the same toolkit object from `server/index.js` via per-service `setAIToolkit(toolkit)` setters. Candidate consolidation: extract to `server/lib/aiToolkitState.js` exporting `setAIToolkitInstance(toolkit)` + `requireToolkit()` so all three services import the same module-level state. Includes barrel + README row per `server/lib/` maintenance rule. Deferred from `[extract-requiretoolkit-pattern-to-runner-js]` — three callers crosses the threshold but the 8-line helper × 3 sites is low-maintenance enough that this can wait for a fourth caller or somebody actually wanting to consolidate.
+- [ ] [feeds-ssrf-ipv6-bracket-hostname-gap] **[MED][SECURITY]** `server/services/feeds.js#isHostSafe` doesn't reliably reject IPv6 literal hostnames like `http://[::1]/feed`. `new URL(...).hostname` returns `'[::1]'` (with brackets), so `net.isIP('[::1]')` returns 0 (brackets aren't valid IP syntax) and execution falls through to `dns.resolve4('[::1]')`. Production DNS typically errors → empty addresses → `return false`, so the loopback is protected *incidentally*, but the protection is fragile (any caching resolver or unusual hosts file could subvert it). Fix: strip surrounding `[…]` brackets before `net.isIP`, add an explicit `if (net.isIP(stripped) === 6) return !isPrivateIP(stripped)` branch, and extend `isPrivateIP` to cover ULA (`fc00::/7`) and link-local (`fe80::/10`) ranges. `isPrivateIP` already handles `::1`/`::`. Surfaced 2026-05-19 while adding feeds.js test coverage; deferred to keep that PR scoped to tests.
### Pipeline — deferred
diff --git a/server/services/feeds.test.js b/server/services/feeds.test.js
new file mode 100644
index 0000000000..db2afd4cbe
--- /dev/null
+++ b/server/services/feeds.test.js
@@ -0,0 +1,373 @@
+import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+let tmpRoot;
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tmpRoot });
+});
+
+const fetchMock = vi.fn();
+vi.mock('../lib/fetchWithTimeout.js', () => ({
+ fetchWithTimeout: (...args) => fetchMock(...args),
+}));
+
+const dnsResolveMock = vi.fn();
+vi.mock('dns/promises', () => ({
+ default: { resolve4: (...args) => dnsResolveMock(...args) },
+ resolve4: (...args) => dnsResolveMock(...args),
+}));
+
+let feeds;
+
+beforeAll(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+beforeEach(async () => {
+ tmpRoot = mkdtempSync(join(tmpdir(), 'portos-feeds-test-'));
+ vi.resetModules();
+ fetchMock.mockReset();
+ dnsResolveMock.mockReset().mockResolvedValue(['93.184.216.34']);
+ feeds = await import('./feeds.js');
+});
+
+afterEach(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+const makeResponse = ({ status = 200, body = '', headers = {} } = {}) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: (k) => headers[k.toLowerCase()] || null },
+ text: async () => body,
+});
+
+const RSS_FIXTURE = `<?xml version="1.0"?>
+<rss version="2.0"><channel>
+<title>Example Feed</title>
+<item>
+ <title>First Post</title>
+ <link>https://example.com/posts/1</link>
+ <description><![CDATA[<p>Hello <b>world</b></p>]]></description>
+ <pubDate>Mon, 18 May 2026 10:00:00 GMT</pubDate>
+ <author>Alice</author>
+</item>
+<item>
+ <title>Second Post</title>
+ <link>https://example.com/posts/2</link>
+ <description>Plain &amp; simple</description>
+ <pubDate>Tue, 19 May 2026 10:00:00 GMT</pubDate>
+ <dc:creator>Bob</dc:creator>
+</item>
+</channel></rss>`;
+
+const ATOM_FIXTURE = `<?xml version="1.0"?>
+<feed xmlns="http://www.w3.org/2005/Atom">
+<title>Atom Source</title>
+<entry>
+ <title>Entry One</title>
+ <link rel="alternate" href="https://example.com/atom/1"/>
+ <summary>summary one</summary>
+ <updated>2026-05-18T12:00:00Z</updated>
+ <author><name>Carol</name></author>
+</entry>
+<entry>
+ <title>Entry Two</title>
+ <link href="https://example.com/atom/2"/>
+ <content>content two</content>
+ <published>2026-05-19T12:00:00Z</published>
+</entry>
+</feed>`;
+
+const FETCH_ERROR = 'Could not fetch feed — check the URL';
+
+describe('getFeeds / getFeedStats — empty state', () => {
+ it('returns empty arrays before any subscriptions', async () => {
+ expect(await feeds.getFeeds()).toEqual([]);
+ expect(await feeds.getFeedStats()).toEqual({ totalFeeds: 0, totalItems: 0, unreadItems: 0 });
+ });
+});
+
+describe('addFeed', () => {
+ it('subscribes to a valid RSS feed and seeds initial items', async () => {
+ fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
+ const result = await feeds.addFeed('https://example.com/rss');
+ expect(result.error).toBeUndefined();
+ expect(result.feed).toMatchObject({
+ url: 'https://example.com/rss',
+ title: 'Example Feed',
+ itemCount: 2,
+ unreadCount: 2,
+ });
+
+ const items = await feeds.getItems({});
+ expect(items).toHaveLength(2);
+ expect(items[0].title).toBe('Second Post');
+ expect(items[0].author).toBe('Bob');
+ expect(items[1].description).toBe('Hello world');
+ });
+
+ it('parses Atom feeds and prefers rel="alternate" link', async () => {
+ fetchMock.mockResolvedValue(makeResponse({ body: ATOM_FIXTURE }));
+ const result = await feeds.addFeed('https://example.com/atom');
+ expect(result.feed.title).toBe('Atom Source');
+ const items = await feeds.getItems({});
+ expect(items.map(i => i.link).sort()).toEqual([
+ 'https://example.com/atom/1',
+ 'https://example.com/atom/2',
+ ]);
+ });
+
+ it('rejects duplicate URLs', async () => {
+ fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
+ await feeds.addFeed('https://example.com/rss');
+ const dup = await feeds.addFeed('https://example.com/rss');
+ expect(dup).toEqual({ error: 'Feed URL already subscribed' });
+ });
+
+ it('returns an error when the fetch returns nothing fetchable', async () => {
+ fetchMock.mockResolvedValue(null);
+ const result = await feeds.addFeed('https://example.com/dead');
+ expect(result).toEqual({ error: FETCH_ERROR });
+ });
+
+ it.each([
+ ['file://', 'file:///etc/passwd'],
+ ['data://', 'data:text/xml,<rss/>'],
+ ])('rejects non-http(s) protocol %s (SSRF guard)', async (_label, url) => {
+ const result = await feeds.addFeed(url);
+ expect(result).toEqual({ error: FETCH_ERROR });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ '127.0.0.1',
+ '10.0.0.1',
+ '192.168.1.1',
+ '172.16.5.5',
+ '169.254.169.254',
+ '0.0.0.0',
+ ])('rejects literal private IPv4 %s without DNS lookup', async (host) => {
+ const result = await feeds.addFeed(`http://${host}/feed`);
+ expect(result).toEqual({ error: FETCH_ERROR });
+ expect(dnsResolveMock).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects hostnames that resolve to a private IP (DNS rebinding guard)', async () => {
+ dnsResolveMock.mockResolvedValue(['10.0.0.42']);
+ const result = await feeds.addFeed('https://evil.example.com/rss');
+ expect(result).toEqual({ error: FETCH_ERROR });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects hostnames with no A records', async () => {
+ dnsResolveMock.mockResolvedValue([]);
+ const result = await feeds.addFeed('https://no-records.example.com/rss');
+ expect(result).toEqual({ error: FETCH_ERROR });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('follows a single safe redirect', 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);
+ });
+
+ it('rejects redirects to private IPs', 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 });
+ });
+
+ it('falls back to the URL hostname when the feed has no <title>', async () => {
+ fetchMock.mockResolvedValue(makeResponse({ body: '<rss><channel></channel></rss>' }));
+ const result = await feeds.addFeed('https://blog.example.com/rss');
+ expect(result.feed.title).toBe('blog.example.com');
+ });
+});
+
+describe('removeFeed', () => {
+ it('removes the feed and all its items', async () => {
+ fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
+ const { feed } = await feeds.addFeed('https://example.com/rss');
+ const result = await feeds.removeFeed(feed.id);
+ expect(result).toEqual({ removed: true });
+ expect(await feeds.getFeeds()).toHaveLength(0);
+ expect(await feeds.getItems({})).toHaveLength(0);
+ });
+
+ it('returns an error for an unknown id', async () => {
+ expect(await feeds.removeFeed('not-real')).toEqual({ error: 'Feed not found' });
+ });
+});
+
+describe('refreshFeed', () => {
+ it('adds only new items (dedupe by link) and bumps lastFetched', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-05-19T10:00:00Z'));
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ const { feed } = await feeds.addFeed('https://example.com/rss');
+ const before = feed.lastFetched;
+
+ vi.setSystemTime(new Date('2026-05-19T10:01:00Z'));
+ const NEXT = RSS_FIXTURE.replace(
+ '</channel></rss>',
+ `<item><title>Third</title><link>https://example.com/posts/3</link><pubDate>Wed, 20 May 2026 10:00:00 GMT</pubDate></item></channel></rss>`,
+ );
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: NEXT }));
+
+ const result = await feeds.refreshFeed(feed.id);
+ expect(result.newCount).toBe(1);
+ 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 () => {
+ expect(await feeds.refreshFeed('missing')).toEqual({ error: 'Feed not found' });
+ });
+
+ it('returns an error when the fetch fails', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ const { feed } = await feeds.addFeed('https://example.com/rss');
+ fetchMock.mockResolvedValueOnce(null);
+ expect(await feeds.refreshFeed(feed.id)).toEqual({ error: 'Could not fetch feed' });
+ });
+});
+
+describe('refreshAllFeeds', () => {
+ it('refreshes every subscribed feed in parallel and counts new items', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ const a = (await feeds.addFeed('https://example.com/rss')).feed;
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: ATOM_FIXTURE }));
+ const b = (await feeds.addFeed('https://example.com/atom')).feed;
+
+ const A_NEXT = RSS_FIXTURE.replace(
+ '</channel></rss>',
+ `<item><title>RSS New</title><link>https://example.com/posts/N</link></item></channel></rss>`,
+ );
+ const B_NEXT = ATOM_FIXTURE.replace(
+ '</feed>',
+ `<entry><title>Atom New</title><link href="https://example.com/atom/N"/><updated>2026-05-20T12:00:00Z</updated></entry></feed>`,
+ );
+ fetchMock.mockImplementation(async (url) =>
+ url.includes('/atom') ? makeResponse({ body: B_NEXT }) : makeResponse({ body: A_NEXT }),
+ );
+
+ const result = await feeds.refreshAllFeeds();
+ expect(result).toMatchObject({ refreshed: 2, newItems: 2, failures: 0 });
+ expect((await feeds.getItems({ feedId: a.id })).map(i => i.title)).toContain('RSS New');
+ expect((await feeds.getItems({ feedId: b.id })).map(i => i.title)).toContain('Atom New');
+ });
+
+ it('counts failures separately when a feed cannot be fetched', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ await feeds.addFeed('https://example.com/rss');
+ fetchMock.mockResolvedValue(null);
+ const result = await feeds.refreshAllFeeds();
+ expect(result.failures).toBe(1);
+ expect(result.newItems).toBe(0);
+ });
+});
+
+const seedTwoFeeds = async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ const a = (await feeds.addFeed('https://example.com/rss')).feed;
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: ATOM_FIXTURE }));
+ const b = (await feeds.addFeed('https://example.com/atom')).feed;
+ return { feedA: a, feedB: b };
+};
+
+describe('getItems', () => {
+ let feedA;
+
+ beforeEach(async () => {
+ ({ feedA } = await seedTwoFeeds());
+ });
+
+ it('filters by feedId', async () => {
+ const aItems = await feeds.getItems({ feedId: feedA.id });
+ expect(aItems).toHaveLength(2);
+ expect(aItems.every(i => i.feedId === feedA.id)).toBe(true);
+ });
+
+ it('filters unread-only', async () => {
+ const items = await feeds.getItems({});
+ await feeds.markItemRead(items[0].id);
+ const unread = await feeds.getItems({ unreadOnly: true });
+ expect(unread).toHaveLength(3);
+ expect(unread.every(i => !i.read)).toBe(true);
+ });
+
+ it('paginates via limit + offset', async () => {
+ expect(await feeds.getItems({ limit: 2 })).toHaveLength(2);
+ expect(await feeds.getItems({ limit: 2, offset: 2 })).toHaveLength(2);
+ expect(await feeds.getItems({ limit: 10, offset: 4 })).toHaveLength(0);
+ });
+
+ it('returns items newest-first across feeds', async () => {
+ const items = await feeds.getItems({});
+ const dates = items.map(i => Date.parse(i.pubDate || i.fetchedAt));
+ for (let i = 1; i < dates.length; i++) {
+ expect(dates[i - 1]).toBeGreaterThanOrEqual(dates[i]);
+ }
+ });
+});
+
+describe('markItemRead / markAllRead', () => {
+ it('marks a single item read', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ await feeds.addFeed('https://example.com/rss');
+ const [item] = await feeds.getItems({});
+ expect(await feeds.markItemRead(item.id)).toEqual({ updated: true });
+ expect((await feeds.getItems({ unreadOnly: true })).find(i => i.id === item.id)).toBeUndefined();
+ });
+
+ it('returns an error for an unknown item id', async () => {
+ expect(await feeds.markItemRead('missing')).toEqual({ error: 'Item not found' });
+ });
+
+ it('marks every item read with no scope', async () => {
+ await seedTwoFeeds();
+ const result = await feeds.markAllRead();
+ expect(result.marked).toBe(4);
+ expect(await feeds.getItems({ unreadOnly: true })).toHaveLength(0);
+ });
+
+ it('marks only the scoped feed when feedId is provided', async () => {
+ const { feedA } = await seedTwoFeeds();
+ const result = await feeds.markAllRead(feedA.id);
+ expect(result.marked).toBe(2);
+ expect(await feeds.getItems({ unreadOnly: true })).toHaveLength(2);
+ });
+});
+
+describe('getFeeds — unread counts', () => {
+ it('reports per-feed unread counts in O(items)', async () => {
+ fetchMock.mockResolvedValueOnce(makeResponse({ body: RSS_FIXTURE }));
+ const { feed } = await feeds.addFeed('https://example.com/rss');
+ const items = await feeds.getItems({ feedId: feed.id });
+ await feeds.markItemRead(items[0].id);
+ const [info] = await feeds.getFeeds();
+ expect(info.unreadCount).toBe(1);
+ });
+});
+
+describe('getFeedStats', () => {
+ it('aggregates totals across feeds', async () => {
+ await seedTwoFeeds();
+ expect(await feeds.getFeedStats()).toEqual({ totalFeeds: 2, totalItems: 4, unreadItems: 4 });
+ });
+});
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
new file mode 100644
index 0000000000..f428a71216
--- /dev/null
+++ b/server/services/shell.test.js
@@ -0,0 +1,371 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+let ptyInstances = [];
+let spawnImpl;
+
+vi.mock('node-pty', () => ({
+ spawn: vi.fn((...args) => spawnImpl(...args)),
+}));
+
+const makeFakePty = () => {
+ const fake = {
+ _dataHandler: null,
+ _exitHandler: null,
+ onData: vi.fn((fn) => { fake._dataHandler = fn; }),
+ onExit: vi.fn((fn) => { fake._exitHandler = fn; }),
+ write: vi.fn(),
+ resize: vi.fn(),
+ kill: vi.fn(),
+ emitData: (chunk) => fake._dataHandler?.(chunk),
+ emitExit: (payload) => fake._exitHandler?.(payload),
+ };
+ ptyInstances.push(fake);
+ return fake;
+};
+
+const defaultSpawn = vi.fn(() => makeFakePty());
+
+const makeSocket = (id = 'sock-A') => ({ id, emit: vi.fn() });
+
+const flushMicrotasks = () => new Promise((resolve) => setImmediate(resolve));
+
+let shell;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ptyInstances = [];
+ spawnImpl = defaultSpawn;
+ defaultSpawn.mockClear();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ shell = await import('./shell.js');
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('createShellSession', () => {
+ it('spawns a PTY and returns a session id', () => {
+ const socket = makeSocket();
+ const id = shell.createShellSession(socket, { shell: '/bin/zsh', cwd: '/tmp', cols: 100, rows: 30 });
+ expect(typeof id).toBe('string');
+ expect(id.length).toBeGreaterThan(0);
+ expect(ptyInstances).toHaveLength(1);
+
+ const pty = vi.mocked(defaultSpawn);
+ expect(pty).toHaveBeenCalledWith('/bin/zsh', [], expect.objectContaining({
+ name: 'xterm-256color',
+ cols: 100,
+ rows: 30,
+ cwd: '/tmp',
+ env: expect.objectContaining({
+ TERM: 'xterm-256color',
+ COLORTERM: 'truecolor',
+ }),
+ }));
+ });
+
+ it('uses sensible defaults for cols/rows/cwd', () => {
+ shell.createShellSession(makeSocket());
+ expect(defaultSpawn).toHaveBeenCalledWith(
+ expect.any(String),
+ [],
+ expect.objectContaining({ cols: 80, rows: 24, cwd: expect.any(String) }),
+ );
+ });
+
+ it('filters env to safe prefixes and merges caller opt-in env', () => {
+ const originalEnv = process.env;
+ process.env = {
+ HOME: '/home/x',
+ PATH: '/usr/bin',
+ MY_SECRET_API_KEY: 'leak-me',
+ };
+ shell.createShellSession(makeSocket(), { env: { CALLER_KEY: 'explicit' } });
+ process.env = originalEnv;
+
+ const spawnCall = defaultSpawn.mock.calls[0];
+ const env = spawnCall[2].env;
+ expect(env.HOME).toBe('/home/x');
+ expect(env.PATH).toBe('/usr/bin');
+ expect(env.MY_SECRET_API_KEY).toBeUndefined();
+ expect(env.CALLER_KEY).toBe('explicit');
+ });
+
+ it('emits shell:error and returns null when max sessions reached', () => {
+ for (let i = 0; i < 5; i++) shell.createShellSession(makeSocket(`s${i}`));
+ const socket = makeSocket('over');
+ const id = shell.createShellSession(socket);
+ expect(id).toBeNull();
+ expect(socket.emit).toHaveBeenCalledWith('shell:error', {
+ error: 'Max 5 shell sessions. Kill an existing session first.',
+ });
+ });
+
+ it('does not throw when over-cap and socket is missing', () => {
+ for (let i = 0; i < 5; i++) shell.createShellSession(makeSocket(`s${i}`));
+ expect(() => shell.createShellSession(null)).not.toThrow();
+ });
+
+ it('returns null and emits when PTY spawn throws', () => {
+ spawnImpl = () => { throw new Error('spawn failed'); };
+ const socket = makeSocket();
+ const id = shell.createShellSession(socket);
+ expect(id).toBeNull();
+ expect(socket.emit).toHaveBeenCalledWith('shell:error', {
+ error: 'Failed to spawn shell: spawn failed',
+ });
+ });
+
+ it('routes PTY output to the attached socket and onData hook', async () => {
+ const onData = vi.fn();
+ const socket = makeSocket();
+ const id = shell.createShellSession(socket, { onData });
+ ptyInstances[0].emitData('hello');
+ await flushMicrotasks();
+ expect(socket.emit).toHaveBeenCalledWith('shell:output', { sessionId: id, data: 'hello' });
+ expect(onData).toHaveBeenCalledWith('hello');
+ });
+
+ 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 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);
+ });
+
+ it('catches synchronous errors from the onData hook without crashing', async () => {
+ const onData = vi.fn(() => { throw new Error('hook explodes'); });
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ shell.createShellSession(makeSocket(), { onData });
+ ptyInstances[0].emitData('boom');
+ await flushMicrotasks();
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('onData'));
+ });
+
+ it('on PTY exit: deletes session, emits shell:exit, runs onExit hook', async () => {
+ const onExit = vi.fn();
+ const socket = makeSocket();
+ const id = shell.createShellSession(socket, { onExit });
+ ptyInstances[0].emitExit({ exitCode: 0 });
+ await flushMicrotasks();
+ expect(shell.getSession(id)).toBeNull();
+ expect(socket.emit).toHaveBeenCalledWith('shell:exit', { sessionId: id, code: 0 });
+ expect(onExit).toHaveBeenCalledWith({ exitCode: 0 });
+ });
+
+ it('schedules initialCommand write after delay', () => {
+ vi.useFakeTimers();
+ const id = shell.createShellSession(makeSocket(), { initialCommand: 'ls', initialCommandDelayMs: 50 });
+ expect(ptyInstances[0].write).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(50);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith('ls\n');
+ expect(shell.getSession(id)).toBeTruthy();
+ vi.useRealTimers();
+ });
+});
+
+describe('attachSession', () => {
+ it('returns null for unknown session id', () => {
+ expect(shell.attachSession('does-not-exist', makeSocket())).toBeNull();
+ });
+
+ it('swaps socket and returns buffered output', () => {
+ const sock1 = makeSocket('sock-A');
+ const id = shell.createShellSession(sock1);
+ ptyInstances[0].emitData('saved');
+ const sock2 = makeSocket('sock-B');
+ const result = shell.attachSession(id, sock2);
+ expect(result).toEqual({ sessionId: id, bufferedOutput: 'saved' });
+ expect(shell.getSession(id).socket).toBe(sock2);
+ });
+
+ it('emits shell:detached on the previous socket when displaced', () => {
+ const sock1 = makeSocket('sock-A');
+ const id = shell.createShellSession(sock1);
+ const sock2 = makeSocket('sock-B');
+ shell.attachSession(id, sock2);
+ expect(sock1.emit).toHaveBeenCalledWith('shell:detached', { sessionId: id, reason: 'attached-elsewhere' });
+ });
+
+ it('claim=true rejects when a different socket holds the session', () => {
+ const sock1 = makeSocket('sock-A');
+ const id = shell.createShellSession(sock1);
+ const sock2 = makeSocket('sock-B');
+ const result = shell.attachSession(id, sock2, { claim: true });
+ expect(result).toEqual({ claimRejected: true });
+ expect(shell.getSession(id).socket).toBe(sock1);
+ expect(sock1.emit).not.toHaveBeenCalledWith('shell:detached', expect.anything());
+ });
+
+ it('claim=true succeeds when re-attaching the same socket', () => {
+ const sock = makeSocket();
+ const id = shell.createShellSession(sock);
+ const result = shell.attachSession(id, sock, { claim: true });
+ expect(result.sessionId).toBe(id);
+ });
+
+ it('claim=true succeeds when the session is unbound', () => {
+ const sock1 = makeSocket('sock-A');
+ const id = shell.createShellSession(sock1);
+ shell.detachSocketSessions(sock1);
+ const sock2 = makeSocket('sock-B');
+ const result = shell.attachSession(id, sock2, { claim: true });
+ expect(result.sessionId).toBe(id);
+ });
+});
+
+describe('listAllSessions', () => {
+ it('reports recipient-relative attached: false for the socket holding the session', () => {
+ const sock = makeSocket();
+ shell.createShellSession(sock);
+ const [info] = shell.listAllSessions(sock);
+ expect(info.attached).toBe(false);
+ });
+
+ it('reports attached: true when a different socket holds the session', () => {
+ const sock = makeSocket('sock-A');
+ shell.createShellSession(sock);
+ const [info] = shell.listAllSessions(makeSocket('sock-B'));
+ expect(info.attached).toBe(true);
+ });
+
+ it('reports attached: false for unbound sessions (recipient-relative or global)', () => {
+ const sock = makeSocket();
+ const id = shell.createShellSession(sock);
+ shell.detachSocketSessions(sock);
+ expect(shell.listAllSessions(makeSocket('any')).find(s => s.sessionId === id).attached).toBe(false);
+ expect(shell.listAllSessions().find(s => s.sessionId === id).attached).toBe(false);
+ });
+
+ it('returns the globally-attached view when forSocket is omitted', () => {
+ const sock = makeSocket();
+ shell.createShellSession(sock);
+ const [info] = shell.listAllSessions();
+ expect(info.attached).toBe(true);
+ });
+
+ it('includes the metadata fields callers consume', () => {
+ const sock = makeSocket();
+ shell.createShellSession(sock, { label: 'task-1', kind: 'agent', agentId: 'a1', command: 'codex' });
+ const [info] = shell.listAllSessions(sock);
+ expect(info).toMatchObject({ label: 'task-1', kind: 'agent', agentId: 'a1', command: 'codex' });
+ expect(typeof info.sessionId).toBe('string');
+ expect(typeof info.createdAt).toBe('number');
+ });
+});
+
+describe('subscribeSessionList / unsubscribeSessionList', () => {
+ it('delivers shell:sessions broadcasts to subscribers', () => {
+ const observer = makeSocket('obs');
+ shell.subscribeSessionList(observer);
+ shell.createShellSession(makeSocket('owner'));
+ const broadcasts = observer.emit.mock.calls.filter(c => c[0] === 'shell:sessions');
+ expect(broadcasts.length).toBeGreaterThan(0);
+ expect(broadcasts[broadcasts.length - 1][1]).toHaveLength(1);
+ });
+
+ it('stops delivering after unsubscribe', () => {
+ const observer = makeSocket('obs');
+ shell.subscribeSessionList(observer);
+ shell.unsubscribeSessionList(observer);
+ shell.createShellSession(makeSocket('owner'));
+ expect(observer.emit).not.toHaveBeenCalledWith('shell:sessions', expect.anything());
+ });
+});
+
+describe('writeToSession / resizeSession', () => {
+ it('writeToSession writes data and returns true', () => {
+ const id = shell.createShellSession(makeSocket());
+ expect(shell.writeToSession(id, 'ls\n')).toBe(true);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith('ls\n');
+ });
+
+ it('writeToSession returns false for missing session', () => {
+ expect(shell.writeToSession('missing', 'x')).toBe(false);
+ });
+
+ it('resizeSession resizes and returns true', () => {
+ const id = shell.createShellSession(makeSocket());
+ expect(shell.resizeSession(id, 120, 40)).toBe(true);
+ expect(ptyInstances[0].resize).toHaveBeenCalledWith(120, 40);
+ });
+
+ it('resizeSession returns false for missing session', () => {
+ expect(shell.resizeSession('missing', 80, 24)).toBe(false);
+ });
+});
+
+describe('killSession', () => {
+ it('kills the PTY, removes the session, fires the onExit hook, broadcasts', async () => {
+ const onExit = vi.fn();
+ const observer = makeSocket('obs');
+ shell.subscribeSessionList(observer);
+ const id = shell.createShellSession(makeSocket('owner'), { onExit });
+ expect(shell.killSession(id)).toBe(true);
+ await flushMicrotasks();
+ expect(ptyInstances[0].kill).toHaveBeenCalled();
+ expect(shell.getSession(id)).toBeNull();
+ expect(onExit).toHaveBeenCalledWith({ exitCode: null, killed: true });
+ const post = observer.emit.mock.calls.filter(c => c[0] === 'shell:sessions').pop();
+ expect(post[1]).toHaveLength(0);
+ });
+
+ it('returns false for an unknown session id', () => {
+ expect(shell.killSession('nope')).toBe(false);
+ });
+});
+
+describe('detachSocketSessions', () => {
+ it('clears socket binding on matching sessions and returns the count', () => {
+ const sock = makeSocket();
+ const id1 = shell.createShellSession(sock);
+ const id2 = shell.createShellSession(sock);
+ shell.createShellSession(makeSocket('other'));
+ expect(shell.detachSocketSessions(sock)).toBe(2);
+ expect(shell.getSession(id1).socket).toBeNull();
+ expect(shell.getSession(id2).socket).toBeNull();
+ });
+
+ it('returns 0 when the socket holds nothing', () => {
+ shell.createShellSession(makeSocket('owner'));
+ expect(shell.detachSocketSessions(makeSocket('stranger'))).toBe(0);
+ });
+
+ it('also unsubscribes the socket from session-list broadcasts', () => {
+ const sock = makeSocket();
+ shell.subscribeSessionList(sock);
+ shell.detachSocketSessions(sock);
+ shell.createShellSession(makeSocket('owner'));
+ const sessionsCalls = sock.emit.mock.calls.filter(c => c[0] === 'shell:sessions');
+ expect(sessionsCalls).toHaveLength(0);
+ });
+});
+
+describe('getSession / getSessionProcess / getSessionCount', () => {
+ it('getSession returns the session record or null', () => {
+ const id = shell.createShellSession(makeSocket());
+ expect(shell.getSession(id)).toMatchObject({ pty: expect.any(Object) });
+ expect(shell.getSession('missing')).toBeNull();
+ });
+
+ it('getSessionProcess returns the PTY or null', () => {
+ const id = shell.createShellSession(makeSocket());
+ expect(shell.getSessionProcess(id)).toBe(ptyInstances[0]);
+ expect(shell.getSessionProcess('missing')).toBeNull();
+ });
+
+ it('getSessionCount tracks active sessions', () => {
+ expect(shell.getSessionCount()).toBe(0);
+ shell.createShellSession(makeSocket());
+ shell.createShellSession(makeSocket());
+ expect(shell.getSessionCount()).toBe(2);
+ });
+});