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
feat: status line, header and drawer cleanup on Creative Director and Pipeline issue pages (#9949)
Adam Eivy0fb64da71bcb
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.mdindex 01de46c9ec..094a3c701e 100644--- a/client/src/components/ui/README.md+++ b/client/src/components/ui/README.md@@ -37,6 +37,7 @@ accessibility). Feature-specific components live under their own feature directo| `ProseEditor` | Prose-writing textarea — serif face, relaxed leading, spellcheck. Markdown string in/out. || `ProvenanceChip` | Chip + popover showing where a generated value came from. || `SideBySideDiff` | Columnar word-level diff — old left, new right. |+| `RecordStatusLine` | One status row under a multi-stage record's title — stage in words (toned for waiting / failed), short facts, and a single next-action button (the Music Video status-line pattern, #9858). || `Skeleton` | Loading-placeholder primitives (`SkeletonBlock` / `Lines` / `Card` / `Rows` / `Region`) — what `PageSkeleton` is built from, and what a sub-region loader should reserve its shape with instead of a bare spinner. || `TabPills` | Shared tab nav — `underline` / `pills` / `filter` (toggle chips) families; `mobileCompact` collapses it to an icon row under `sm` (labelled `<select>` when a tab has no icon). || `Toast` | Toast notification system (`toast()`, `.success()`, `.error()`, `.loading()`, `<Toaster />`). |diff --git a/client/src/components/ui/RecordStatusLine.jsx b/client/src/components/ui/RecordStatusLine.jsxnew file mode 100644index 0000000000..c8f54a1b49--- /dev/null+++ b/client/src/components/ui/RecordStatusLine.jsx@@ -0,0 +1,50 @@+import { ArrowRight } from 'lucide-react';++const TONES = {+ error: 'text-port-error',+ muted: 'text-port-text-muted',+ ok: 'text-port-success',+ warn: 'text-port-warning',+};++/**+ * The one "where does this record stand" row under a multi-stage record's+ * title: a headline naming the current stage in words (toned `warn` when it+ * waits on the user, `error` when it failed), short facts, and at most one+ * next-action button. Mirrors the Music Video header's status line (#9858) for+ * the pages that don't share its layout.+ *+ * `status` is `{ headline, tone, facts: [{ id, label, tone }] }`; `nextAction`+ * is `{ label, reason?, disabled?, icon? }` or null. `leading` is an optional+ * node (a back link) that sits before the status text.+ */+export default function RecordStatusLine({+ status, nextAction = null, onNextAction, leading = null, className = '',+}) {+ if (!status) return null;+ const ActionIcon = nextAction?.icon || ArrowRight;+ return (+ <div className={`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 ${className}`}>+ {leading}+ <p role="status" aria-label="Record status" className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-0.5 text-sm">+ <span className={`font-medium ${TONES[status.tone] || ''}`}>{status.headline}</span>+ {status.facts.map((fact) => (+ <span key={fact.id} className={`flex items-center gap-2 text-xs ${TONES[fact.tone] || ''}`}>+ <span aria-hidden="true" className="text-port-text-muted">·</span>{fact.label}+ </span>+ ))}+ </p>+ {nextAction && (+ <button+ type="button"+ onClick={onNextAction}+ disabled={nextAction.disabled}+ title={nextAction.reason}+ className="flex min-h-[44px] shrink-0 items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-sm text-white disabled:opacity-50 sm:min-h-0"+ >+ <ActionIcon size={14} aria-hidden="true" /> {nextAction.label}+ </button>+ )}+ </div>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c668ce0c2b..2a4ac5e7f1 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -77,6 +77,7 @@ grep -i "what you want to do" client/src/lib/README.md| `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. || `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |+| `creativeDirectorStatus.js` | `describeCreativeDirectorStatus(project, { activeAgents, activeTab })` → `{ headline, tone, facts, next }` — the one "where it stands, what's next" status line for a CD project (stage in words, whether it waits on the user, a single `start`/`resume`/`edit-draft`/`goto`/`open-final` next action). Pure; rendered by `components/ui/RecordStatusLine`. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `federatedMediaSupports(status, feature, capability)` mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (`lyrics`, `inputAssets`) from the status-root `features` list, retaining only the legacy `inputAssets` capability block for peers on the previous build because that signal is genuinely per-model, and `peerMediaProviderSnapshot(peer)` returns the status payload to ask it against. `peerModelAcceptsInput(capability, role, status)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. || `fableLoomReadiness.js` | Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting. |@@ -102,6 +103,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `pipelineImageDefaults.js` | Pipeline comic-page image-gen defaults + settings reader. |+| `pipelineIssueStatus.js` | `describePipelineIssueStatus(issue, { stages, labels, autoRunActive, latest, activeStage })` → `{ headline, tone, facts, next }` — the pipeline issue's status line (failed / generating / needs-review / next-empty stage, or the live auto-run frame in words) with the one next action. Pure; rendered by `components/ui/RecordStatusLine`. || `reverseOutlineGrid.js` | `buildPlotlineGrid` (reverse-outline scenes + plotlines → plotline-by-sequence grid rows/cells) + `sceneComponentCount`. Used by the Reverse Outline page. || `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. || `imageGenBackends.js` | Icon metadata, `deriveAvailableBackends`, and `imageGenReadiness(status)` — a compatibility-safe `ready` / `unavailable` / `unknown` read of image-gen status responses; re-exports everything from `imageGenModes.js` so consumers keep one import site. |diff --git a/client/src/lib/creativeDirectorStatus.js b/client/src/lib/creativeDirectorStatus.jsnew file mode 100644index 0000000000..63fc380360--- /dev/null+++ b/client/src/lib/creativeDirectorStatus.js@@ -0,0 +1,70 @@+/**+ * "Where does this Creative Director project stand, and what is the user's next+ * move" — the one status line under the project title (#9949), derived from the+ * project record alone so it can be tested without rendering the page.+ *+ * Returns `{ headline, tone, facts, next }`. `tone` is `warn` while the project+ * waits on the user, `error` when it failed, `ok` when done, else `muted`+ * (the director is working). `next` is `{ id, label, reason, tab? }` or null:+ * `start` / `resume` run the project, `edit-draft` opens the video draft,+ * `goto` opens `tab`, `open-final` opens the delivered video. A `goto` into the+ * tab already on screen is dropped — the work is already in front of the user.+ */++const sceneProgress = (project) => {+ const scenes = project.treatment?.scenes || [];+ if (!scenes.length) return null;+ return `${scenes.filter((scene) => scene.status === 'accepted').length} of ${scenes.length} scenes accepted`;+};++const videoNext = (project, { cut, activeTab }) => {+ const { status } = project;+ if (status === 'draft') return { id: 'edit-draft', label: 'Edit draft', reason: 'Review the brief and production limits, then start from the Overview' };+ if (status === 'paused' || status === 'failed') return { id: 'edit-draft', label: 'Edit production settings', reason: 'Adjust the saved choices before restarting' };+ if (status === 'complete') return null;+ if (cut?.filename && activeTab !== 'review') return { id: 'goto', tab: 'review', label: 'Review the cut', reason: 'Approve or request changes to the assembled cut' };+ return null;+};++const standardNext = (project) => {+ switch (project.status) {+ case 'draft': return { id: 'start', label: 'Start', reason: 'Start the director on this project' };+ case 'paused': return { id: 'resume', label: 'Resume', reason: 'Continue where the director paused' };+ case 'failed': return { id: 'start', label: 'Retry', reason: 'Start the director again from the saved state' };+ case 'complete': return project.finalVideoId ? { id: 'open-final', label: 'Open final video', reason: 'View the delivered video in Media History' } : null;+ default: return null;+ }+};++export function describeCreativeDirectorStatus(project, { activeAgents = 0, activeTab = null } = {}) {+ if (!project) return null;+ const isVideo = project.workspace === 'video';+ const cut = project.videoFinalCut || project.videoRoughCut;+ const cutAwaitingReview = isVideo && !!cut?.filename && !['draft', 'failed', 'complete'].includes(project.status);+ const progress = sceneProgress(project);++ let headline;+ let tone = 'muted';+ switch (project.status) {+ case 'draft': headline = 'Draft · waiting for you to start'; tone = 'warn'; break;+ case 'planning': headline = 'Planning · the director is writing the treatment and plan'; break;+ case 'rendering': headline = progress ? `Rendering · ${progress}` : 'Rendering · the director is generating scenes'; break;+ case 'stitching': headline = 'Stitching · assembling the final video'; break;+ case 'paused': headline = 'Paused · waiting for you to resume'; tone = 'warn'; break;+ case 'failed': headline = `Failed${project.failureReason ? ` · ${project.failureReason}` : ''}`; tone = 'error'; break;+ case 'complete': headline = 'Complete · final video ready'; tone = 'ok'; break;+ default: headline = `Status: ${project.status}`;+ }+ if (cutAwaitingReview) {+ headline = 'Cut ready · waiting for your review';+ tone = 'warn';+ }++ const facts = [];+ if (activeAgents > 0) facts.push({ id: 'agents', label: `${activeAgents} ${activeAgents === 1 ? 'agent' : 'agents'} working`, tone: 'muted' });+ if (progress && project.status !== 'rendering') facts.push({ id: 'scenes', label: progress, tone: 'muted' });++ let next = isVideo ? videoNext(project, { cut, activeTab }) : standardNext(project);+ if (next?.id === 'goto' && next.tab === activeTab) next = null;+ return { headline, tone, facts, next };+}diff --git a/client/src/lib/creativeDirectorStatus.test.js b/client/src/lib/creativeDirectorStatus.test.jsnew file mode 100644index 0000000000..cca9873a33--- /dev/null+++ b/client/src/lib/creativeDirectorStatus.test.js@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import { describeCreativeDirectorStatus } from './creativeDirectorStatus.js';++const project = (overrides = {}) => ({ id: 'cd-example', name: 'Example project', status: 'draft', ...overrides });++describe('describeCreativeDirectorStatus', () => {+ it('names a project waiting on the user and offers the one action that unblocks it', () => {+ const draft = describeCreativeDirectorStatus(project());+ expect(draft).toMatchObject({ tone: 'warn', headline: 'Draft · waiting for you to start', next: { id: 'start', label: 'Start' } });+ expect(describeCreativeDirectorStatus(project({ status: 'paused' })).next).toMatchObject({ id: 'resume', label: 'Resume' });+ // A video draft is edited, not started from the header.+ expect(describeCreativeDirectorStatus(project({ workspace: 'video' })).next).toMatchObject({ id: 'edit-draft' });+ });++ it('sends a video with a cut to review, but not when the review tab is already open', () => {+ const video = project({ workspace: 'video', status: 'stitching', videoRoughCut: { filename: 'cut.mp4' } });+ const status = describeCreativeDirectorStatus(video, { activeTab: 'overview' });+ expect(status).toMatchObject({ tone: 'warn', headline: 'Cut ready · waiting for your review', next: { id: 'goto', tab: 'review' } });+ expect(describeCreativeDirectorStatus(video, { activeTab: 'review' }).next).toBeNull();+ });++ it('reports a running project in words with its scene progress and working agents, and no action', () => {+ const status = describeCreativeDirectorStatus(project({+ status: 'rendering',+ treatment: { scenes: [{ status: 'accepted' }, { status: 'rendering' }, { status: 'pending' }] },+ }), { activeAgents: 2 });+ expect(status).toMatchObject({ tone: 'muted', headline: 'Rendering · 1 of 3 scenes accepted', next: null });+ expect(status.facts).toEqual([{ id: 'agents', label: '2 agents working', tone: 'muted' }]);+ });++ it('surfaces why a failed project failed and offers a retry', () => {+ expect(describeCreativeDirectorStatus(project({ status: 'failed', failureReason: 'Render queue unavailable' })))+ .toMatchObject({ tone: 'error', headline: 'Failed · Render queue unavailable', next: { id: 'start', label: 'Retry' } });+ });++ it('points a delivered project at its final video', () => {+ expect(describeCreativeDirectorStatus(project({ status: 'complete', finalVideoId: 'job-1' })))+ .toMatchObject({ tone: 'ok', next: { id: 'open-final' } });+ expect(describeCreativeDirectorStatus(project({ status: 'complete' })).next).toBeNull();+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 23dafcaa93..c85d3c2205 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -40,6 +40,7 @@ export * from './characterIntegrity.js';export * from './catalogTypes.js';export * from './creativeDirectorPlan.js';export * from './creativeDirectorPreview.js';+export * from './creativeDirectorStatus.js';export * from './editorialRoadmap.js';export * from './eidoverseDraftReconcile.js';export * from './eidoverseWorldReset.js';@@ -80,6 +81,7 @@ export * from './musicVideoAutomation.js';export * from './musicVideoAutonomous.js';export * from './musicVideoPreview.js';export * from './pipelineImageDefaults.js';+export * from './pipelineIssueStatus.js';export * from './reverseOutlineGrid.js';export * from './reviewerModels.js';export * from './reviewerPins.js';diff --git a/client/src/lib/pipelineIssueStatus.js b/client/src/lib/pipelineIssueStatus.jsnew file mode 100644index 0000000000..a392020e81--- /dev/null+++ b/client/src/lib/pipelineIssueStatus.js@@ -0,0 +1,65 @@+import { formatCount } from '../utils/formatters.js';++/**+ * "Where does this pipeline issue stand, and what is the user's next move" — the+ * one status line under the issue title (#9949), derived from the issue's stage+ * records plus the live auto-run frame so it can be tested without the page.+ *+ * `stages` is the ordered list of visible stage ids, `labels` maps id → label.+ * Returns `{ headline, tone, facts, next }`: `tone` is `error` for a failed+ * stage, `warn` while a stage waits on the user, `ok` when every stage is+ * ready, else `muted`. `next` is `{ id: 'cancel-auto-run' }` during a run or+ * `{ id: 'goto', stage, label, reason }` pointing at the stage to open (dropped+ * when that stage is already on screen).+ */++// Stage statuses that mean the stage has produced something the user can build on.+const READY = new Set(['ready', 'edited']);++// The auto-run SSE frame, in words. Null while nothing has been reported yet.+function describeFrame(frame, labels) {+ const label = labels[frame?.stage] || frame?.stage;+ switch (frame?.type) {+ case 'stage:start': return `Generating ${label}…`;+ case 'stage:complete':+ return frame.stage === 'episodeVideo'+ ? `${label} kicked off — ${frame.scenes} ${frame.scenes === 1 ? 'scene' : 'scenes'} queued in Creative Director`+ : `${label} ready (${formatCount(frame.length)} chars)`;+ case 'stage:error': return `${label} error — ${frame.error}`;+ case 'skip': return `${label} skipped — ${frame.reason}`;+ case 'start': return 'Starting auto-run…';+ default: return null;+ }+}++export function describePipelineIssueStatus(issue, { stages, labels, autoRunActive = false, latest = null, activeStage = null } = {}) {+ if (!issue) return null;+ const statusOf = (id) => issue.stages?.[id]?.status || 'empty';+ const ready = stages.filter((id) => READY.has(statusOf(id)));+ const facts = [{ id: 'progress', label: `${ready.length} of ${stages.length} stages ready`, tone: 'muted' }];+ const goto = (stage, verb) => (stage === activeStage ? null : { id: 'goto', stage, label: `${verb} ${labels[stage]}`, reason: `Open the ${labels[stage]} stage` });++ if (autoRunActive) {+ const frame = describeFrame(latest, labels);+ return {+ headline: `Auto-run in progress${frame ? ` · ${frame}` : ''}`,+ tone: latest?.type === 'stage:error' ? 'error' : 'muted',+ facts,+ next: { id: 'cancel-auto-run', label: 'Cancel auto-run', reason: 'Stop the auto-run after the current stage' },+ };+ }++ const failed = stages.find((id) => statusOf(id) === 'error');+ if (failed) {+ // `errorMessage` is the server's persisted failure text (up to 4000 chars) — one line here.+ const reason = (issue.stages?.[failed]?.errorMessage || '').slice(0, 160);+ return { headline: `${labels[failed]} failed${reason ? ` · ${reason}` : ''}`, tone: 'error', facts, next: goto(failed, 'Open') };+ }+ const generating = stages.find((id) => statusOf(id) === 'generating');+ if (generating) return { headline: `Generating ${labels[generating]}`, tone: 'muted', facts, next: null };+ const review = stages.find((id) => statusOf(id) === 'needs-review');+ if (review) return { headline: `${labels[review]} needs your review`, tone: 'warn', facts, next: goto(review, 'Review') };+ const empty = stages.find((id) => statusOf(id) === 'empty');+ if (empty) return { headline: `Next up: ${labels[empty]} · waiting for you to start it`, tone: 'warn', facts, next: goto(empty, 'Open') };+ return { headline: 'All stages ready', tone: 'ok', facts, next: null };+}diff --git a/client/src/lib/pipelineIssueStatus.test.js b/client/src/lib/pipelineIssueStatus.test.jsnew file mode 100644index 0000000000..64b1c4f792--- /dev/null+++ b/client/src/lib/pipelineIssueStatus.test.js@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { describePipelineIssueStatus } from './pipelineIssueStatus.js';++const stages = ['idea', 'prose', 'comicScript'];+const labels = { idea: 'Idea', prose: 'Prose', comicScript: 'Comic' };+const issue = (statuses, extra = {}) => ({+ stages: Object.fromEntries(Object.entries(statuses).map(([id, status]) => [id, { status, ...extra[id] }])),+});+const describe_ = (statuses, opts = {}, extra) => describePipelineIssueStatus(issue(statuses, extra), { stages, labels, ...opts });++describe('describePipelineIssueStatus', () => {+ it('names the next stage waiting on the user, and drops the action when that stage is already open', () => {+ const waiting = describe_({ idea: 'ready', prose: 'empty', comicScript: 'empty' }, { activeStage: 'idea' });+ expect(waiting).toMatchObject({ tone: 'warn', headline: 'Next up: Prose · waiting for you to start it', next: { id: 'goto', stage: 'prose', label: 'Open Prose' } });+ expect(waiting.facts[0].label).toBe('1 of 3 stages ready');+ expect(describe_({ idea: 'ready', prose: 'empty' }, { activeStage: 'prose' }).next).toBeNull();+ expect(describe_({ idea: 'ready', prose: 'needs-review' }, { activeStage: 'idea' }))+ .toMatchObject({ tone: 'warn', headline: 'Prose needs your review', next: { stage: 'prose', label: 'Review Prose' } });+ });++ it('describes a live auto-run from its latest frame and offers cancel', () => {+ const running = describe_({ idea: 'ready' }, { autoRunActive: true, latest: { type: 'stage:start', stage: 'prose' } });+ expect(running).toMatchObject({ tone: 'muted', headline: 'Auto-run in progress · Generating Prose…', next: { id: 'cancel-auto-run' } });+ expect(describe_({}, { autoRunActive: true, latest: null }).headline).toBe('Auto-run in progress');+ expect(describe_({}, { autoRunActive: true, latest: { type: 'stage:error', stage: 'prose', error: 'quota' } }))+ .toMatchObject({ tone: 'error', headline: 'Auto-run in progress · Prose error — quota' });+ });++ it('reports a failed stage with its reason ahead of anything else', () => {+ const failed = describe_({ idea: 'ready', prose: 'error', comicScript: 'needs-review' }, { activeStage: 'idea' }, { prose: { errorMessage: 'Provider timed out' } });+ expect(failed).toMatchObject({ tone: 'error', headline: 'Prose failed · Provider timed out', next: { stage: 'prose', label: 'Open Prose' } });+ });++ it('reports generation in progress and completion without an action', () => {+ expect(describe_({ idea: 'ready', prose: 'generating' })).toMatchObject({ tone: 'muted', headline: 'Generating Prose', next: null });+ expect(describe_({ idea: 'ready', prose: 'edited', comicScript: 'ready' })).toMatchObject({ tone: 'ok', headline: 'All stages ready', next: null });+ });+});diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 70a60abea0..dc47decd16 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -1,6 +1,8 @@import { useEffect, useState, useCallback, useRef } from 'react';import { useParams, useNavigate, useSearchParams, Link } from 'react-router';-import { ArrowLeft, ClipboardList, Eye, Film, FileText, LayoutList, Package, Play, Pause, RefreshCw, ScrollText, SlidersHorizontal, Square, Trash2 } from 'lucide-react';+import { ArrowLeft, Clapperboard, ClipboardList, Eye, Film, FileText, LayoutList, Package, Pause, ScrollText, SlidersHorizontal, Square, Trash2 } from 'lucide-react';+import PageHeader from '../components/PageHeader.jsx';+import RecordStatusLine from '../components/ui/RecordStatusLine.jsx';import TabPills from '../components/ui/TabPills.jsx';import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';@@ -30,6 +32,7 @@ import { getCosAgents } from '../services/apiAgents.js';import { useSocketResource } from '../hooks/useSocketResource';import { useValidTab } from '../hooks/useValidTab';import useMediaJobProgress from '../hooks/useMediaJobProgress';+import { describeCreativeDirectorStatus } from '../lib/creativeDirectorStatus.js';const PROJECT_EVENTS = ['creative-director:project:changed'];const AGENT_EVENTS = ['cos:agent:spawned', 'cos:agent:completed', 'cos:agent:updated'];@@ -192,90 +195,90 @@ function CreativeDirectorProject({ id, basePath }) {if (!project || project.id !== id) return <div className="p-6 text-port-error">Project not found.</div>;const goTo = (tabId) => navigate(`${basePath}/${id}/${tabId}`);+ const status = describeCreativeDirectorStatus(project, { activeAgents: activeAgents.length, activeTab });+ const runNext = () => {+ switch (status.next?.id) {+ case 'start': case 'resume': return handleAction(status.next.id);+ case 'edit-draft': return setEditingDraft(true);+ case 'goto': return goTo(status.next.tab);+ case 'open-final': return navigate(`/media/history?selected=${encodeURIComponent(project.finalVideoId)}`);+ default: return undefined;+ }+ };+ // Every tab keeps the assembled cut in view once there is one; the Overview+ // renders it itself (with the "final assembly" placeholder before then).+ const showCutAbove = project.workspace === 'video' && activeTab !== 'overview' && !!(project.videoFinalCut || project.videoRoughCut)?.filename;return (<div className="flex flex-col h-full">- <div className="shrink-0 px-6 pt-6 pb-3 border-b border-port-border">- <div className="flex items-center justify-between gap-3">- <div className="flex items-center gap-3 min-w-0">- <Link to={basePath} className="text-port-text-muted hover:text-port-text"><ArrowLeft className="w-4 h-4" /></Link>- <div className="min-w-0">- <h1 className="line-clamp-2 break-words text-xl font-semibold" title={project.name}>{project.name}</h1>- <div className="text-xs text-port-text-muted truncate">- {project.id} • status: <span className="text-port-text">{project.status}</span>- </div>- </div>- </div>- <div className="flex flex-wrap justify-end gap-1">- <button onClick={fetchProject} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">- <RefreshCw className="w-3 h-3" /> Refresh- </button>- <button onClick={() => setModelsOpen(true)} title="AI provider + model for this project's treatment, plan, and scene evaluation" className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">- <SlidersHorizontal className="w-3 h-3" /> Models+ <PageHeader+ icon={Clapperboard}+ title={project.name}+ actions={<>+ <button onClick={() => setModelsOpen(true)} title="AI provider + model for this project's treatment, plan, and scene evaluation" className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">+ <SlidersHorizontal className="w-3 h-3" /> Models+ </button>+ {!['paused', 'complete', 'failed', 'draft'].includes(project.status) && (+ <button onClick={() => handleAction('pause')} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">+ <Pause className="w-3 h-3" /> Pause</button>- {project.workspace !== 'video' && (project.status === 'draft' || project.status === 'failed') && (- <button onClick={() => handleAction('start')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">- <Play className="w-3 h-3" /> Start- </button>- )}- {project.workspace !== 'video' && project.status === 'paused' && (- <button onClick={() => handleAction('resume')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">- <Play className="w-3 h-3" /> Resume- </button>- )}- {!['paused', 'complete', 'failed', 'draft'].includes(project.status) && (- <button onClick={() => handleAction('pause')} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">- <Pause className="w-3 h-3" /> Pause- </button>- )}- {!['complete', 'failed', 'draft'].includes(project.status) && (- isConfirmingStop(project.id) ? (- <ConfirmButtonPair- prompt="Stop?"- confirmText="Stop"- ariaLabel={`Confirm stop project ${project.name}`}- onConfirm={() => confirmStop(() => handleAction('stop'))}- onCancel={cancelStop}- />- ) : (- <button- type="button"- onClick={() => requestStop(project.id)}- title="Stop: kill the running agent, retire its queued tasks, and cancel pending renders. Pause only stops NEW work being queued."- aria-label={`Stop project ${project.name}`}- className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs hover:text-port-error"- >- <Square className="w-3 h-3" /> Stop- </button>- )- )}- {isConfirmingDelete(project.id) ? (+ )}+ {!['complete', 'failed', 'draft'].includes(project.status) && (+ isConfirmingStop(project.id) ? (<ConfirmButtonPair- prompt="Delete?"- confirmText="Delete"- ariaLabel={`Confirm delete project ${project.name}`}- onConfirm={() => confirmDelete(handleDelete)}- onCancel={cancelDelete}+ prompt="Stop?"+ confirmText="Stop"+ ariaLabel={`Confirm stop project ${project.name}`}+ onConfirm={() => confirmStop(() => handleAction('stop'))}+ onCancel={cancelStop}/>) : (<buttontype="button"- onClick={() => requestDelete(project.id)}- disabled={deleting}- title={deleting ? 'Deleting Creative Director project…' : 'Delete this Creative Director project'}- aria-label={`${deleting ? 'Deleting' : 'Delete'} project ${project.name}`}- aria-busy={deleting}- className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs hover:bg-port-error/20 hover:text-port-error disabled:opacity-50"+ onClick={() => requestStop(project.id)}+ title="Stop: kill the running agent, retire its queued tasks, and cancel pending renders. Pause only stops NEW work being queued."+ aria-label={`Stop project ${project.name}`}+ className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs hover:text-port-error">- <Trash2 className="w-3 h-3" /> {deleting ? 'Deleting…' : 'Delete'}+ <Square className="w-3 h-3" /> Stop</button>- )}- </div>- </div>- <TabPills tabs={tabs} activeTab={activeTab} onChange={goTo} mobileCompact ariaLabel="Video project sections" className="mt-3" />+ )+ )}+ {isConfirmingDelete(project.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ confirmText="Delete"+ ariaLabel={`Confirm delete project ${project.name}`}+ onConfirm={() => confirmDelete(handleDelete)}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(project.id)}+ disabled={deleting}+ title={deleting ? 'Deleting Creative Director project…' : 'Delete this Creative Director project'}+ aria-label={`${deleting ? 'Deleting' : 'Delete'} project ${project.name}`}+ aria-busy={deleting}+ className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs hover:bg-port-error/20 hover:text-port-error disabled:opacity-50"+ >+ <Trash2 className="w-3 h-3" /> {deleting ? 'Deleting…' : 'Delete'}+ </button>+ )}+ </>}+ />+ <div className="shrink-0 space-y-2 border-b border-port-border px-3 py-2 sm:px-4">+ <RecordStatusLine+ status={status}+ nextAction={status.next}+ onNextAction={runNext}+ leading={<Link to={basePath} aria-label="Back to projects" className="text-port-text-muted hover:text-port-text"><ArrowLeft className="w-4 h-4" /></Link>}+ />+ <TabPills tabs={tabs} activeTab={activeTab} onChange={goTo} mobileCompact ariaLabel="Video project sections" /></div><div className="flex-1 overflow-auto p-6">+ {showCutAbove && <div className="mb-4"><VideoCutPanel project={project} /></div>}{project.workspace === 'video' && activeTab === 'review' && <VideoReviewPanel key={project.id} project={project} onChange={fetchProject} />}<ActiveAgentsBanner agents={activeAgents} />@@ -288,7 +291,6 @@ function CreativeDirectorProject({ id, basePath }) {{['draft', 'paused', 'failed'].includes(project.status) && <button onClick={() => setEditingDraft(true)} className="px-3 py-2 rounded bg-port-accent text-white">{project.status === 'draft' ? 'Edit draft' : 'Edit production settings'}</button>}<VideoCutPanel project={project} /><VideoExecutionPanel key={project.id} project={project} onChange={fetchProject} basePath={basePath} />- <VideoDraftDrawer open={editingDraft} onClose={() => setEditingDraft(false)} project={project} onSaved={saved => setProject(prev => ({ ...prev, ...saved }))} /></section>}{project.workspace !== 'video' && activeTab === 'overview' && (<OverviewTab@@ -309,6 +311,9 @@ function CreativeDirectorProject({ id, basePath }) {{activeTab === 'runs' && <RunsTab project={project} />}</div>+ {/* Page-level, not inside the Overview: the status line's "Edit draft" opens it from any tab. */}+ {project.workspace === 'video' && <VideoDraftDrawer open={editingDraft} onClose={() => setEditingDraft(false)} project={project} onSaved={saved => setProject(prev => ({ ...prev, ...saved }))} />}+<CreativeDirectorModelsDraweropen={modelsOpen}onClose={() => setModelsOpen(false)}diff --git a/client/src/pages/CreativeDirectorDetail.test.jsx b/client/src/pages/CreativeDirectorDetail.test.jsxindex 754180ec5f..16a1e3b173 100644--- a/client/src/pages/CreativeDirectorDetail.test.jsx+++ b/client/src/pages/CreativeDirectorDetail.test.jsx@@ -307,3 +307,50 @@ describe('CreativeDirectorDetail realtime project lifecycle', () => {expect(screen.getByRole('heading', { name: 'Started project' })).toBeInTheDocument();});});++describe('CreativeDirectorDetail status line', () => {+ const statusLine = () => screen.getByRole('status', { name: 'Record status' });+ beforeEach(() => vi.clearAllMocks());++ it('says a draft waits on the user and offers Start above the fold, with no Refresh button or raw id', async () => {+ cdApi.getCreativeDirectorProject.mockResolvedValue(PROJECT);+ await renderPage();+ expect(statusLine()).toHaveTextContent('Draft · waiting for you to start');+ expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Refresh/ })).not.toBeInTheDocument();+ // The raw id is no longer part of the header (the location probe is the test's own).+ expect(screen.getByRole('heading', { name: PROJECT.name }).closest('div[class*="border-b"]')).not.toHaveTextContent(PROJECT.id);+ });++ it('names a running project and its scene progress without offering a start action', async () => {+ cdApi.getCreativeDirectorProject.mockResolvedValue({+ ...PROJECT, status: 'rendering', treatment: { scenes: [{ status: 'accepted' }, { status: 'rendering' }] },+ });+ await renderPage();+ expect(statusLine()).toHaveTextContent('Rendering · 1 of 2 scenes accepted');+ expect(screen.queryByRole('button', { name: /^(Start|Resume|Retry)$/ })).not.toBeInTheDocument();+ });++ it('reports a failed project with its reason and retries through the same start action', async () => {+ const user = userEvent.setup();+ cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, status: 'failed', failureReason: 'Render queue unavailable' });+ cdApi.startCreativeDirectorProject.mockResolvedValue({ ok: true, project: { ...PROJECT, status: 'planning' } });+ await renderPage();+ expect(statusLine()).toHaveTextContent('Failed · Render queue unavailable');+ await user.click(screen.getByRole('button', { name: 'Retry' }));+ expect(cdApi.startCreativeDirectorProject).toHaveBeenCalledWith(PROJECT.id, { silent: true });+ });++ it('keeps the assembled video in view on every tab once a cut exists', async () => {+ const cut = { videoId: 'job-example', filename: 'example.mp4', durationSeconds: 12, audioMode: 'music' };+ cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, workspace: 'video', status: 'stitching', videoRoughCut: cut });+ render(+ <MemoryRouter initialEntries={['/video/cd-example/runs']}>+ <Routes><Route path="/video/:id/:tab" element={<CreativeDirectorDetail basePath="/video" />} /></Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByRole('region', { name: 'Assembled video' })).toBeInTheDocument();+ expect(statusLine()).toHaveTextContent('Cut ready · waiting for your review');+ expect(screen.getByRole('button', { name: 'Review the cut' })).toBeInTheDocument();+ });+});diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex a055cd5721..9202ab8754 100644--- a/client/src/pages/PipelineIssue.jsx+++ b/client/src/pages/PipelineIssue.jsx@@ -3,18 +3,20 @@** Tab-driven stage navigation per /pipeline/issues/:issueId/:stage. Top action* bar exposes the auto-run-text button which kicks off idea→prose→(comicScript- * + teleplay) and streams progress via SSE.+ * + teleplay) and streams progress via SSE; a status line under the title names+ * where the issue stands and the one next action.*/import { useEffect, useRef, useState, useMemo } from 'react';-import { Link, useParams, useNavigate } from 'react-router';+import { Link, useParams, useNavigate, useSearchParams } from 'react-router';import {- ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,+ ArrowLeft, Sparkles, Loader2, Lightbulb, BookOpen, FileText, Film as FilmIcon,LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings, Mic, Lock, Unlock,} from 'lucide-react';import toast from '../components/ui/Toast';import PageSkeleton from '../components/ui/PageSkeleton';-import Modal from '../components/ui/Modal';+import Drawer from '../components/Drawer';+import RecordStatusLine from '../components/ui/RecordStatusLine';import TabPills from '../components/ui/TabPills';import {getPipelineConfig, getPipelineIssue, getPipelineSeries, updatePipelineIssue,@@ -38,11 +40,11 @@ import LengthProfilePicker from '../components/pipeline/LengthProfilePicker';import ArcRolePicker from '../components/pipeline/ArcRolePicker';import CatalogCastPanel from '../components/CatalogCastPanel';import { VisualGenSettingsPanel } from '../components/pipeline/stages/VisualGenSettings';-import { formatCount } from '../utils/formatters';+import { describePipelineIssueStatus } from '../lib/pipelineIssueStatus';// Stages that surface a header-level settings gear. The Comic editor// (`comicScript`) owns its own image-gen drawer inside ComicScriptStage,-// so it stays off this list — only Storyboards needs the shared modal.+// so it stays off this list — only Storyboards needs the shared drawer.const VISUAL_STAGE_LABELS = {storyboards: 'Storyboards',};@@ -105,13 +107,18 @@ export default function PipelineIssue() {const [loading, setLoading] = useState(true);const [autoRunStarting, setAutoRunStarting] = useState(false);const [autoRunActive, setAutoRunActive] = useState(false);- const [settingsOpen, setSettingsOpen] = useState(false);+ // Deep-linkable open state for the per-stage generation settings drawer; the+ // stage tabs navigate without a query string, so switching stage closes it.+ const [searchParams, setSearchParams] = useSearchParams();+ const settingsOpen = searchParams.get('settings') === '1';+ const setSettingsOpen = (next) => setSearchParams((prev) => {+ const params = new URLSearchParams(prev);+ if (next) params.set('settings', '1'); else params.delete('settings');+ return params;+ }, { replace: !next });const [lengthProfileSaving, setLengthProfileSaving] = useState(false);const [arcRoleSaving, setArcRoleSaving] = useState(false);const [genConfigSaving, setGenConfigSaving] = useState(false);- // Close the settings modal whenever the active stage changes so it doesn't- // reopen unexpectedly when the user returns to a previously-visited stage.- useEffect(() => { setSettingsOpen(false); }, [stageId]);const { latest, frames } = usePipelineProgress(pipelineAutoRunSseUrl, [issueId], { enabled: autoRunActive });useEffect(() => {@@ -200,7 +207,7 @@ export default function PipelineIssue() {.finally(() => setArcRoleSaving(false));};- // Persist genConfig changes from the header settings modal. The active+ // Persist genConfig changes from the header settings drawer. The active// visual stage owns the config record (we keep per-stage genConfig so a// user can pin "codex" for comicPages but "local" for storyboards).const handleGenConfigChange = async (next) => {@@ -303,6 +310,19 @@ export default function PipelineIssue() {? `${PIPELINE_STAGE_LABELS[stageId]} stage is locked — unlock it to regenerate`: ambientLockHint;+ const statusStages = stageTabs.map((tab) => tab.id).filter((id) => id !== 'nouns');+ const status = describePipelineIssueStatus(issue, {+ stages: statusStages,+ labels: PIPELINE_STAGE_LABELS,+ autoRunActive,+ latest,+ activeStage: stageId,+ });+ const runNext = () => {+ if (status?.next?.id === 'cancel-auto-run') handleCancelAutoRun();+ else if (status?.next?.id === 'goto') navigate(`/pipeline/issues/${issueId}/${status.next.stage}`);+ };+if (loading) {return (<PageSkeleton@@ -371,15 +391,6 @@ export default function PipelineIssue() {disabled={autoRunStarting || autoRunActive}/>) : null}- {autoRunActive && (- <button- type="button"- onClick={handleCancelAutoRun}- className="inline-flex items-center gap-1 px-3 py-2 rounded-lg bg-port-card border border-port-border text-port-error text-sm"- >- <X size={14} /> Cancel auto-run- </button>- )}<buttontype="button"onClick={() => handleAutoRun({})}@@ -435,16 +446,7 @@ export default function PipelineIssue() {</div></div>- {autoRunActive && latest ? (- <div className="text-xs text-gray-400">- {latest.type === 'stage:start' && <>Generating <span className="text-white">{PIPELINE_STAGE_LABELS[latest.stage]}</span>…</>}- {latest.type === 'stage:complete' && latest.stage === 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} kicked off — {latest.scenes} scene{latest.scenes === 1 ? '' : 's'} queued in Creative Director</>}- {latest.type === 'stage:complete' && latest.stage !== 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} ready ({formatCount(latest.length)} chars)</>}- {latest.type === 'stage:error' && <>{PIPELINE_STAGE_LABELS[latest.stage]} error — {latest.error}</>}- {latest.type === 'skip' && <>{PIPELINE_STAGE_LABELS[latest.stage]} skipped — {latest.reason}</>}- {latest.type === 'start' && <>Starting auto-run…</>}- </div>- ) : null}+ <RecordStatusLine status={status} nextAction={status?.next} onNextAction={runNext} /></div>{/* Stage tabs */}@@ -484,10 +486,10 @@ export default function PipelineIssue() {{['prose', 'comicScript', 'teleplay'].includes(stageId) ? (<IssueJudgePanel issue={issue} stageId={stageId} />) : null}- {/* Frames log for debugging during auto-run — collapsed but available. */}+ {/* Raw auto-run progress frames — the only place JSON renders, collapsed. */}{frames.length > 0 ? (<details className="mt-6 text-xs text-gray-600">- <summary className="cursor-pointer text-gray-500">Auto-run frames ({frames.length})</summary>+ <summary className="cursor-pointer text-gray-500">Debug details · auto-run frames ({frames.length})</summary><pre className="mt-2 p-3 bg-port-bg border border-port-border rounded overflow-auto max-h-64">{frames.map((f) => JSON.stringify(f)).join('\n')}</pre></details>) : null}@@ -495,29 +497,20 @@ export default function PipelineIssue() {{/* Per-stage generation settings — only available on visual stages. */}{isVisualStage && (- <Modal open={settingsOpen} onClose={() => setSettingsOpen(false)} size="lg" ariaLabel="Generation settings">- <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">- <div className="flex items-center justify-between">- <h2 className="text-base font-semibold text-white">- {VISUAL_STAGE_LABELS[stageId]} — Generation settings- </h2>- <button- type="button"- onClick={() => setSettingsOpen(false)}- className="p-1 text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center"- aria-label="Close"- >- <X size={16} />- </button>- </div>- <VisualGenSettingsPanel- value={issue.stages?.[stageId]?.genConfig || null}- onChange={handleGenConfigChange}- stageLabel={VISUAL_STAGE_LABELS[stageId]}- series={series}- />- </div>- </Modal>+ <Drawer+ open={settingsOpen}+ onClose={() => setSettingsOpen(false)}+ title={`${VISUAL_STAGE_LABELS[stageId]} — Generation settings`}+ size="md"+ closeLabel="Close generation settings"+ >+ <VisualGenSettingsPanel+ value={issue.stages?.[stageId]?.genConfig || null}+ onChange={handleGenConfigChange}+ stageLabel={VISUAL_STAGE_LABELS[stageId]}+ series={series}+ />+ </Drawer>)}</div>);diff --git a/client/src/pages/PipelineIssue.test.jsx b/client/src/pages/PipelineIssue.test.jsxnew file mode 100644index 0000000000..d97bec7387--- /dev/null+++ b/client/src/pages/PipelineIssue.test.jsx@@ -0,0 +1,111 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++const progress = vi.hoisted(() => ({ latest: null, frames: [] }));+vi.mock('../hooks/usePipelineProgress', () => ({ usePipelineProgress: () => progress }));+vi.mock('../services/api', async (importOriginal) => ({+ ...(await importOriginal()),+ getPipelineConfig: vi.fn(async () => ({ arcRoles: [] })),+ getPipelineIssue: vi.fn(),+ getPipelineSeries: vi.fn(),+ updatePipelineIssue: vi.fn(),+ startPipelineAutoRunText: vi.fn(),+ cancelPipelineAutoRunText: vi.fn(async () => ({})),+ pipelineAutoRunSseUrl: () => '/sse',+}));+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));+vi.mock('../components/pipeline/stages/IdeaStage', () => ({ default: () => <div>Idea stage</div> }));+vi.mock('../components/pipeline/stages/ProseStage', () => ({ default: () => <div>Prose stage</div> }));+vi.mock('../components/pipeline/stages/NounsStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/ComicScriptStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/TeleplayStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/ComicPagesStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/StoryboardsStage', () => ({ default: () => <div>Storyboards stage</div> }));+vi.mock('../components/pipeline/stages/EpisodeVideoStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/AudioStage', () => ({ default: () => null }));+vi.mock('../components/pipeline/IssueJudgePanel', () => ({ default: () => null }));+vi.mock('../components/pipeline/SeriesLlmPicker', () => ({ default: () => null }));+vi.mock('../components/pipeline/LengthProfilePicker', () => ({ default: () => null }));+vi.mock('../components/pipeline/ArcRolePicker', () => ({ default: () => null }));+vi.mock('../components/CatalogCastPanel', () => ({ default: () => null }));+vi.mock('../components/pipeline/stages/VisualGenSettings', () => ({ VisualGenSettingsPanel: () => <div>Visual settings form</div> }));++import * as api from '../services/api';+import PipelineIssue from './PipelineIssue';++const issueWith = (stages) => ({+ id: 'issue-example', seriesId: 'series-example', number: 3, title: 'Example issue',+ stages: Object.fromEntries(Object.entries(stages).map(([id, status]) => [id, typeof status === 'string' ? { status } : status])),+});++function LocationProbe() {+ const { pathname, search } = useLocation();+ return <div data-testid="location">{pathname}{search}</div>;+}++const renderIssue = async (issue, path = '/pipeline/issues/issue-example/idea') => {+ api.getPipelineIssue.mockResolvedValue(issue);+ api.getPipelineSeries.mockResolvedValue({ id: 'series-example', name: 'Example series', targetFormat: 'video' });+ render(+ <MemoryRouter initialEntries={[path]}>+ <LocationProbe />+ <Routes><Route path="/pipeline/issues/:issueId/:stage" element={<PipelineIssue />} /></Routes>+ </MemoryRouter>,+ );+ await screen.findByRole('heading', { name: /Example issue/ });+};+const statusLine = () => screen.getByRole('status', { name: 'Record status' });++describe('PipelineIssue status line', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ progress.latest = null;+ progress.frames = [];+ });++ it('names the next waiting stage above the tabs and opens it from the next-action button', async () => {+ const user = userEvent.setup();+ await renderIssue(issueWith({ idea: 'ready', prose: 'empty' }));+ expect(statusLine()).toHaveTextContent('Next up: Prose · waiting for you to start it');+ await user.click(screen.getByRole('button', { name: 'Open Prose' }));+ expect(screen.getByTestId('location')).toHaveTextContent('/pipeline/issues/issue-example/prose');+ });++ it('describes a running auto-run in words and cancels it from the status line', async () => {+ const user = userEvent.setup();+ api.startPipelineAutoRunText.mockResolvedValue({});+ await renderIssue(issueWith({ idea: 'ready', prose: 'empty' }));+ progress.latest = { type: 'stage:start', stage: 'prose' };+ await user.click(screen.getByRole('button', { name: /Auto-run text/ }));+ expect(statusLine()).toHaveTextContent('Auto-run in progress · Generating Prose…');+ await user.click(within(statusLine().parentElement).getByRole('button', { name: 'Cancel auto-run' }));+ expect(api.cancelPipelineAutoRunText).toHaveBeenCalledWith('issue-example', { silent: true });+ });++ it('reports a failed stage with its reason', async () => {+ await renderIssue(issueWith({ idea: 'ready', prose: { status: 'error', errorMessage: 'Provider timed out' } }));+ expect(statusLine()).toHaveTextContent('Prose failed · Provider timed out');+ expect(screen.getByRole('button', { name: 'Open Prose' })).toBeInTheDocument();+ });++ it('keeps raw progress frames inside a named debug disclosure', async () => {+ progress.frames = [{ type: 'stage:start', stage: 'prose' }];+ await renderIssue(issueWith({ idea: 'ready' }));+ const disclosure = screen.getByText(/Debug details/).closest('details');+ expect(disclosure).not.toHaveAttribute('open');+ expect(disclosure).toHaveTextContent('"type":"stage:start"');+ expect(document.body.textContent.split('"type":"stage:start"')).toHaveLength(2);+ });++ it('opens per-stage generation settings in a deep-linkable drawer', async () => {+ const user = userEvent.setup();+ await renderIssue(issueWith({ idea: 'ready', storyboards: 'ready' }), '/pipeline/issues/issue-example/storyboards');+ expect(screen.queryByText('Visual settings form')).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Storyboards generation settings' }));+ expect(screen.getByTestId('location')).toHaveTextContent('?settings=1');+ expect(screen.getByText('Visual settings form')).toBeInTheDocument();+ expect(screen.getByText('Storyboards — Generation settings')).toBeInTheDocument();+ });+});