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

fix([issue-3284]): keep the group toggle usable while filtering, and fold case-variant families

[._.]/ Adam Eivy5cffa5b40a30
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e83d66556b..0f05e32c44 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -147,7 +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`; `stageGroupLabelFor(key, config)` is the name-or-key form both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `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. |
+| `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 `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `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/promptStageGroups.js b/client/src/lib/promptStageGroups.js
index bf753261f6..23e9932795 100644
--- a/client/src/lib/promptStageGroups.js
+++ b/client/src/lib/promptStageGroups.js
@@ -35,8 +35,11 @@ export function isSystemStage(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/;
+// Most names encode their family as `<Family> — <specific>`. The shipped catalog
+// uses an em dash, but a user naming their own stage in the Create Stage modal
+// will reach for a plain hyphen, so accept all three. A spaced separator is
+// required — `Twin Spoken-vs-Written Comparison` must not split.
+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`
@@ -80,13 +83,28 @@ export function stageGroupLabel(displayName) {
/**
* The group for a `[key, config]` pair — the display name when it has one,
* else the key. The single definition of that fallback: the page's
- * auto-expand and this module's bucketing must agree on the label, or a
- * deep-linked stage opens the wrong group.
+ * auto-expand and this module's bucketing must agree, or a deep-linked stage
+ * opens the wrong group.
*/
export function stageGroupLabelFor(key, config) {
return stageGroupLabel(config?.name || key);
}
+/**
+ * The identity a group is bucketed and remembered under. Case-folded because
+ * headers render uppercase: `Pipeline — X` and `pipeline — y` are one group to
+ * the eye, and letting them be two produces twin `PIPELINE` headers with the
+ * user's stage in whichever one they didn't open. The first spelling seen wins
+ * as the *display* label; this key is what open/closed state is stored under.
+ */
+export function stageGroupKey(label) {
+ return String(label || '').toLowerCase();
+}
+
+export function stageGroupKeyFor(key, config) {
+ return stageGroupKey(stageGroupLabelFor(key, config));
+}
+
/**
* 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
@@ -101,8 +119,9 @@ export function stageHaystack(key, config) {
*
* `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.
+ * `{ key, label, stages: [[key, config], …] }` — `key` is the case-folded
+ * identity to store open/closed state under, `label` the first spelling seen.
+ * Groups sort alphabetically with `Other` pinned last, stages by display name.
*
* An empty query and `systemOnly: false` return everything, so the same call
* drives both the unfiltered and the filtered render.
@@ -117,23 +136,26 @@ export function buildStageGroups(stages, { query = '', systemOnly = false } = {}
return matchHaystack(stageHaystack(key, config), tokens);
});
- const byLabel = new Map();
+ const byKey = new Map();
for (const entry of matched) {
const label = stageGroupLabelFor(entry[0], entry[1]);
- const list = byLabel.get(label);
- if (list) list.push(entry); else byLabel.set(label, [entry]);
+ const key = stageGroupKey(label);
+ const group = byKey.get(key);
+ if (group) group.stages.push(entry);
+ else byKey.set(key, { key, label, stages: [entry] });
}
// `Other` sorts last; everything else alphabetically. Ranking rather than
// branching so a second pinned bucket is one table entry, not a rewrite.
- const rank = (label) => (label === OTHER_GROUP_LABEL ? 1 : 0);
- const groups = [...byLabel.entries()]
- .map(([label, list]) => ({
- label,
- stages: list.sort(([aKey, a], [bKey, b]) =>
+ const otherKey = stageGroupKey(OTHER_GROUP_LABEL);
+ const rank = (group) => (group.key === otherKey ? 1 : 0);
+ const groups = [...byKey.values()]
+ .map((group) => ({
+ ...group,
+ stages: group.stages.sort(([aKey, a], [bKey, b]) =>
String(a?.name || aKey).localeCompare(String(b?.name || bKey))),
}))
- .sort((a, b) => rank(a.label) - rank(b.label) || a.label.localeCompare(b.label));
+ .sort((a, b) => rank(a) - rank(b) || 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.js
index 343d6f119b..f5c2c62c00 100644
--- a/client/src/lib/promptStageGroups.test.js
+++ b/client/src/lib/promptStageGroups.test.js
@@ -6,6 +6,7 @@ import {
buildStageGroups,
stageGroupLabel,
stageGroupLabelFor,
+ stageGroupKeyFor,
stageHaystack,
isSystemStage,
SYSTEM_STAGE_KEYS,
@@ -24,12 +25,15 @@ describe('stageGroupLabel', () => {
expect(stageGroupLabel('Pipeline — Reverse Outline — v2')).toBe('Pipeline');
});
- it('accepts an en-dash separator too', () => {
+ it('accepts an en-dash or a plain hyphen separator too', () => {
expect(stageGroupLabel('Importer – Analyze')).toBe('Importer');
+ // What a user actually types in the Create Stage modal.
+ expect(stageGroupLabel('Writers Room - My Pass')).toBe('Writers Room');
});
- it('ignores hyphens that are not the separator', () => {
+ it('requires the separator to be spaced, so in-word hyphens do not split', () => {
expect(stageGroupLabel('Twin Spoken-vs-Written Comparison')).toBe('Twin');
+ expect(stageGroupLabel('Multi-Turn Consistency Scorer')).toBe(OTHER_GROUP_LABEL);
});
it('falls back to a known leading word for pre-dash names', () => {
@@ -171,22 +175,38 @@ describe('buildStageGroups', () => {
const { groups } = buildStageGroups({ 'cos-report-summary': {} });
expect(groups[0].label).toBe('CoS');
});
+
+ it('merges case-variant family names into one group, keeping the first spelling', () => {
+ const { groups } = buildStageGroups({
+ 'a': stage('Pipeline — Alpha'),
+ 'b': stage('pipeline — beta'),
+ 'c': stage('PIPELINE — gamma'),
+ });
+ expect(groups).toHaveLength(1);
+ expect(groups[0].key).toBe('pipeline');
+ expect(groups[0].label).toBe('Pipeline');
+ expect(groups[0].stages).toHaveLength(3);
+ });
});
-describe('stageGroupLabelFor', () => {
+describe('stageGroupLabelFor / stageGroupKeyFor', () => {
it('prefers the display name and falls back to the key', () => {
expect(stageGroupLabelFor('x', stage('Importer — Analyze'))).toBe('Importer');
expect(stageGroupLabelFor('brain-classifier', {})).toBe('Brain');
expect(stageGroupLabelFor('brain-classifier', undefined)).toBe('Brain');
});
- it('agrees with the label buildStageGroups buckets under', () => {
+ it('agrees with the key buildStageGroups buckets under', () => {
const stages = { 'brain-classifier': {}, 'creative-director-treatment': stage('Creative Director — Treatment') };
const { groups } = buildStageGroups(stages);
- for (const { label, stages: rows } of groups) {
- for (const [key, config] of rows) expect(stageGroupLabelFor(key, config)).toBe(label);
+ for (const { key: groupKey, stages: rows } of groups) {
+ for (const [key, config] of rows) expect(stageGroupKeyFor(key, config)).toBe(groupKey);
}
});
+
+ it('case-folds the key so differently-spelled families share one group', () => {
+ expect(stageGroupKeyFor('a', stage('Pipeline — X'))).toBe(stageGroupKeyFor('b', stage('pipeline — y')));
+ });
});
// Drift guard: the word-prefix fallback is a curated list, so a NEW stage family
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 308b5a59f8..108ca11f24 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -25,7 +25,7 @@ import { getProviders } from '../services/apiProviders';
import Pill from '../components/ui/Pill';
// Aliased: `confirmDeleteStage` destructures an `isSystemStage` field off the
// pending-delete record, which would otherwise shadow this import.
-import { buildStageGroups, stageGroupLabelFor, isSystemStage as isSystemStageKey } from '../lib/promptStageGroups';
+import { buildStageGroups, stageGroupKeyFor, isSystemStage as isSystemStageKey } from '../lib/promptStageGroups';
const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];
@@ -62,7 +62,13 @@ export default function PromptManager() {
// deep-linking (`?stage=`) is already in the URL.
const [stageQuery, setStageQuery] = useState('');
const [systemOnly, setSystemOnly] = useState(false);
+ // Two disclosure sets, because the default flips with the filter: unfiltered,
+ // groups start CLOSED and this tracks the ones opened; filtered, they start
+ // OPEN (hiding a match reads as "no results") and `collapsedWhileFiltering`
+ // tracks the ones folded away — a broad query like "e" matches every stage,
+ // so the user still needs to be able to fold Pipeline's 78 rows out of view.
const [expandedGroups, setExpandedGroups] = useState(() => new Set());
+ const [collapsedWhileFiltering, setCollapsedWhileFiltering] = useState(() => new Set());
// Stage editing (selection is URL-driven — see selectedStage above)
const [stageTemplate, setStageTemplate] = useState('');
@@ -296,19 +302,29 @@ export default function PromptManager() {
// 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]
- ? stageGroupLabelFor(selectedStage, stages[selectedStage])
+ const selectedGroupKey = selectedStage && stages[selectedStage]
+ ? stageGroupKeyFor(selectedStage, stages[selectedStage])
: null;
useEffect(() => {
- if (!selectedGroupLabel) return;
- setExpandedGroups((prev) => new Set(prev).add(selectedGroupLabel));
- }, [selectedGroupLabel]);
+ if (!selectedGroupKey) return;
+ setExpandedGroups((prev) => new Set(prev).add(selectedGroupKey));
+ }, [selectedGroupKey]);
- const toggleGroup = (label) => setExpandedGroups((prev) => {
- const next = new Set(prev);
- if (next.has(label)) next.delete(label); else next.add(label);
+ // Folding a group away is scoped to the filter that motivated it — clearing
+ // the search must not leave groups collapsed-by-exception in a view whose
+ // default is already collapsed.
+ useEffect(() => {
+ setCollapsedWhileFiltering((prev) => (prev.size === 0 ? prev : new Set()));
+ }, [stageFilterActive]);
+
+ const toggleInSet = (set, key) => {
+ const next = new Set(set);
+ if (next.has(key)) next.delete(key); else next.add(key);
return next;
- });
+ };
+ const toggleGroup = (key) => (stageFilterActive
+ ? setCollapsedWhileFiltering((prev) => toggleInSet(prev, key))
+ : setExpandedGroups((prev) => toggleInSet(prev, key)));
if (loading) {
return (
@@ -402,7 +418,11 @@ export default function PromptManager() {
value={stageQuery}
onChange={(e) => setStageQuery(e.target.value)}
placeholder="Search stages…"
- className="w-full pl-8 pr-9 py-2.5 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder:text-gray-500 focus:border-port-accent focus:outline-hidden"
+ // WebKit paints its own cancel glyph on a non-empty
+ // type=search, which would sit on top of the labelled clear
+ // button below; Tailwind's preflight resets only
+ // ::-webkit-search-decoration, so suppress it here.
+ className="w-full pl-8 pr-9 py-2.5 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder:text-gray-500 focus:border-port-accent focus:outline-hidden [&::-webkit-search-cancel-button]:appearance-none"
/>
{stageQuery && (
<button
@@ -432,24 +452,25 @@ export default function PromptManager() {
</div>
</div>
<div className="space-y-1">
- {stageGroups.map(({ label, stages: groupStages }) => {
- // A filter forces every surviving group open — hits hidden
- // behind collapsed headers read as "no results" — which also
- // makes the toggle inert, so it disables rather than lying.
- const open = stageFilterActive || expandedGroups.has(label);
+ {stageGroups.map(({ key: groupKey, label, stages: groupStages }) => {
+ // A filter flips the default open — hits hidden behind collapsed
+ // headers read as "no results" — but the toggle stays live so a
+ // broad query's biggest group can still be folded away.
+ const open = stageFilterActive
+ ? !collapsedWhileFiltering.has(groupKey)
+ : expandedGroups.has(groupKey);
const Chevron = open ? ChevronDown : ChevronRight;
return (
- <div key={label}>
+ <div key={groupKey}>
<button
- onClick={() => toggleGroup(label)}
- disabled={stageFilterActive}
+ onClick={() => toggleGroup(groupKey)}
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-2 rounded-lg text-xs font-semibold uppercase tracking-wide text-gray-400 enabled:hover:bg-port-border enabled:hover:text-white"
+ aria-label={`${label}, ${groupStages.length} stage${groupStages.length === 1 ? '' : 's'}`}
+ className="w-full flex items-center gap-1 px-2 py-2 rounded-lg text-xs font-semibold uppercase tracking-wide text-gray-400 hover:bg-port-border hover:text-white"
>
- <Chevron size={12} className={`shrink-0 ${stageFilterActive ? 'invisible' : ''}`} />
+ <Chevron 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>
</button>
@@ -883,9 +904,12 @@ export default function PromptManager() {
type="text"
value={newStageForm.name}
onChange={(e) => setNewStageForm({ ...newStageForm, name: e.target.value })}
- placeholder="My Stage"
+ placeholder="Pipeline — My Stage"
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
/>
+ <p className="text-xs text-gray-500 mt-1">
+ Name it <span className="text-gray-400">Family — Specific</span> to file it under an existing group
+ </p>
</FormField>
</div>
diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsx
index 1831ad866b..4b027e0cfa 100644
--- a/client/src/pages/PromptManager.test.jsx
+++ b/client/src/pages/PromptManager.test.jsx
@@ -50,7 +50,7 @@ const renderPage = (entry = '/prompts') => render(
);
const searchBox = () => screen.getByLabelText('Search prompt stages');
-const groupHeader = (label) => screen.getByRole('button', { name: new RegExp(`^${label}, \\d+ stages$`, 'i') });
+const groupHeader = (label) => screen.getByRole('button', { name: new RegExp(`^${label}, \\d+ stages?$`, 'i') });
describe('PromptManager stage list', () => {
beforeEach(() => {
@@ -65,7 +65,8 @@ describe('PromptManager stage list', () => {
// Group headers, not rows.
expect(groupHeader('Pipeline')).toBeTruthy();
- expect(groupHeader('Brain')).toBeTruthy();
+ expect(groupHeader('Brain').getAttribute('aria-label')).toBe('Brain, 1 stage');
+ expect(groupHeader('Pipeline').getAttribute('aria-label')).toBe('Pipeline, 2 stages');
expect(screen.getByText('4 stages')).toBeTruthy();
expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();
});
@@ -97,14 +98,54 @@ describe('PromptManager stage list', () => {
expect(screen.getByText('1 of 4')).toBeTruthy();
});
- it('disables the group toggle while filtering rather than leaving a dead control', async () => {
+ it('keeps the group toggle live while filtering so a broad query can be folded', async () => {
renderPage();
await screen.findByText('Prompt Stages');
- expect(groupHeader('Pipeline').disabled).toBe(false);
- fireEvent.change(searchBox(), { target: { value: 'comic' } });
- expect(groupHeader('Pipeline').disabled).toBe(true);
+ // A query matching everything must not become an uncollapsible wall.
+ fireEvent.change(searchBox(), { target: { value: 'e' } });
+ expect(screen.getByText('4 of 4')).toBeTruthy();
expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('true');
+ expect(screen.getByText('Pipeline — Prose Draft')).toBeTruthy();
+
+ fireEvent.click(groupHeader('Pipeline'));
+ expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('false');
+ expect(screen.queryByText('Pipeline — Prose Draft')).toBeNull();
+ // Folding one group leaves the others open.
+ expect(screen.getByText('Brain Classifier')).toBeTruthy();
+ });
+
+ it('forgets a filter-scoped collapse once the filter clears', async () => {
+ renderPage();
+ await screen.findByText('Prompt Stages');
+
+ fireEvent.change(searchBox(), { target: { value: 'e' } });
+ fireEvent.click(groupHeader('Pipeline'));
+ expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('false');
+
+ // Clearing returns to the collapsed-by-default view...
+ fireEvent.change(searchBox(), { target: { value: '' } });
+ expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('false');
+ // ...and expanding still works (the collapse exception did not persist).
+ fireEvent.click(groupHeader('Pipeline'));
+ expect(screen.getByText('Pipeline — Prose Draft')).toBeTruthy();
+ });
+
+ it('folds two spellings of the same family into one group', async () => {
+ getPrompts.mockResolvedValue({
+ stages: {
+ ...STAGES,
+ 'pipeline-lowercase': { name: 'pipeline — hand typed', description: 'user made' },
+ },
+ });
+ renderPage();
+ await screen.findByText('Prompt Stages');
+
+ // One PIPELINE header, holding all three — not two headers that render alike.
+ expect(screen.getAllByRole('button', { name: /^Pipeline, \d+ stages?$/i })).toHaveLength(1);
+ fireEvent.click(groupHeader('Pipeline'));
+ expect(screen.getByText('pipeline — hand typed')).toBeTruthy();
+ expect(screen.getByText('Pipeline — Prose Draft')).toBeTruthy();
});
it('filters on the description too', async () => {
@@ -133,6 +174,8 @@ describe('PromptManager stage list', () => {
expect(searchBox().value).toBe('');
expect(screen.getByText('4 stages')).toBeTruthy();
+ // Rows the filter revealed go back into their collapsed groups.
+ expect(screen.queryByText('Pipeline — Comic Book Script')).toBeNull();
});
it('narrows to system stages with the SYSTEM-only toggle', async () => {
@@ -177,13 +220,16 @@ describe('PromptManager delete demotion', () => {
getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: true, usedBy: ['Brain thought classification'] });
});
- it('keeps delete out of the list rows entirely', async () => {
+ it('keeps delete — or any other control — 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();
+ // Count buttons rather than probe for a label: a re-added row control
+ // fails this however it happens to be named.
+ const rows = screen.getByText('Pipeline — Prose Draft').closest('div[class*="space-y-1"]');
+ expect(within(rows).getAllByRole('button')).toHaveLength(2);
+ expect(within(rows).getByText('Pipeline — Comic Book Script')).toBeTruthy();
});
it('offers delete from the selected stage detail pane', async () => {