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([issue-3284]): make the 127-stage Prompt Manager list searchable and groupable
[._.]/ Adam Eivy88b686af9b47
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 75379f4870..1ac47a7b1e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -147,6 +147,7 @@ grep -i "what you want to do" client/src/lib/README.md| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |+| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention, falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`. `stageHaystack(key, config)`, `isSystemStage(key)` / `SYSTEM_STAGE_KEYS` (cosmetic mirror of the server's `systemStages` table — deletion is guarded server-side). Pure — no React, no I/O. || `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. || `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. || `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order — it does NOT render a `manifest` group: each runtime atlas's sidecar manifest is folded onto its atlas row as `row.manifest`, and other behind-the-scenes JSON is omitted. `runtimeVersionDir(path)` / `isRuntimeVersionPath(path)` / `isRuntimeSidecarManifest(path)` expose the `runtime/vN` grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like `AssetInspector` reuse one definition instead of re-regexing. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex dfdf9c9eb4..141c8d11fe 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -109,6 +109,7 @@ export * from './midiPlayback.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';export * from './powersBreakdown.js';+export * from './promptStageGroups.js';export * from './referenceAnalysis.js';export * from './scoreNotation.js';export * from './scorePlayback.js';diff --git a/client/src/lib/promptStageGroups.js b/client/src/lib/promptStageGroups.jsnew file mode 100644index 0000000000..5a02bafd3c--- /dev/null+++ b/client/src/lib/promptStageGroups.js@@ -0,0 +1,128 @@+/**+ * Prompt-stage search + grouping for the Prompt Manager's Stages pane (#3284).+ *+ * The stage list is 120+ entries deep and the taxonomy is already encoded in the+ * display names — `Pipeline — Prose Draft`, `Writers Room — Live Continuation`,+ * `CoS Agent Briefing`. These helpers turn that convention into navigable+ * structure: an AND-token filter over title + description + key, then ordered+ * groups keyed on the name's prefix.+ *+ * Token semantics are shared with the media browser (`mediaSearch.js`) rather+ * than re-rolled — same "every whitespace term must match somewhere" contract+ * users already learned there.+ *+ * Pure — no React, no I/O. The page owns the disclosure state and icons.+ */++import { tokenizeQuery, matchHaystack } from './mediaSearch.js';++// Stages PortOS features call by name. Mirror of the `systemStages` table in+// `server/routes/prompts.js` — the server is authoritative for *deletion*+// (it force-guards on its own copy); this copy only drives the SYSTEM badge and+// the SYSTEM-only filter, so a drift here is cosmetic, never destructive.+export const SYSTEM_STAGE_KEYS = [+ 'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',+ 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',+ 'memory-evaluate', 'app-detection',+];++const SYSTEM_STAGE_SET = new Set(SYSTEM_STAGE_KEYS);++export function isSystemStage(key) {+ return SYSTEM_STAGE_SET.has(key);+}++// Bucket for names that carry neither a dash prefix nor a known leading word.+export const OTHER_GROUP_LABEL = 'Other';++// Most names encode their family as `<Family> — <specific>` (em or en dash).+const DASH_PREFIX_RE = /^(.+?)\s[—–]\s/;++// Families whose names predate the dash convention (`CoS Agent Briefing`,+// `Brain Classifier`). Matched as a leading WORD run so `Model Personality`+// wins over a hypothetical `Model` — longest-first ordering is what makes that+// deterministic, so keep multi-word entries above their prefixes.+export const STAGE_WORD_PREFIXES = [+ 'Model Personality',+ 'App Detection',+ 'Brain',+ 'CoS',+ 'Memory',+ 'Soul',+ 'Twin',+];++/**+ * The group a stage belongs to, derived from its display name (falling back to+ * its key when a stage has no name). Hyphens normalize to spaces first so a+ * name-less `cos-evaluate` still lands under CoS rather than in Other.+ */+export function stageGroupLabel(displayName) {+ const name = String(displayName || '').trim();+ if (!name) return OTHER_GROUP_LABEL;++ const dashed = DASH_PREFIX_RE.exec(name);+ if (dashed) {+ const prefix = dashed[1].trim();+ if (prefix) return prefix;+ }++ const normalized = name.replace(/-/g, ' ').toLowerCase();+ for (const prefix of STAGE_WORD_PREFIXES) {+ const needle = prefix.toLowerCase();+ if (normalized === needle || normalized.startsWith(`${needle} `)) return prefix;+ }+ return OTHER_GROUP_LABEL;+}++/**+ * The lowercased searchable string for one stage. Title and description are+ * what the issue asks for; the raw key rides along so a user who knows the+ * stage id (`brain-daily-digest`) can type it directly.+ */+export function stageHaystack(key, config) {+ return `${config?.name || ''} ${config?.description || ''} ${key || ''}`.toLowerCase();+}++/**+ * Filter + group the stage map for the Stages pane.+ *+ * `stages` is the `{ key: config }` map the prompts API returns. Returns+ * `{ groups, matchCount, totalCount }` where each group is+ * `{ label, stages: [[key, config], …] }` — groups sorted alphabetically with+ * `Other` pinned last, stages sorted by display name within a group.+ *+ * An empty query and `systemOnly: false` return everything, so the same call+ * drives both the unfiltered and the filtered render.+ */+export function buildStageGroups(stages, { query = '', systemOnly = false } = {}) {+ const entries = Object.entries(stages || {});+ const tokens = tokenizeQuery(query);++ const matched = entries.filter(([key, config]) => {+ if (systemOnly && !isSystemStage(key)) return false;+ if (tokens.length === 0) return true;+ return matchHaystack(stageHaystack(key, config), tokens);+ });++ const byLabel = new Map();+ for (const entry of matched) {+ const label = stageGroupLabel(entry[1]?.name || entry[0]);+ const list = byLabel.get(label);+ if (list) list.push(entry); else byLabel.set(label, [entry]);+ }++ const groups = [...byLabel.entries()]+ .map(([label, list]) => ({+ label,+ stages: list.sort(([aKey, a], [bKey, b]) =>+ String(a?.name || aKey).localeCompare(String(b?.name || bKey))),+ }))+ .sort((a, b) => {+ if (a.label === OTHER_GROUP_LABEL) return b.label === OTHER_GROUP_LABEL ? 0 : 1;+ if (b.label === OTHER_GROUP_LABEL) return -1;+ return a.label.localeCompare(b.label);+ });++ return { groups, matchCount: matched.length, totalCount: entries.length };+}diff --git a/client/src/lib/promptStageGroups.test.js b/client/src/lib/promptStageGroups.test.jsnew file mode 100644index 0000000000..ce417ac544--- /dev/null+++ b/client/src/lib/promptStageGroups.test.js@@ -0,0 +1,170 @@+import { describe, it, expect } from 'vitest';+import {+ buildStageGroups,+ stageGroupLabel,+ stageHaystack,+ isSystemStage,+ SYSTEM_STAGE_KEYS,+ OTHER_GROUP_LABEL,+} from './promptStageGroups.js';++const stage = (name, description = '') => ({ name, description });++describe('stageGroupLabel', () => {+ it('takes the prefix before an em-dash', () => {+ expect(stageGroupLabel('Creative Director — Treatment')).toBe('Creative Director');+ expect(stageGroupLabel('Pipeline — Reader Panel: The Editor')).toBe('Pipeline');+ });++ it('splits on the FIRST dash so a dashed suffix stays in the name', () => {+ expect(stageGroupLabel('Pipeline — Reverse Outline — v2')).toBe('Pipeline');+ });++ it('accepts an en-dash separator too', () => {+ expect(stageGroupLabel('Importer – Analyze')).toBe('Importer');+ });++ it('ignores hyphens that are not the separator', () => {+ expect(stageGroupLabel('Twin Spoken-vs-Written Comparison')).toBe('Twin');+ });++ it('falls back to a known leading word for pre-dash names', () => {+ expect(stageGroupLabel('CoS Agent Briefing')).toBe('CoS');+ expect(stageGroupLabel('Brain Daily Digest')).toBe('Brain');+ expect(stageGroupLabel('App Detection')).toBe('App Detection');+ });++ it('prefers the longest matching word prefix', () => {+ expect(stageGroupLabel('Model Personality Self-Profile')).toBe('Model Personality');+ });++ it('matches a word prefix on a hyphenated stage key', () => {+ expect(stageGroupLabel('cos-evaluate')).toBe('CoS');+ expect(stageGroupLabel('brain-classifier')).toBe('Brain');+ });++ it('does not match a word prefix mid-name', () => {+ expect(stageGroupLabel('Values-Alignment Scorer')).toBe(OTHER_GROUP_LABEL);+ });++ it('degrades to Other for empty / unknown names', () => {+ expect(stageGroupLabel('')).toBe(OTHER_GROUP_LABEL);+ expect(stageGroupLabel(null)).toBe(OTHER_GROUP_LABEL);+ expect(stageGroupLabel('Wholly Novel Thing')).toBe(OTHER_GROUP_LABEL);+ });+});++describe('isSystemStage', () => {+ it('recognizes the mirrored server list', () => {+ for (const key of SYSTEM_STAGE_KEYS) expect(isSystemStage(key)).toBe(true);+ });+ it('is false for user stages', () => {+ expect(isSystemStage('pipeline-prose-draft')).toBe(false);+ expect(isSystemStage(undefined)).toBe(false);+ });+});++describe('stageHaystack', () => {+ it('covers title, description and key, lowercased', () => {+ const h = stageHaystack('brain-daily-digest', stage('Brain Daily Digest', 'Summarize the day'));+ expect(h).toContain('brain daily digest');+ expect(h).toContain('summarize the day');+ expect(h).toContain('brain-daily-digest');+ });++ it('tolerates a missing config', () => {+ expect(stageHaystack('lonely-key', undefined)).toContain('lonely-key');+ });+});++describe('buildStageGroups', () => {+ const stages = {+ 'pipeline-prose-draft': stage('Pipeline — Prose Draft', 'Draft the prose'),+ 'pipeline-comic-script': stage('Pipeline — Comic Book Script', 'Panels and balloons'),+ 'creative-director-treatment': stage('Creative Director — Treatment', 'Treatment doc'),+ 'cos-evaluate': stage('CoS Task Evaluation', 'Grade a task'),+ 'brain-classifier': stage('Brain Classifier', 'Classify a thought'),+ 'values-alignment-scorer': stage('Values-Alignment Scorer', 'Score alignment'),+ };++ it('returns every stage grouped when unfiltered', () => {+ const { groups, matchCount, totalCount } = buildStageGroups(stages);+ expect(totalCount).toBe(6);+ expect(matchCount).toBe(6);+ expect(groups.map(g => g.label)).toEqual([+ 'Brain', 'CoS', 'Creative Director', 'Pipeline', OTHER_GROUP_LABEL,+ ]);+ });++ it('pins Other last regardless of alphabetical position', () => {+ const { groups } = buildStageGroups(stages);+ expect(groups[groups.length - 1].label).toBe(OTHER_GROUP_LABEL);+ });++ it('sorts stages by display name within a group', () => {+ const { groups } = buildStageGroups(stages);+ const pipeline = groups.find(g => g.label === 'Pipeline');+ expect(pipeline.stages.map(([, c]) => c.name)).toEqual([+ 'Pipeline — Comic Book Script',+ 'Pipeline — Prose Draft',+ ]);+ });++ it('filters on the title', () => {+ const { groups, matchCount } = buildStageGroups(stages, { query: 'comic' });+ expect(matchCount).toBe(1);+ expect(groups).toHaveLength(1);+ expect(groups[0].stages[0][0]).toBe('pipeline-comic-script');+ });++ it('filters on the description', () => {+ const { matchCount, groups } = buildStageGroups(stages, { query: 'balloons' });+ expect(matchCount).toBe(1);+ expect(groups[0].stages[0][0]).toBe('pipeline-comic-script');+ });++ it('filters on the stage key', () => {+ const { matchCount } = buildStageGroups(stages, { query: 'values-alignment' });+ expect(matchCount).toBe(1);+ });++ it('is case-insensitive and AND-joins terms', () => {+ expect(buildStageGroups(stages, { query: 'PIPELINE PROSE' }).matchCount).toBe(1);+ expect(buildStageGroups(stages, { query: 'pipeline treatment' }).matchCount).toBe(0);+ });++ it('treats a whitespace-only query as no filter', () => {+ expect(buildStageGroups(stages, { query: ' ' }).matchCount).toBe(6);+ });++ it('narrows to system stages when systemOnly is set', () => {+ const { groups, matchCount, totalCount } = buildStageGroups(stages, { systemOnly: true });+ expect(totalCount).toBe(6);+ expect(matchCount).toBe(2);+ expect(groups.flatMap(g => g.stages.map(([k]) => k)).sort()).toEqual(['brain-classifier', 'cos-evaluate']);+ });++ it('composes systemOnly with a query', () => {+ const { matchCount } = buildStageGroups(stages, { query: 'classify', systemOnly: true });+ expect(matchCount).toBe(1);+ expect(buildStageGroups(stages, { query: 'prose', systemOnly: true }).matchCount).toBe(0);+ });++ it('returns no groups but a real total when nothing matches', () => {+ const { groups, matchCount, totalCount } = buildStageGroups(stages, { query: 'zzzz' });+ expect(groups).toEqual([]);+ expect(matchCount).toBe(0);+ expect(totalCount).toBe(6);+ });++ it('handles an empty / missing stage map', () => {+ expect(buildStageGroups({})).toEqual({ groups: [], matchCount: 0, totalCount: 0 });+ expect(buildStageGroups(null).totalCount).toBe(0);+ expect(buildStageGroups(undefined).groups).toEqual([]);+ });++ it('groups a name-less stage by its key', () => {+ const { groups } = buildStageGroups({ 'cos-report-summary': {} });+ expect(groups[0].label).toBe('CoS');+ });+});diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxindex ab3bbced04..259679ff22 100644--- a/client/src/pages/PromptManager.jsx+++ b/client/src/pages/PromptManager.jsx@@ -1,6 +1,6 @@-import { useState, useEffect, useRef } from 'react';+import { useState, useEffect, useRef, useMemo } from 'react';import { useSearchParams } from 'react-router-dom';-import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase } from 'lucide-react';+import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase, Search, X, ChevronRight, ChevronDown } from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import ProviderModelSelector from '../components/ProviderModelSelector';@@ -22,6 +22,7 @@ import {getJobSkills, getJobSkill, saveJobSkill as apiSaveJobSkill, previewJobSkill as apiPreviewJobSkill,} from '../services/apiPrompts';import { getProviders } from '../services/apiProviders';+import { buildStageGroups, stageGroupLabel, isSystemStage } from '../lib/promptStageGroups';const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];@@ -53,12 +54,12 @@ export default function PromptManager() {const [variables, setVariables] = useState({});const [loading, setLoading] = useState(true);- // System stages that are protected- const systemStages = [- 'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',- 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',- 'memory-evaluate', 'app-detection'- ];+ // Stage list search / grouping. The query is deliberately LOCAL, not a URL+ // param: it's a transient way to reach a stage, and the thing worth+ // deep-linking (`?stage=`) is already in the URL.+ const [stageQuery, setStageQuery] = useState('');+ const [systemOnly, setSystemOnly] = useState(false);+ const [expandedGroups, setExpandedGroups] = useState(() => new Set());// Stage editing (selection is URL-driven — see selectedStage above)const [stageTemplate, setStageTemplate] = useState('');@@ -283,6 +284,32 @@ export default function PromptManager() {return p ? filterSelectableModels(p.models || [p.defaultModel]) : [];};+ const stageFilterActive = stageQuery.trim() !== '' || systemOnly;+ const { groups: stageGroups, matchCount: stageMatchCount, totalCount: stageTotalCount } = useMemo(+ () => buildStageGroups(stages, { query: stageQuery, systemOnly }),+ [stages, stageQuery, systemOnly],+ );++ // The group holding the open stage expands itself so a deep link / reload+ // lands with its row visible. Seeding STATE (rather than forcing it open at+ // render time) keeps the user free to collapse it again afterwards.+ const selectedGroupLabel = selectedStage && stages[selectedStage]+ ? stageGroupLabel(stages[selectedStage].name || selectedStage)+ : null;+ useEffect(() => {+ if (!selectedGroupLabel) return;+ setExpandedGroups((prev) => (prev.has(selectedGroupLabel) ? prev : new Set(prev).add(selectedGroupLabel)));+ }, [selectedGroupLabel]);++ // While a filter is on, every surviving group shows its matches — a search+ // that returns hits behind collapsed headers reads as "no results".+ const groupIsOpen = (label) => stageFilterActive || expandedGroups.has(label);+ const toggleGroup = (label) => setExpandedGroups((prev) => {+ const next = new Set(prev);+ if (next.has(label)) next.delete(label); else next.add(label);+ return next;+ });+if (loading) {return (<div className="flex flex-col h-full">@@ -364,39 +391,115 @@ export default function PromptManager() {<Plus size={16} /></button></div>- <div className="space-y-1">- {Object.entries(stages).sort(([a], [b]) => a.localeCompare(b)).map(([name, config]) => (- <div- key={name}- className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${- selectedStage === name- ? 'bg-port-accent/20 text-port-accent'- : 'text-gray-300 hover:bg-port-border'- }`}- >- <button- onClick={() => setSelectedStage(name)}- className="flex-1 min-w-0 text-left"- >- <div className="flex items-center gap-1">- <span className="font-medium truncate">{config.name || name}</span>- {systemStages.includes(name) && (- <span className="shrink-0 text-[10px] px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded uppercase font-semibold">- System- </span>- )}- </div>- <div className="text-xs text-gray-500 truncate">{config.description}</div>- </button>+ {/* Search + SYSTEM filter, pinned above the list so it stays+ reachable while the grouped rows scroll. */}+ <div className="sticky top-0 z-10 -mx-4 px-4 pb-3 bg-port-card">+ <div className="relative">+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />+ <input+ type="search"+ id="stage-search"+ aria-label="Search prompt stages"+ value={stageQuery}+ onChange={(e) => setStageQuery(e.target.value)}+ placeholder="Search stages…"+ className="w-full pl-8 pr-8 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:border-port-accent focus:outline-hidden"+ />+ {stageQuery && (<button- onClick={() => requestDeleteStage(name)}- className="shrink-0 p-1 text-gray-500 hover:text-port-error"- title="Delete stage"+ onClick={() => setStageQuery('')}+ aria-label="Clear stage search"+ className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-white">- <Trash2 size={14} />+ <X size={14} /></button>+ )}+ </div>+ <div className="flex items-center justify-between gap-2 mt-2">+ <button+ onClick={() => setSystemOnly(v => !v)}+ aria-pressed={systemOnly}+ className={`text-[10px] px-2 py-1 rounded uppercase font-semibold transition-colors ${+ systemOnly+ ? 'bg-port-accent text-white'+ : 'bg-port-border text-gray-400 hover:text-white'+ }`}+ >+ System only+ </button>+ <span className="text-xs text-gray-500">+ {stageFilterActive ? `${stageMatchCount} of ${stageTotalCount}` : `${stageTotalCount} stages`}+ </span>+ </div>+ </div>+ <div className="space-y-1">+ {stageGroups.map(({ label, stages: groupStages }) => {+ const open = groupIsOpen(label);+ const headerBody = (+ <>+ {stageFilterActive+ ? null+ : open+ ? <ChevronDown size={12} className="shrink-0" />+ : <ChevronRight size={12} className="shrink-0" />}+ <span className="min-w-0 truncate">{label}</span>+ <span className="ml-auto shrink-0 text-gray-500 normal-case">{groupStages.length}</span>+ </>+ );+ return (+ <div key={label}>+ {/* While a filter is on every group is forced open, so the+ toggle would be a dead control — render a plain heading+ instead of a button that does nothing. */}+ {stageFilterActive ? (+ <div className="flex items-center gap-1 px-2 py-1.5 text-xs font-semibold uppercase tracking-wide text-gray-400">+ {headerBody}+ </div>+ ) : (+ <button+ onClick={() => toggleGroup(label)}+ aria-expanded={open}+ // Without this the name computes to "Pipeline78" — the+ // count span abuts the label with no separator.+ aria-label={`${label}, ${groupStages.length} stages`}+ className="w-full flex items-center gap-1 px-2 py-1.5 rounded-lg text-xs font-semibold uppercase tracking-wide text-gray-400 hover:bg-port-border hover:text-white"+ >+ {headerBody}+ </button>+ )}+ {open && (+ <div className="space-y-1 pl-2">+ {groupStages.map(([name, config]) => (+ <button+ key={name}+ onClick={() => setSelectedStage(name)}+ className={`w-full text-left px-3 py-2 rounded-lg text-sm ${+ selectedStage === name+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-300 hover:bg-port-border'+ }`}+ >+ <div className="flex items-center gap-1">+ <span className="font-medium truncate">{config.name || name}</span>+ {isSystemStage(name) && (+ <span className="shrink-0 text-[10px] px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded uppercase font-semibold">+ System+ </span>+ )}+ </div>+ <div className="text-xs text-gray-500 truncate">{config.description}</div>+ </button>+ ))}+ </div>+ )}+ </div>+ );+ })}+ {stageGroups.length === 0 && (+ <div className="text-sm text-gray-500 px-3 py-2">+ {stageFilterActive ? 'No stages match that search' : 'No prompt stages found'}</div>- ))}+ )}</div></div>@@ -428,6 +531,16 @@ export default function PromptManager() {><Save size={14} /> Save</button>+ {/* Delete lives here, not on the list row: a destructive+ control sitting beside 120+ select targets is a+ mis-tap waiting to happen (#3284). */}+ <button+ onClick={() => requestDeleteStage(selectedStage)}+ title="Delete stage"+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-border hover:bg-port-error text-gray-300 hover:text-white rounded"+ >+ <Trash2 size={14} /> Delete+ </button></div></div>diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsxnew file mode 100644index 0000000000..65a85983e1--- /dev/null+++ b/client/src/pages/PromptManager.test.jsx@@ -0,0 +1,199 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import PromptManager from './PromptManager';++// The Stages pane is the subject: 100+ rows with no way to reach one (#3284).+// Only the list-shaping API calls need real fixtures; everything else resolves+// empty so the page mounts.+const getPrompts = vi.fn();+const getPrompt = vi.fn();+const getPromptUsage = vi.fn();++vi.mock('../services/apiPrompts', () => ({+ getPrompts: (...a) => getPrompts(...a),+ getPrompt: (...a) => getPrompt(...a),+ createPrompt: vi.fn(),+ savePrompt: vi.fn(),+ deletePrompt: vi.fn(),+ previewPrompt: vi.fn(),+ getPromptUsage: (...a) => getPromptUsage(...a),+ getPromptVariables: vi.fn(() => Promise.resolve({ variables: {} })),+ createPromptVariable: vi.fn(),+ savePromptVariable: vi.fn(),+ deletePromptVariable: vi.fn(),+ getJobSkills: vi.fn(() => Promise.resolve({ skills: [] })),+ getJobSkill: vi.fn(),+ saveJobSkill: vi.fn(),+ previewJobSkill: vi.fn(),+}));++vi.mock('../services/apiProviders', () => ({+ getProviders: vi.fn(() => Promise.resolve({ providers: [], activeProvider: null })),+}));++vi.mock('../components/ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++const STAGES = {+ 'pipeline-prose-draft': { name: 'Pipeline — Prose Draft', description: 'Draft the prose' },+ 'pipeline-comic-script': { name: 'Pipeline — Comic Book Script', description: 'Panels and balloons' },+ 'creative-director-treatment': { name: 'Creative Director — Treatment', description: 'Treatment doc' },+ 'brain-classifier': { name: 'Brain Classifier', description: 'Classify a thought' },+};++const renderPage = (entry = '/prompts') => render(+ <MemoryRouter initialEntries={[entry]}>+ <PromptManager />+ </MemoryRouter>,+);++const searchBox = () => screen.getByLabelText('Search prompt stages');+const groupHeader = (label) => screen.getByRole('button', { name: new RegExp(`^${label}, \\d+ stages$`, 'i') });++describe('PromptManager stage list', () => {+ beforeEach(() => {+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES });+ getPrompt.mockReset().mockResolvedValue({ name: 'Pipeline — Prose Draft', template: 'body', variables: [] });+ getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: false, usedBy: [] });+ });++ it('shows collapsed groups and a stage count instead of a flat 100-row list', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ // Group headers, not rows.+ expect(groupHeader('Pipeline')).toBeTruthy();+ expect(groupHeader('Brain')).toBeTruthy();+ expect(screen.getByText('4 stages')).toBeTruthy();+ expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();+ });++ it('expands and re-collapses a group on click', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ const header = groupHeader('Pipeline');+ expect(header.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(header);+ expect(header.getAttribute('aria-expanded')).toBe('true');+ expect(screen.getByText('Pipeline — Prose Draft')).toBeTruthy();++ fireEvent.click(header);+ expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();+ });++ it('filters rows on the title as the user types, auto-revealing matches', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.change(searchBox(), { target: { value: 'comic' } });++ // No manual expand needed — a filtered group shows its matches.+ expect(screen.getByText('Pipeline — Comic Book Script')).toBeTruthy();+ expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();+ expect(screen.queryByText('Brain Classifier')).toBeNull();+ expect(screen.getByText('1 of 4')).toBeTruthy();+ });++ it('drops the group toggle while filtering rather than leaving a dead control', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');+ expect(groupHeader('Pipeline')).toBeTruthy();++ fireEvent.change(searchBox(), { target: { value: 'comic' } });+ expect(screen.queryByRole('button', { name: /^Pipeline, \d+ stages$/i })).toBeNull();+ expect(screen.getByText('Pipeline')).toBeTruthy();+ });++ it('filters on the description too', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.change(searchBox(), { target: { value: 'balloons' } });+ expect(screen.getByText('Pipeline — Comic Book Script')).toBeTruthy();+ expect(screen.getByText('1 of 4')).toBeTruthy();+ });++ it('reports an empty result rather than a silently blank pane', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.change(searchBox(), { target: { value: 'zzzz' } });+ expect(screen.getByText('No stages match that search')).toBeTruthy();+ });++ it('clears the query from the clear button', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.change(searchBox(), { target: { value: 'comic' } });+ fireEvent.click(screen.getByLabelText('Clear stage search'));++ expect(searchBox().value).toBe('');+ expect(screen.getByText('4 stages')).toBeTruthy();+ });++ it('narrows to system stages with the SYSTEM-only toggle', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ const toggle = screen.getByRole('button', { name: /system only/i });+ expect(toggle.getAttribute('aria-pressed')).toBe('false');+ fireEvent.click(toggle);++ expect(toggle.getAttribute('aria-pressed')).toBe('true');+ expect(screen.getByText('Brain Classifier')).toBeTruthy();+ expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();+ expect(screen.getByText('1 of 4')).toBeTruthy();+ });++ it('selects a stage into the URL from a filtered row', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.change(searchBox(), { target: { value: 'comic' } });+ fireEvent.click(screen.getByText('Pipeline — Comic Book Script'));++ await waitFor(() => expect(getPrompt).toHaveBeenCalledWith('pipeline-comic-script', { silent: true }));+ });++ it('opens the group holding a deep-linked stage', async () => {+ renderPage('/prompts?stage=brain-classifier');+ await screen.findByText('Prompt Stages');++ await waitFor(() => expect(groupHeader('Brain').getAttribute('aria-expanded')).toBe('true'));+ expect(screen.getByText('Brain Classifier')).toBeTruthy();+ // Sibling groups stay closed.+ expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('false');+ });+});++describe('PromptManager delete demotion', () => {+ beforeEach(() => {+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES });+ getPrompt.mockReset().mockResolvedValue({ name: 'Brain Classifier', template: 'body', variables: [] });+ getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: true, usedBy: ['Brain thought classification'] });+ });++ it('keeps delete out of the list rows entirely', async () => {+ renderPage();+ await screen.findByText('Prompt Stages');+ fireEvent.click(groupHeader('Pipeline'));++ const list = screen.getByText('Pipeline — Prose Draft').closest('div[class*="space-y-1"]');+ expect(within(list).queryByTitle('Delete stage')).toBeNull();+ });++ it('offers delete from the selected stage detail pane', async () => {+ renderPage('/prompts?stage=brain-classifier');+ await screen.findByText('Prompt Stages');++ const del = await screen.findByRole('button', { name: /^delete$/i });+ fireEvent.click(del);++ await waitFor(() => expect(getPromptUsage).toHaveBeenCalledWith('brain-classifier', { silent: true }));+ expect(await screen.findByText('Delete System Stage?')).toBeTruthy();+ });+});