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: lead with the selected Prompt Manager editor on narrow screens (#11142)

[._.]/ Adam Eivy070b7f75a145
diff --git a/client/src/pages/PromptManager.browser.test.js b/client/src/pages/PromptManager.browser.test.js
new file mode 100644
index 0000000000..efad044382
--- /dev/null
+++ b/client/src/pages/PromptManager.browser.test.js
@@ -0,0 +1,159 @@
+// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import react from '@vitejs/plugin-react';
+import { BROWSER_FIXTURE_STARTUP_MS, startBrowserFixture } from '../test/browserFixture.js';
+
+vi.setConfig({ testTimeout: 30000 });
+
+const require = createRequire(import.meta.url);
+// Prefer the client dev dependency; linked worktrees can also use the same
+// pinned driver from the server without installing into shared node_modules.
+const { chromium } = require(require.resolve('playwright-core', { paths: [
+ fileURLToPath(new URL('../..', import.meta.url)),
+ fileURLToPath(new URL('../../../server', import.meta.url)),
+] }));
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+].find(path => path && existsSync(path));
+
+// Where the Layout would put the page: the viewport minus the sidebar. The
+// fixture draws that box itself, so the matrix can vary navigation state.
+const NAV_EXPANDED = 256;
+const NAV_COLLAPSED = 64;
+const SCENARIOS = [
+ [1440, 900, NAV_EXPANDED], [1280, 800, NAV_EXPANDED], [1024, 768, NAV_EXPANDED],
+ [1024, 768, NAV_COLLAPSED], [768, 1024, NAV_COLLAPSED], [390, 844, 0], [320, 812, 0],
+];
+const TABS = [
+ ['stages', 'stage=family-3-stage-1', 'Save'],
+ ['variables', 'tab=variables&var=var-6', 'Save'],
+ ['job-skills', 'tab=job-skills&skill=skill-5', 'Save'],
+];
+
+describe.skipIf(!chrome)('Prompt Manager selection-first workspace geometry (#11142)', () => {
+ let fixture;
+ let browser;
+ let origin;
+ beforeAll(async () => {
+ fixture = await startBrowserFixture({
+ name: 'prompt-manager',
+ createServer,
+ chromium,
+ viteConfig: temp => ({
+ configFile: false,
+ cacheDir: join(temp, 'vite-cache'),
+ optimizeDeps: {
+ entries: ['src/pages/PromptManager.jsx'],
+ include: ['react-dom/client', 'react-router', 'lucide-react'],
+ },
+ root: fileURLToPath(new URL('../..', import.meta.url)),
+ plugins: [react(), {
+ name: 'prompt-manager-browser-fixture',
+ enforce: 'pre',
+ resolveId(id, importer) {
+ if (id === '/prompt-fixture.jsx') return '\0prompt-fixture.jsx';
+ if (importer?.endsWith('/PromptManager.jsx')) {
+ if (id === '../services/apiPrompts') return '\0prompt-api';
+ if (id === '../services/apiProviders') return '\0prompt-providers';
+ if (id === '../components/settings/SettingsTabsHeader') return '\0prompt-tabs-header';
+ }
+ },
+ load(id) {
+ // 17 synthetic stage families (all collapsed but the selected one),
+ // 8+ variables and 8+ skills: the catalogues the audit measured.
+ if (id === '\0prompt-api') return `
+ const stages = {};
+ for (let f = 1; f <= 17; f++) for (let s = 1; s <= 4; s++) {
+ stages['family-' + f + '-stage-' + s] = { name: 'Family ' + f + ' — Stage ' + s, description: 'Example stage' };
+ }
+ const variables = {};
+ for (let v = 1; v <= 8; v++) variables['var-' + v] = { name: 'Variable ' + v, category: 'rules', content: 'example ' + v };
+ const skills = [];
+ for (let k = 1; k <= 8; k++) skills.push({ name: 'skill-' + k, jobId: 'job-' + k, hasTemplate: true });
+ export const getPrompts = async () => ({ stages, systemStages: [] });
+ export const getPrompt = async (name) => ({ name: stages[name].name, template: 'example template', variables: [] });
+ export const getPromptVariables = async () => ({ variables });
+ export const getJobSkills = async () => ({ skills });
+ export const getJobSkill = async (name) => ({ content: '# ' + name, jobName: 'Job ' + name, jobId: 'job-' + name, category: 'maintenance', interval: 'daily' });
+ const none = async () => ({});
+ export const createPrompt = none, savePrompt = none, deletePrompt = none, previewPrompt = none, getPromptUsage = none,
+ createPromptVariable = none, savePromptVariable = none, deletePromptVariable = none, saveJobSkill = none, previewJobSkill = none;
+ `;
+ if (id === '\0prompt-providers') return 'export const getProviders = async () => ({ providers: [], activeProvider: null });';
+ if (id === '\0prompt-tabs-header') return 'export default function SettingsTabsHeader() { return null; }';
+ if (id !== '\0prompt-fixture.jsx') return;
+ return `
+ import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import { MemoryRouter } from 'react-router';
+ import PromptManager from '/src/pages/PromptManager.jsx';
+ import '/src/index.css';
+ const q = new URLSearchParams(location.search);
+ const entry = '/prompts?' + (q.get('entry') || '');
+ createRoot(document.getElementById('root')).render(
+ React.createElement('div', { style: { width: q.get('w') + 'px', height: '100vh', marginLeft: 'auto' } },
+ React.createElement(MemoryRouter, { initialEntries: [entry] }, React.createElement(PromptManager)))
+ );
+ `;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/prompt-test', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/prompt-test',
+ '<div id="root"></div><script type="module" src="/prompt-fixture.jsx"></script>'));
+ });
+ },
+ }],
+ server: { host: '127.0.0.1', port: 0 },
+ }),
+ launchOptions: { executablePath: chrome },
+ warmup: async (page, url) => {
+ await page.goto(`${url}prompt-test?w=1000&entry=stage%3Dfamily-1-stage-1`, { timeout: 20000 });
+ await page.getByRole('button', { name: /^Save$/ }).waitFor({ timeout: 10000 });
+ },
+ });
+ ({ browser, origin } = fixture);
+ }, BROWSER_FIXTURE_STARTUP_MS);
+ afterAll(() => fixture?.close(), 60000);
+
+ for (const [tabName, entry] of TABS) {
+ it.each(SCENARIOS)(`${tabName}: selected editor action is above the fold at %ix%i (nav %ipx)`, async (width, height, nav) => {
+ const page = await browser.newPage({ viewport: { width, height } });
+ page.setDefaultTimeout(8000);
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ try {
+ await page.goto(`${origin}prompt-test?w=${width - nav}&entry=${encodeURIComponent(entry)}`, { timeout: 15000 });
+ const save = page.getByRole('button', { name: /^Save$/ });
+ await save.waitFor();
+ const box = await save.boundingBox();
+ // The primary action sits inside the first screen without scrolling.
+ expect(box.y).toBeGreaterThanOrEqual(0);
+ expect(box.y + box.height).toBeLessThanOrEqual(height);
+ // Nothing is clipped sideways.
+ expect(box.x + box.width).toBeLessThanOrEqual(width);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)).toBe(true);
+ const narrow = width - nav - 32 < 720;
+ const chooser = page.getByRole('button', { name: /Choose another/ });
+ expect(await chooser.count()).toBe(narrow ? 1 : 0);
+ if (narrow) {
+ await chooser.click();
+ const drawer = page.getByRole('dialog');
+ await drawer.waitFor();
+ const drawerBox = await drawer.boundingBox();
+ expect(drawerBox.x).toBeGreaterThanOrEqual(0);
+ expect(drawerBox.x + drawerBox.width).toBeLessThanOrEqual(width);
+ }
+ expect(errors).toEqual([]);
+ } finally {
+ await page.close();
+ }
+ });
+ }
+});
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 0c4f78ed25..26b36a325b 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { useSearchParams } from 'react-router';
-import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase, Search, X, ChevronRight, ChevronDown } from 'lucide-react';
+import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase, Search, X, ChevronRight, ChevronDown, List } from 'lucide-react';
import toast from '../components/ui/Toast';
import ProviderModelSelector from '../components/ProviderModelSelector';
import { filterSelectableModels, getProviderTimeout } from '../utils/providers';
@@ -11,7 +11,9 @@ import {
TIMEOUT_INPUT_MAX_MS,
TIMEOUT_INPUT_STEP_MS,
} from '../utils/formatters';
+import useContainerWidth from '../hooks/useContainerWidth';
import useFieldDraft from '../hooks/useFieldDraft';
+import Drawer from '../components/Drawer';
import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';
import PageSkeleton from '../components/ui/PageSkeleton';
import PageHeader from '../components/PageHeader';
@@ -31,6 +33,13 @@ import { STAGE_MODEL_TIER_OPTIONS, canonicalStageModelTier } from '../lib/stageM
const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];
+// The page keeps catalogue and editor side by side only while its own content
+// box (not the viewport — the sidebar takes a variable share) leaves the
+// catalogue column a usable width. Below it the selected editor leads and the
+// catalogue moves behind a Drawer (#11142). 0 = not measured yet / no
+// ResizeObserver, which renders the side-by-side layout.
+const SPLIT_PANE_MIN_WIDTH = 720;
+
// Shared by the loading and loaded branches so the bar doesn't change height
// when the fetch settles.
const PAGE_SUBTITLE = 'Customize AI prompts for backend operations';
@@ -56,6 +65,7 @@ export default function PromptManager() {
const rawTab = searchParams.get('tab');
const tab = VALID_PROMPT_TABS.includes(rawTab) ? rawTab : 'stages';
const setTab = (next) => {
+ setChooserOpen(false);
const p = new URLSearchParams(searchParams);
if (next === 'stages') p.delete('tab');
else p.set('tab', next);
@@ -77,6 +87,17 @@ export default function PromptManager() {
const setSelectedStage = (name) => setParam('stage', name);
const setSelectedVar = (key) => setParam('var', key);
const setSelectedJobSkill = (name) => setParam('skill', name);
+ // The scroll box is measured (see SPLIT_PANE_MIN_WIDTH) and reset to the top
+ // when a record opens, so a narrow layout lands on the editor, not the
+ // scrolled-away catalogue.
+ const [pageRef, pageWidth] = useContainerWidth();
+ const splitPane = pageWidth === 0 || pageWidth >= SPLIT_PANE_MIN_WIDTH;
+ // Narrow layouts only: the catalogue Drawer. Closed by every path that moves
+ // the selection; merely opening it never touches editor state.
+ const [chooserOpen, setChooserOpen] = useState(false);
+ // Narrow layouts only: the "+" blank-variable draft has no URL param, so
+ // this is what makes it the active editor instead of the catalogue.
+ const [varDraftOpen, setVarDraftOpen] = useState(false);
const [stages, setStages] = useState({});
// The CURATED system-stage keys. Served by GET /api/prompts
// (`server/lib/promptSystemStages.js`) rather than mirrored client-side, so
@@ -281,6 +302,13 @@ export default function PromptManager() {
}));
};
+ // Opening a record lands on its editor. In the narrow layout the catalogue
+ // that was scrolled through unmounts and the editor takes its place; without
+ // this the scroll offset of the old, longer content can be kept.
+ useEffect(() => {
+ pageRef.current?.scrollTo?.({ top: 0 });
+ }, [pageRef, tab, selectedStage, selectedVar, selectedJobSkill]);
+
const loadData = async () => {
await loadCatalogues(Object.keys(CATALOGUES));
setLoading(false);
@@ -362,6 +390,7 @@ export default function PromptManager() {
// Re-clicking the open stage is how a user backs out of the prompt from
// the list side; leaving it armed would strand the row mid-question.
setPendingStage(null);
+ setChooserOpen(false);
return;
}
if (isStageDirty) {
@@ -375,6 +404,7 @@ export default function PromptManager() {
// `selectedStage` effect — otherwise the frame between the two renders the
// OUTGOING stage's text and dirty badges under the incoming stage's row.
const switchStage = (name) => {
+ setChooserOpen(false);
setPendingStage(null);
setStageTemplate('');
setStageConfig({});
@@ -457,7 +487,11 @@ export default function PromptManager() {
.catch((err) => { toast.error('Failed to delete variable: ' + err.message); return false; });
if (!ok) return;
toast.success(`Variable "${label}" deleted`);
- if (selectedVar === key) switchVariable(null);
+ if (selectedVar === key) {
+ switchVariable(null);
+ // A deleted record leaves the catalogue, not a blank draft, behind.
+ setVarDraftOpen(false);
+ }
await loadData();
};
@@ -469,7 +503,7 @@ export default function PromptManager() {
// Re-clicking the open variable is how a user backs out of the prompt from
// the list side; leaving it armed would strand the row mid-question. The
// "+" (null key) is exempt: in create mode it still resets the draft.
- if (key !== null && key === selectedVar) { setPendingVar(null); return; }
+ if (key !== null && key === selectedVar) { setPendingVar(null); setChooserOpen(false); return; }
if (isVarDirty) { cancelVarDelete(); setPendingVar({ key }); return; }
switchVariable(key);
};
@@ -478,6 +512,8 @@ export default function PromptManager() {
// `selectedVar` effect — otherwise the frame between the two renders the
// OUTGOING variable's text and dirty badge under the incoming variable's row.
const switchVariable = (key) => {
+ setChooserOpen(false);
+ setVarDraftOpen(key === null);
setPendingVar(null);
varHydratedRef.current = null;
setVarForm(BLANK_VAR_FORM);
@@ -615,6 +651,7 @@ export default function PromptManager() {
// Re-clicking the open skill is how a user backs out of the prompt from
// the list side; leaving it armed would strand the row mid-question.
setPendingJobSkill(null);
+ setChooserOpen(false);
return;
}
if (isJobSkillDirty) {
@@ -628,6 +665,7 @@ export default function PromptManager() {
// `selectedJobSkill` effect — otherwise the frame between the two renders the
// OUTGOING skill's text and dirty badges under the incoming skill's row.
const switchJobSkill = (name) => {
+ setChooserOpen(false);
setPendingJobSkill(null);
setJobSkillContent('');
setSavedJobSkillContent('');
@@ -700,70 +738,22 @@ export default function PromptManager() {
<div className="flex flex-col h-full">
<PageHeader icon={FileText} title="Prompt Manager" subtitle={PAGE_SUBTITLE} />
<SettingsTabsHeader activeTab="prompts" />
- <div className="flex-1 overflow-auto p-4">
+ <div ref={pageRef} className="flex-1 overflow-auto p-4">
<PageSkeleton header="none" label="Loading prompts" cards={3} sidebar={false} />
</div>
</div>
);
}
- return (
- <div className="flex flex-col h-full">
- <PageHeader
- icon={FileText}
- title="Prompt Manager"
- subtitle={PAGE_SUBTITLE}
- actions={(
- <button
- onClick={loadData}
- className="p-2 text-gray-400 hover:text-white"
- title="Reload" aria-label="Reload"
- >
- <RefreshCw size={20} />
- </button>
- )}
- />
-
- <SettingsTabsHeader activeTab="prompts" />
-
- <div className="flex-1 overflow-auto p-4">
- {/* Tabs */}
- <div className="flex flex-wrap gap-2 mb-6">
- <button
- onClick={() => setTab('stages')}
- className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
- tab === 'stages' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
- }`}
- >
- <FileText size={16} /> Stages
- </button>
- <button
- onClick={() => setTab('variables')}
- className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
- tab === 'variables' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
- }`}
- >
- <Variable size={16} /> Variables
- </button>
- <button
- onClick={() => setTab('job-skills')}
- className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
- tab === 'job-skills' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
- }`}
- >
- <Briefcase size={16} /> Job Skills
- </button>
- </div>
-
- {/* Stages Tab */}
- {tab === 'stages' && (
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
- {/* Stage List */}
- <div className="bg-port-card border border-port-border rounded-xl p-4">
+ // Each tab's catalogue (record list) and editor are built once and placed by
+ // `renderWorkspace` below: side by side when the page is wide enough for both,
+ // otherwise editor-first with the catalogue behind a "Choose another…" Drawer.
+ const stageCatalogue = (
+ <>
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm font-medium text-gray-400">Prompt Stages</h2>
<button
- onClick={() => setCreatingStage(true)}
+ onClick={() => { setChooserOpen(false); setCreatingStage(true); }}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-accent hover:text-port-accent/80"
title="New Stage" aria-label="New Stage"
>
@@ -897,10 +887,10 @@ export default function PromptManager() {
</div>
)}
</div>
- </div>
-
- {/* Stage Editor */}
- <div className="lg:col-span-2 space-y-4">
+ </>
+ );
+ const stageEditor = (
+ <>
{selectedStage && !stages[selectedStage] && !stagesFailed ? (
<div className="bg-port-card border border-port-border rounded-xl p-12 text-center text-gray-500">
That stage could not be found — it may have been deleted or renamed.{' '}
@@ -1054,15 +1044,10 @@ export default function PromptManager() {
Select a stage to edit
</div>
)}
- </div>
- </div>
- )}
-
- {/* Variables Tab */}
- {tab === 'variables' && (
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
- {/* Variable List */}
- <div className="bg-port-card border border-port-border rounded-xl p-4">
+ </>
+ );
+ const variableCatalogue = (
+ <>
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-gray-400">Variables</h3>
<button
@@ -1151,10 +1136,10 @@ export default function PromptManager() {
)
))}
</div>
- </div>
-
- {/* Variable Editor */}
- <div className="lg:col-span-2">
+ </>
+ );
+ const variableEditor = (
+ <>
{selectedVar && !variables[selectedVar] && variablesFailed ? (
<div className="bg-port-card border border-port-border rounded-xl p-12 text-center text-gray-500">
The variable list is unavailable, so this variable cannot be shown.{' '}
@@ -1237,15 +1222,10 @@ export default function PromptManager() {
</div>
</div>
)}
- </div>
- </div>
- )}
-
- {/* Job Skills Tab */}
- {tab === 'job-skills' && (
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
- {/* Job Skill List */}
- <div className="bg-port-card border border-port-border rounded-xl p-4">
+ </>
+ );
+ const jobSkillCatalogue = (
+ <>
<div className="mb-3">
<h3 className="text-sm font-medium text-gray-400">Autonomous Job Skills</h3>
<p className="text-xs text-gray-500 mt-1">Versioned prompt templates for recurring jobs</p>
@@ -1301,10 +1281,10 @@ export default function PromptManager() {
<div className="text-sm text-gray-500 px-3 py-2">No job skill templates found</div>
)}
</div>
- </div>
-
- {/* Job Skill Editor */}
- <div className="lg:col-span-2 space-y-4">
+ </>
+ );
+ const jobSkillEditor = (
+ <>
{selectedJobSkill ? (
<>
<div className="bg-port-card border border-port-border rounded-xl p-4 @container">
@@ -1374,8 +1354,109 @@ export default function PromptManager() {
<p className="text-xs mt-2">These templates define how recurring autonomous jobs execute</p>
</div>
)}
- </div>
+ </>
+ );
+ // Places one tab's catalogue + editor. Wide: catalogue column beside the
+ // editor. Narrow: with a record open, its editor leads (title, read state and
+ // actions at the top) and the catalogue opens in a Drawer from a "Choose
+ // another…" row; with nothing open, the catalogue is the whole view. Either
+ // way each control exists once, so Save/Preview are never duplicated.
+ const renderWorkspace = ({ catalogue, editor, active, noun, title }) => {
+ const catalogueCard = <div className="bg-port-card border border-port-border rounded-xl p-4">{catalogue}</div>;
+ if (splitPane) {
+ return (
+ <div className="grid grid-cols-3 gap-6">
+ {catalogueCard}
+ <div className="col-span-2 space-y-4">{editor}</div>
</div>
+ );
+ }
+ if (!active) return catalogueCard;
+ return (
+ <div className="space-y-4">
+ <button
+ type="button"
+ onClick={() => setChooserOpen(true)}
+ aria-haspopup="dialog"
+ className="w-full min-h-[44px] flex items-center justify-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-sm text-gray-300 hover:text-white"
+ >
+ <List size={16} /> Choose another {noun}…
+ </button>
+ {editor}
+ <Drawer
+ open={chooserOpen}
+ onClose={() => setChooserOpen(false)}
+ title={title}
+ size="sm"
+ closeLabel={`Close ${noun} list`}
+ >
+ {catalogue}
+ </Drawer>
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex flex-col h-full">
+ <PageHeader
+ icon={FileText}
+ title="Prompt Manager"
+ subtitle={PAGE_SUBTITLE}
+ actions={(
+ <button
+ onClick={loadData}
+ className="p-2 text-gray-400 hover:text-white"
+ title="Reload" aria-label="Reload"
+ >
+ <RefreshCw size={20} />
+ </button>
+ )}
+ />
+
+ <SettingsTabsHeader activeTab="prompts" />
+
+ <div ref={pageRef} className="flex-1 overflow-auto p-4">
+ {/* Tabs */}
+ <div className="flex flex-wrap gap-2 mb-6">
+ <button
+ onClick={() => setTab('stages')}
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
+ tab === 'stages' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ <FileText size={16} /> Stages
+ </button>
+ <button
+ onClick={() => setTab('variables')}
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
+ tab === 'variables' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ <Variable size={16} /> Variables
+ </button>
+ <button
+ onClick={() => setTab('job-skills')}
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
+ tab === 'job-skills' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ <Briefcase size={16} /> Job Skills
+ </button>
+ </div>
+
+ {/* Stages Tab */}
+ {tab === 'stages' && (
+ renderWorkspace({ catalogue: stageCatalogue, editor: stageEditor, active: Boolean(selectedStage), noun: 'stage', title: 'Prompt Stages' })
+ )}
+
+ {/* Variables Tab */}
+ {tab === 'variables' && (
+ renderWorkspace({ catalogue: variableCatalogue, editor: variableEditor, active: Boolean(selectedVar) || varDraftOpen || isVarDirty, noun: 'variable', title: 'Variables' })
+ )}
+
+ {/* Job Skills Tab */}
+ {tab === 'job-skills' && (
+ renderWorkspace({ catalogue: jobSkillCatalogue, editor: jobSkillEditor, active: Boolean(selectedJobSkill), noun: 'job skill', title: 'Autonomous Job Skills' })
)}
{/* Create Stage Modal */}
diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsx
index 5d65b854b9..5a60a6b0b4 100644
--- a/client/src/pages/PromptManager.test.jsx
+++ b/client/src/pages/PromptManager.test.jsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter, useLocation, useNavigate } from 'react-router';
import PromptManager from './PromptManager';
@@ -1379,3 +1379,117 @@ describe('PromptManager unavailable catalogues (#11143)', () => {
await waitFor(() => expect(screen.queryByText(/may be out of date/)).toBeNull());
});
});
+
+// Below the split-pane width the selected editor leads and the catalogue moves
+// behind a Drawer (#11142). happy-dom has no layout, so the page's measured
+// content width is injected through a ResizeObserver stand-in.
+describe('PromptManager narrow layout (#11142)', () => {
+ const NARROW_PX = 500;
+ const realResizeObserver = globalThis.ResizeObserver;
+ const VARIABLES = {
+ 'tone-guide': { name: 'Tone Guide', category: 'style', content: 'stay wry' },
+ 'house-style': { name: 'House Style', category: 'style', content: 'oxford comma' },
+ };
+ const SKILLS = [
+ { name: 'code-fixer', jobId: 'job-code-fixer', hasTemplate: true },
+ { name: 'doc-writer', jobId: 'job-doc-writer', hasTemplate: false },
+ ];
+
+ beforeEach(() => {
+ globalThis.ResizeObserver = class {
+ constructor(cb) { this.cb = cb; }
+ observe() { this.cb([{ contentRect: { width: NARROW_PX } }]); }
+ disconnect() {}
+ };
+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });
+ getPrompt.mockReset().mockImplementation((name) => Promise.resolve({
+ name: STAGES[name]?.name || name, description: STAGES[name]?.description, template: `${name} template`, variables: [],
+ }));
+ getPromptVariables.mockReset().mockResolvedValue({ variables: VARIABLES });
+ getJobSkills.mockReset().mockResolvedValue({ skills: SKILLS });
+ getJobSkill.mockReset().mockImplementation((name) => Promise.resolve({
+ content: `# ${name} template`, jobName: `Job ${name}`, jobId: `job-${name}`, category: 'maintenance', interval: 'daily',
+ }));
+ });
+
+ afterEach(() => {
+ globalThis.ResizeObserver = realResizeObserver;
+ });
+
+ const chooser = (noun) => screen.getByRole('button', { name: new RegExp(`Choose another ${noun}`) });
+
+ it('leads with the selected stage editor and keeps the catalogue out of the page flow', async () => {
+ await renderPage('/prompts?stage=pipeline-prose-draft');
+ await screen.findByDisplayValue('pipeline-prose-draft template');
+
+ expect(screen.getByRole('button', { name: /^save$/i })).toBeTruthy();
+ expect(screen.queryByLabelText('Search prompt stages')).toBeNull();
+ expect(chooser('stage')).toBeTruthy();
+ });
+
+ it('opens the catalogue in a drawer, keeps unsaved edits, and switches stage from it', async () => {
+ await renderPage('/prompts?stage=pipeline-prose-draft');
+ await screen.findByDisplayValue('pipeline-prose-draft template');
+ fireEvent.change(screen.getByLabelText('Template'), { target: { value: 'edited by hand' } });
+
+ fireEvent.click(chooser('stage'));
+ const drawer = screen.getByRole('dialog', { name: 'Prompt Stages' });
+ expect(within(drawer).getByLabelText('Search prompt stages')).toBeTruthy();
+ // Opening the chooser alone must not touch the edit.
+ expect(screen.getByLabelText('Template').value).toBe('edited by hand');
+
+ // The unsaved-edit guard runs inside the drawer, in the clicked row's slot.
+ fireEvent.click(within(drawer).getByText('Pipeline — Comic Book Script'));
+ expect(within(drawer).getByText(/Discard unsaved changes/)).toBeTruthy();
+ fireEvent.click(within(drawer).getByRole('button', { name: 'Keep editing' }));
+ expect(screen.getByLabelText('Template').value).toBe('edited by hand');
+
+ fireEvent.click(within(drawer).getByText('Pipeline — Comic Book Script'));
+ fireEvent.click(within(drawer).getByRole('button', { name: 'Discard' }));
+ await screen.findByDisplayValue('pipeline-comic-script template');
+ expect(currentSearch()).toContain('stage=pipeline-comic-script');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('shows the catalogue alone when nothing is selected', async () => {
+ await renderPage('/prompts');
+ expect(await screen.findByLabelText('Search prompt stages')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /Choose another/ })).toBeNull();
+ expect(screen.queryByText('Select a stage to edit')).toBeNull();
+ });
+
+ it('offers Retry in the active workspace when the selected stage fails to load', async () => {
+ getPrompt.mockReset().mockRejectedValue(new Error('boom'));
+ await renderPage('/prompts?stage=pipeline-prose-draft');
+ expect(await screen.findByRole('button', { name: 'Retry' })).toBeTruthy();
+ expect(screen.queryByLabelText('Search prompt stages')).toBeNull();
+ });
+
+ it('opens a variable editor first, and a blank draft from the catalogue add button', async () => {
+ await renderPage('/prompts?tab=variables');
+ await screen.findByText('Tone Guide');
+ expect(screen.queryByPlaceholderText('Variable content...')).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Add variable' }));
+ expect(screen.getByText('New Variable')).toBeTruthy();
+ expect(screen.queryByText('Tone Guide')).toBeNull();
+
+ fireEvent.click(chooser('variable'));
+ const drawer = screen.getByRole('dialog', { name: 'Variables' });
+ fireEvent.click(within(drawer).getByText('House Style'));
+ await screen.findByDisplayValue('oxford comma');
+ expect(currentSearch()).toContain('var=house-style');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('opens a job skill editor first with the skills behind the chooser', async () => {
+ await renderPage('/prompts?tab=job-skills&skill=code-fixer');
+ await screen.findByDisplayValue('# code-fixer template');
+ expect(screen.queryByText('doc-writer')).toBeNull();
+
+ fireEvent.click(chooser('job skill'));
+ fireEvent.click(within(screen.getByRole('dialog')).getByText('doc-writer'));
+ await screen.findByDisplayValue('# doc-writer template');
+ expect(currentSearch()).toContain('skill=doc-writer');
+ });
+});