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

refactor([issue-3284]): collapse the stage-group header to one render path

[._.]/ Adam Eivyf681815a6c66
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 1ac47a7b1e..e83d66556b 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`. `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 `[{ 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. |
| `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 5a02bafd3c..bf753261f6 100644
--- a/client/src/lib/promptStageGroups.js
+++ b/client/src/lib/promptStageGroups.js
@@ -52,6 +52,9 @@ export const STAGE_WORD_PREFIXES = [
'Twin',
];
+// Lowercased once at module load — the match below runs per stage per keystroke.
+const LOWERED_WORD_PREFIXES = STAGE_WORD_PREFIXES.map((prefix) => [prefix, prefix.toLowerCase()]);
+
/**
* 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
@@ -68,13 +71,22 @@ export function stageGroupLabel(displayName) {
}
const normalized = name.replace(/-/g, ' ').toLowerCase();
- for (const prefix of STAGE_WORD_PREFIXES) {
- const needle = prefix.toLowerCase();
+ for (const [prefix, needle] of LOWERED_WORD_PREFIXES) {
if (normalized === needle || normalized.startsWith(`${needle} `)) return prefix;
}
return OTHER_GROUP_LABEL;
}
+/**
+ * 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.
+ */
+export function stageGroupLabelFor(key, config) {
+ return stageGroupLabel(config?.name || key);
+}
+
/**
* 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
@@ -107,22 +119,21 @@ export function buildStageGroups(stages, { query = '', systemOnly = false } = {}
const byLabel = new Map();
for (const entry of matched) {
- const label = stageGroupLabel(entry[1]?.name || entry[0]);
+ const label = stageGroupLabelFor(entry[0], entry[1]);
const list = byLabel.get(label);
if (list) list.push(entry); else byLabel.set(label, [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]) =>
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);
- });
+ .sort((a, b) => rank(a.label) - rank(b.label) || 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 ce417ac544..343d6f119b 100644
--- a/client/src/lib/promptStageGroups.test.js
+++ b/client/src/lib/promptStageGroups.test.js
@@ -1,7 +1,11 @@
import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
import {
buildStageGroups,
stageGroupLabel,
+ stageGroupLabelFor,
stageHaystack,
isSystemStage,
SYSTEM_STAGE_KEYS,
@@ -168,3 +172,47 @@ describe('buildStageGroups', () => {
expect(groups[0].label).toBe('CoS');
});
});
+
+describe('stageGroupLabelFor', () => {
+ 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', () => {
+ 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);
+ }
+ });
+});
+
+// Drift guard: the word-prefix fallback is a curated list, so a NEW stage family
+// that skips the `Family — Specific` convention would silently land in `Other`
+// with nothing to notice it. Pin the shipped catalog's Other bucket so adding
+// such a stage fails here instead of quietly becoming unfiled in the UI.
+describe('shipped stage catalog', () => {
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
+ const seeded = JSON.parse(
+ readFileSync(resolve(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ ).stages;
+
+ it('files every shipped stage except the three known un-prefixed scorers', () => {
+ const { groups, totalCount } = buildStageGroups(seeded);
+ expect(totalCount).toBeGreaterThan(100);
+ const other = groups.find(g => g.label === OTHER_GROUP_LABEL);
+ expect(other?.stages.map(([key]) => key) ?? []).toEqual([
+ 'adversarial-boundary-scorer',
+ 'multi-turn-consistency-scorer',
+ 'values-alignment-scorer',
+ ]);
+ });
+
+ it('keeps every shipped group non-empty and Other last', () => {
+ const { groups } = buildStageGroups(seeded);
+ expect(groups.every(g => g.stages.length > 0)).toBe(true);
+ expect(groups[groups.length - 1].label).toBe(OTHER_GROUP_LABEL);
+ });
+});
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 259679ff22..38aef103ae 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -22,7 +22,10 @@ import {
getJobSkills, getJobSkill, saveJobSkill as apiSaveJobSkill, previewJobSkill as apiPreviewJobSkill,
} from '../services/apiPrompts';
import { getProviders } from '../services/apiProviders';
-import { buildStageGroups, stageGroupLabel, isSystemStage } from '../lib/promptStageGroups';
+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';
const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];
@@ -294,16 +297,13 @@ export default function PromptManager() {
// 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)
+ ? stageGroupLabelFor(selectedStage, stages[selectedStage])
: null;
useEffect(() => {
if (!selectedGroupLabel) return;
- setExpandedGroups((prev) => (prev.has(selectedGroupLabel) ? prev : new Set(prev).add(selectedGroupLabel)));
+ setExpandedGroups((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);
@@ -398,7 +398,6 @@ export default function PromptManager() {
<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)}
@@ -434,39 +433,26 @@ export default function PromptManager() {
</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>
- </>
- );
+ // 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);
+ const Chevron = open ? ChevronDown : ChevronRight;
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>
- )}
+ <button
+ onClick={() => toggleGroup(label)}
+ disabled={stageFilterActive}
+ 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 enabled:hover:bg-port-border enabled:hover:text-white"
+ >
+ <Chevron size={12} className={`shrink-0 ${stageFilterActive ? 'invisible' : ''}`} />
+ <span className="min-w-0 truncate">{label}</span>
+ <span className="ml-auto shrink-0 text-gray-500 normal-case">{groupStages.length}</span>
+ </button>
{open && (
<div className="space-y-1 pl-2">
{groupStages.map(([name, config]) => (
@@ -481,10 +467,10 @@ export default function PromptManager() {
>
<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">
+ {isSystemStageKey(name) && (
+ <Pill tone="bare" size="xs" bordered={false} className="shrink-0 bg-port-accent/20 text-port-accent uppercase font-semibold">
System
- </span>
+ </Pill>
)}
</div>
<div className="text-xs text-gray-500 truncate">{config.description}</div>
diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsx
index 65a85983e1..1831ad866b 100644
--- a/client/src/pages/PromptManager.test.jsx
+++ b/client/src/pages/PromptManager.test.jsx
@@ -97,14 +97,14 @@ describe('PromptManager stage list', () => {
expect(screen.getByText('1 of 4')).toBeTruthy();
});
- it('drops the group toggle while filtering rather than leaving a dead control', async () => {
+ it('disables the group toggle while filtering rather than leaving a dead control', async () => {
renderPage();
await screen.findByText('Prompt Stages');
- expect(groupHeader('Pipeline')).toBeTruthy();
+ expect(groupHeader('Pipeline').disabled).toBe(false);
fireEvent.change(searchBox(), { target: { value: 'comic' } });
- expect(screen.queryByRole('button', { name: /^Pipeline, \d+ stages$/i })).toBeNull();
- expect(screen.getByText('Pipeline')).toBeTruthy();
+ expect(groupHeader('Pipeline').disabled).toBe(true);
+ expect(groupHeader('Pipeline').getAttribute('aria-expanded')).toBe('true');
});
it('filters on the description too', async () => {