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([client-component-tests-for-categoryeditor-promote]): wire vitest infra + UniverseBuilder tests

[._.]/ Adam Eivy30bb489e4c91
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 87f18b34f1..5a204604bf 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,6 +40,9 @@ jobs:
- name: Run server tests
run: npm run test:ci --prefix server
+ - name: Run client tests
+ run: npm test --prefix client
+
- name: Build client
run: npm run build --prefix client
diff --git a/CLAUDE.md b/CLAUDE.md
index 5dbe383e65..e3c91f297a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -17,6 +17,7 @@ npm run dev
# Run tests
cd server && npm test
cd server && npm run test:watch # Watch mode
+cd client && npm test # Vitest (jsdom) — component/unit tests
# PM2 management
pm2 start ecosystem.config.cjs
diff --git a/DONE.md b/DONE.md
index a1327f5ded..80b69a5253 100644
--- a/DONE.md
+++ b/DONE.md
@@ -8,6 +8,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
## 2026-05
+- **[client-component-tests-for-categoryeditor-promote] Client component tests for `CategoryEditor` + `TrunkView`.** Wired up the first vitest-based client test suite (vitest 3 + jsdom + @testing-library/react + user-event) — new `client/vitest.config.js`, `client/src/test/setup.js`, `test` + `test:watch` scripts in `client/package.json`, CI step in `.github/workflows/ci.yml`. Named-exported `CategoryEditor` and `TrunkView` from `client/src/pages/UniverseBuilder.jsx` and added `client/src/pages/UniverseBuilder.test.jsx` covering: promote button disabled when `!canPromote` (parent's `!selectedId`); promote fires directly with no targetKind for a kinded bucket; clicking promote on a `bucketKind: null` ("other") variation opens the trunk picker; clicking a picker option calls `onPromote(variation, { targetKind })` with the correct kind; `TrunkView` "Bulk-render all" button disabled at zero count and enabled with the right count from variations. Three pre-existing orphaned client tests (`cleanPlatePrompt`, `clipboard`, `normalize`) now run too.
- **CoS — explicit `init()` instead of module-level auto-init.** Dropped the `NODE_ENV !== 'test' && VITEST !== 'true'` guard from `server/services/cos.js`; `init` is now exported and called from `server/index.js` alongside the other startup `*.init()` calls. Test imports no longer spin up event listeners / timers as a side effect, and the prod boot path no longer branches on test-env vars.
- **Universe Builder DRY — `resolveProviderAndModel` + `findBibleEntryByName`.** Two shared helpers landed in `server/lib/`. The first collapses four inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains across the universe-builder LLM entrypoints onto one helper; the second consolidates the "case-insensitive name OR alias" predicate at the promote duplicate-collision check. (The retired-characters bucket fold keeps its O(1) seen-set index since it folds entries into a growing array — a per-iteration linear scan would have made it O(n*m).)
- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."
diff --git a/PLAN.md b/PLAN.md
index 1127ac2d7f..b07a23c159 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -11,8 +11,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **Phase B — Expand contract enrichment.** Teach `buildExpansionPrompt()` (`server/services/universeBuilderExpand.js`) to return rich canon arrays (`characters[]`/`settings[]`/`objects[]` with `physicalDescription`/`palette`/`recurringDetails`/`wardrobe`) alongside the existing `categories` (now kind-tagged) + `compositeSheets`. Update `isExpansionShape()` predicate. Client `handleExpand` in `UniverseBuilder.jsx` merges canon entries into the canon arrays parallel to the category merge (dedupe by name, respect per-entry locks). Categories the LLM emits include a `kind` so they land under the right trunk.
- **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.
- **Phase D — Polish & promotion.** ~~"Promote variation to canon" action~~ shipped: `POST /api/universe-builder/:id/promote-variation` LLM-expands a `{label, prompt}` variation into a full canon entry (per-kind `physicalDescription` / `slugline`+`palette` / `description`+`significance`) and atomically writes the canon append + variation removal in one `updateUniverse` patch. CategoryEditor renders a promote button per row; Other-tab buckets open a trunk picker (since `kind: 'other'` can't be auto-resolved). Duplicate-name collisions short-circuit with a 409 before the LLM call. Deferred: client component tests; standalone design doc (not warranted — CLAUDE.md notes + this PR's prose cover the contract).
- - **Phase D follow-ups (deferred from the Phase D PR):**
- - [ ] [client-component-tests-for-categoryeditor-promote] **Client component tests for `CategoryEditor` promote wiring + `TrunkView` button visibility.** Assert promote button disabled when `!selectedId`, picker opens for `kind: 'other'` buckets, picker option click invokes `onPromote` with the correct `targetKind`. No client vitest infra wired for `UniverseBuilder.jsx` yet — add when the page's first spec lands.
- **Phase C follow-ups (deferred from the Phase C PR):**
- [ ] [auto-sort-with-ai-llm-classify-each-kind-other] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.
- [ ] [unify-canoncard-variation-card-into-a-single] **Unify `CanonCard` + variation card into a single `EntryCard`.** Phase C reuses `CanonCard` for canon and `CategoryEditor` for variations inside the same TrunkView. Visual consistency is achieved through shared Tailwind classes; an actual single-component unification (with thumbnail-from-`primaryImageRef`-or-recent-render) is the Phase D card-extraction task.
diff --git a/client/package.json b/client/package.json
index f240b410a1..d6084abfe1 100644
--- a/client/package.json
+++ b/client/package.json
@@ -7,7 +7,9 @@
"dev": "vite --host 0.0.0.0 --port 5554",
"build": "vite build",
"lint": "eslint src --ext .js,.jsx",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "vitest run",
+ "test:watch": "vitest"
},
"dependencies": {
"@dnd-kit/core": "6.3.1",
@@ -29,12 +31,17 @@
"devDependencies": {
"@eslint/js": "9.23.0",
"@tailwindcss/postcss": "4.2.1",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
+ "@testing-library/user-event": "^14.6.1",
"@vitejs/plugin-react": "5.1.4",
"eslint": "9.23.0",
"eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "5.2.0",
+ "jsdom": "^25.0.1",
"tailwindcss": "4.2.1",
- "vite": "7.3.2"
+ "vite": "7.3.2",
+ "vitest": "^3.2.4"
},
"overrides": {
"brace-expansion": "5.0.5",
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 52d202e5b2..728028774f 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -2133,7 +2133,7 @@ const GENERATE_PRESETS = [3, 5, 10];
const GENERATE_CUSTOM_MIN = 1;
const GENERATE_CUSTOM_MAX = 50;
-function CategoryEditor({
+export function CategoryEditor({
category, variations, canRemove = false, onChange, onRemove,
canRender = false, onRenderCategory = null, onRenderVariation = null,
onGenerate = null,
@@ -2855,7 +2855,7 @@ function BucketChipStrip({ buckets, activeBucket, setBucket, showAll = true, ext
// - blank (default "All"): renders canon + every variation under this trunk
// - BUCKET_CANON: renders only canon entries (via the existing UniverseCanonSection)
// - <bucketKey>: renders that bucket's variations via CategoryEditor
-function TrunkView({
+export function TrunkView({
trunk, draft, selectedId, buckets, activeBucket, setBucket,
canRender, canPromote, imageCfg, onUniverseChange,
onRemoveBucket, onUpdateBucket, onGenerateInBucket, onPromoteVariation,
diff --git a/client/src/pages/UniverseBuilder.test.jsx b/client/src/pages/UniverseBuilder.test.jsx
new file mode 100644
index 0000000000..4016cc85b7
--- /dev/null
+++ b/client/src/pages/UniverseBuilder.test.jsx
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+
+import { CategoryEditor, TrunkView } from './UniverseBuilder';
+
+// MemoryRouter wrapper — UniverseBuilder.jsx imports react-router-dom hooks at
+// module scope, so the test harness needs a router context even when the
+// extracted component doesn't read URL state itself.
+const renderWithRouter = (ui) => render(<MemoryRouter>{ui}</MemoryRouter>);
+
+const sampleVariation = { label: 'Rogue navigator', prompt: 'A scrappy navigator with a tarnished sextant.' };
+
+describe('CategoryEditor — promote wiring', () => {
+ const renderEditor = ({ canPromote = true, bucketKind = 'characters', onPromote } = {}) => {
+ renderWithRouter(
+ <CategoryEditor
+ category="heroes"
+ variations={[sampleVariation]}
+ onChange={() => {}}
+ canPromote={canPromote}
+ bucketKind={bucketKind}
+ onPromote={onPromote}
+ />
+ );
+ };
+
+ it('disables the promote button when canPromote is false', () => {
+ renderEditor({ canPromote: false, onPromote: vi.fn() });
+
+ expect(screen.getByRole('button', { name: /Save the universe first to enable promote/i })).toBeDisabled();
+ });
+
+ it('fires onPromote directly with no targetKind for a kinded bucket', async () => {
+ const onPromote = vi.fn().mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderEditor({ onPromote });
+
+ const promoteBtn = screen.getByRole('button', { name: /Promote to canon — LLM expands/i });
+ expect(promoteBtn).toBeEnabled();
+ expect(promoteBtn).not.toHaveAttribute('aria-haspopup');
+
+ await user.click(promoteBtn);
+ expect(onPromote).toHaveBeenCalledExactlyOnceWith(sampleVariation, undefined);
+ });
+
+ it('opens a trunk-picker menu when bucketKind is "other" instead of promoting directly', async () => {
+ const onPromote = vi.fn().mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderEditor({ bucketKind: null, onPromote });
+
+ const promoteBtn = screen.getByRole('button', { name: /Promote to canon — pick a trunk/i });
+ expect(promoteBtn).toHaveAttribute('aria-haspopup', 'menu');
+ expect(promoteBtn).toHaveAttribute('aria-expanded', 'false');
+
+ await user.click(promoteBtn);
+ expect(onPromote).not.toHaveBeenCalled();
+ expect(promoteBtn).toHaveAttribute('aria-expanded', 'true');
+
+ const menu = screen.getByRole('menu');
+ expect(within(menu).getByText(/Promote to canon as/i)).toBeInTheDocument();
+ expect(within(menu).getByRole('menuitem', { name: 'Cast' })).toBeInTheDocument();
+ expect(within(menu).getByRole('menuitem', { name: 'Places' })).toBeInTheDocument();
+ expect(within(menu).getByRole('menuitem', { name: 'Objects' })).toBeInTheDocument();
+ });
+
+ it('clicking a picker option invokes onPromote with the chosen targetKind', async () => {
+ const onPromote = vi.fn().mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderEditor({ bucketKind: null, onPromote });
+
+ await user.click(screen.getByRole('button', { name: /Promote to canon — pick a trunk/i }));
+ await user.click(screen.getByRole('menuitem', { name: 'Places' }));
+
+ expect(onPromote).toHaveBeenCalledExactlyOnceWith(sampleVariation, { targetKind: 'settings' });
+ });
+});
+
+describe('TrunkView — Bulk-render-all button', () => {
+ const baseTrunk = { id: 'cast', kind: 'characters', label: 'Cast' };
+ const noop = () => {};
+ const baseProps = {
+ selectedId: 'u1',
+ activeBucket: 'heroes',
+ setBucket: noop,
+ canRender: true,
+ canPromote: true,
+ imageCfg: null,
+ onUniverseChange: noop,
+ onRemoveBucket: noop,
+ onUpdateBucket: noop,
+ onGenerateInBucket: noop,
+ onPromoteVariation: noop,
+ onBulkRenderBucket: noop,
+ onRenderVariation: noop,
+ onBulkRenderTrunk: noop,
+ onAddBucket: noop,
+ };
+
+ it('disables "Bulk-render all" when the trunk has no canon and no variations', () => {
+ renderWithRouter(
+ <TrunkView
+ {...baseProps}
+ trunk={baseTrunk}
+ draft={{ id: 'u1', characters: [], categories: { heroes: { kind: 'characters', variations: [] } } }}
+ buckets={['heroes']}
+ />
+ );
+
+ const bulkBtn = screen.getByRole('button', { name: /Bulk-render all \(0\)/i });
+ expect(bulkBtn).toBeDisabled();
+ });
+
+ it('enables "Bulk-render all" with the right count when variations exist', () => {
+ renderWithRouter(
+ <TrunkView
+ {...baseProps}
+ trunk={baseTrunk}
+ draft={{
+ id: 'u1',
+ characters: [],
+ categories: {
+ heroes: { kind: 'characters', variations: [{ label: 'a', prompt: 'p' }, { label: 'b', prompt: 'q' }] },
+ villains: { kind: 'characters', variations: [{ label: 'c', prompt: 'r' }] },
+ },
+ }}
+ buckets={['heroes', 'villains']}
+ />
+ );
+
+ const bulkBtn = screen.getByRole('button', { name: /Bulk-render all \(3\)/i });
+ expect(bulkBtn).toBeEnabled();
+ });
+});
diff --git a/client/src/test/setup.js b/client/src/test/setup.js
new file mode 100644
index 0000000000..01d18c214e
--- /dev/null
+++ b/client/src/test/setup.js
@@ -0,0 +1,7 @@
+import '@testing-library/jest-dom/vitest';
+import { afterEach } from 'vitest';
+import { cleanup } from '@testing-library/react';
+
+afterEach(() => {
+ cleanup();
+});
diff --git a/client/vitest.config.js b/client/vitest.config.js
new file mode 100644
index 0000000000..4dbca5c6ac
--- /dev/null
+++ b/client/vitest.config.js
@@ -0,0 +1,13 @@
+import { defineConfig } from 'vitest/config';
+import react from '@vitejs/plugin-react';
+
+export default defineConfig({
+ plugins: [react()],
+ test: {
+ environment: 'jsdom',
+ globals: true,
+ setupFiles: ['./src/test/setup.js'],
+ css: false,
+ include: ['src/**/*.{test,spec}.{js,jsx}'],
+ },
+});
diff --git a/package.json b/package.json
index 1b94f73442..352917d18d 100644
--- a/package.json
+++ b/package.json
@@ -28,7 +28,7 @@
"setup:ghostty": "node scripts/setup-ghostty.js",
"setup:hooks": "bash scripts/setup-git-hooks.sh",
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
- "test": "npm test --prefix server",
+ "test": "npm test --prefix server && npm test --prefix client",
"theme:check": "node scripts/check-themes.js",
"smoke": "node scripts/smoke-boot.js"
},