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
Route Creative Commission editing to a detail page with render history
Adam Eivy0f5d762cc157
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c0d9174ab2..58969ee0bf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,8 @@## Changed+- **Clicking a Creative Commission now opens its own page showing every render it has made.** A commission used to open a sidebar edit form; it now navigates to a routed detail page (`/creative-commission/:id`) that leads with a gallery of every render the commission has produced — each run's final video (with an inline play badge), rendered scene, or produced image, newest first — above the full editable brief/schedule/generation config. Rate a render 👍/👎 and add a note right on its card to steer the next run, run the commission now, pause it, or delete it from the header. The render, its Creative Director output, and the open commission are all directly shareable and bookmarkable (the URL is the source of truth), and a notification about a scheduled run deep-links straight to the render. Creating a new commission still uses the quick "New Commission" drawer on the index; a run whose project was pruned degrades to a status-only card with its output link intact.+- [issue-2702] **The Creative Director now shows you what it made.** Project cards on `/creative-director` lead with a preview of the produced media — the final video's poster with a play badge (click the artwork to open the project, the badge to play it inline), a rendered scene, or a produced image from a directive plan — falling back to a tidy "no render yet" placeholder instead of a wall of text. The Overview tab renders the final cut inline instead of showing only a job id, keeping the Media History link alongside it; plans that emit images show the image. Previews respect each project's aspect ratio (16:9 / 9:16 / 1:1), and the grid never downloads a video until you actually press play.- [issue-2689] **Layered Intelligence now diagnoses *why* its proposals were turned down, instead of parroting the tracker back at itself.** When a filed proposal is closed unmerged, it's classified against a fixed vocabulary — duplicate, declined, out of scope, missing context, quality, environment blocker, and more — read from the issue's close reason and its labels, and stored alongside the outcome. The loop's feedback block used to tell it "common rejection reasons: not_planned", which restates the outcome rather than explaining it; it now reads "already tracked elsewhere (2); the user declined it (1)". A proposal closed with nothing to explain it is recorded as an explicit unknown and counted, so "3 of 4 closed with no recorded reason" is reported to the loop as the blind spot it is — never dressed up as a real diagnosis, and never allowed to read as "nothing was ever rejected". Rejections the loop hasn't classified yet are reported as their own separate count rather than being folded in with the ones it examined and couldn't explain, because the two have different remedies. Merged proposals never acquire a rejection reason, which matters for Jira- and PLAN.md-backed apps whose trackers report no close reason at all and whose ordinary close *is* a merge. Costs no extra AI calls and no extra tracker reads — every reason is derived from issue data the loop already fetches — and rejection history recorded before this upgrade is re-diagnosed on the next run rather than needing a reset.diff --git a/PLAN.md b/PLAN.mdindex bfb47cb6f8..e9b30ca3ca 100644--- a/PLAN.md+++ b/PLAN.md@@ -215,3 +215,8 @@ by `/do:replan --issues`:- [ ] **A federated video poster never un-sticks from "Syncing".** `peerSyncAssets.js#doPullOneAsset` regenerates a pulled video's thumbnail locally but emits `asset-arrived` only for the `*.mp4` — never for the `.jpg` — so `MediaImage`'s exact-filename listener (now used for the CD card posters in `ProjectPreview.jsx`) never fires, and the card sits on the placeholder until a remount. Worse for a stitched final: the regenerated name is derived from the VIDEO filename (`timeline-<project>-<ts>.jpg`), while every poster URL in the UI is `<jobId>.jpg` — the same id≠filename mismatch #2702 fixed on the client, still live on the federated path. Fix server-side: emit an `asset-arrived` for the regenerated thumbnail, and key its name off the synced history row's `thumbnail` field rather than the mp4 basename. Pre-existing (the bare `<img>` it replaced never recovered either); flagged by codex review on PR #2719.- [ ] **Give the video id→filename resolution a real home.** `useVideoFileSrc` (`client/src/hooks/useVideoFileSrc.js`) fetches the WHOLE `/video-gen/history` list to resolve one id, because a history entry's id is not its filename stem (the timeline renderer mints `timeline-<project>-<ts>.mp4` beside a `randomUUID()` id) and no by-id endpoint exists. Three surfaces now need it (CD cards, CD Overview, `EpisodeVideoStage`). Consider a `GET /api/video-gen/history/:id` (or a `/api/media/video/:id` resolver that 302s to the real file), which would also let `ScenePreview` stop reconstructing paths at all. Deferred from #2702 as an explicit "no new server endpoints" scope-out.++### Creative Commission detail-page follow-ups++- [ ] **Resolve a commission's render projects without pulling the whole CD project list.** `client/src/pages/CreativeCommissionDetail.jsx` fetches `listCreativeDirectorProjects()` (every project, non-slim) on load just to index the ≤50 referenced by `runs[].projectId`. It's a single request and matches how the CD list page already loads, but it scales with the install's *total* project count, not the commission's. Once a by-id/batch resolver exists (see the `useVideoFileSrc` follow-up above — same "no by-id endpoint" root cause), swap this to fetch only the referenced projects. Deferred from the detail-page PR to avoid adding a server endpoint in a client-only change.+- [ ] **Consider extracting the shared run-now/pause/delete commission actions.** The `handleRunNow` / `toggleEnabled` / `handleDelete` handlers now live in both `CreativeCommissions.jsx` (list state — `setCommissions` map/filter) and `CreativeCommissionDetail.jsx` (single-record state — `setCommission`). Two occurrences with genuinely different state shapes, so the rule of three isn't met and a `useCommissionActions` hook would need to abstract over both shapes awkwardly; left as-is. Revisit if a third surface (e.g. a dashboard widget) needs the same actions.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 80c0239286..2222cf1520 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -71,6 +71,7 @@ const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEdconst CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));const CreativeCommissions = lazyWithReload(() => import('./pages/CreativeCommissions'));+const CreativeCommissionDetail = lazyWithReload(() => import('./pages/CreativeCommissionDetail'));const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));@@ -346,11 +347,14 @@ export default function App() {<Route path="creative-director" element={<CreativeDirector />} /><Route path="creative-director/:id" element={<CreativeDirectorOverviewRedirect />} /><Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />+ {/* Index (list) hosts the create drawer at /new; `:id` is now a routed+ detail page (editable config + render history), not a sidebar edit+ drawer. React Router ranks the static `new` segment above `:id`, so+ the index reads `new` off the pathname while every real id lands on+ the detail page. */}<Route path="creative-commission" element={<CreativeCommissions />} />- {/* `:id` matches the literal `new` (create mode) too — a separate- static `new` route would render with no :id param and leave the- drawer closed, since React Router ranks the static segment higher. */}- <Route path="creative-commission/:id" element={<CreativeCommissions />} />+ <Route path="creative-commission/new" element={<CreativeCommissions />} />+ <Route path="creative-commission/:id" element={<CreativeCommissionDetail />} /><Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} /><Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} /><Route path="media-history" element={<RedirectWithSearch to="/media/history" />} />diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsxnew file mode 100644index 0000000000..06d1c5962f--- /dev/null+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx@@ -0,0 +1,290 @@+/**+ * Editable configuration form for a Creative Commission (#2657).+ *+ * The pure field sections of a commission's brief/schedule/generation/assignment,+ * shared by the index create drawer and the routed detail page. Run history ++ * render previews are rendered separately (see RenderHistory.jsx) so this stays a+ * config-only surface — the create drawer has no runs, and the detail page shows+ * renders in a dedicated gallery above the config.+ *+ * State lives in the PARENT (per the Drawer state-hoisting rule); this component+ * is fully controlled via `form` + `patchForm`.+ */++import { useEffect, useMemo, useState } from 'react';+import ProviderModelSelector from '../ProviderModelSelector';+import { isProcessProvider } from '../../utils/providers';+import { getProviders } from '../../services/api';+import { WEEKDAYS, inputCls, labelCls, describeSchedule } from './commissionForm.js';++export default function CommissionConfigForm({ form, patchForm, saving, onSave, onCancel, saveLabel = 'Save' }) {+ return (+ <div className="space-y-5">+ {/* Identity */}+ <section className="space-y-3">+ <div>+ <label className={labelCls} htmlFor="commission-name">Name</label>+ <input+ id="commission-name"+ className={inputCls}+ value={form.name}+ maxLength={200}+ onChange={(e) => patchForm(['name'], e.target.value)}+ placeholder="Nightly Surreal"+ />+ </div>+ <label className="flex items-center gap-2 text-sm text-gray-300">+ <input+ type="checkbox"+ checked={form.enabled}+ onChange={(e) => patchForm(['enabled'], e.target.checked)}+ />+ Enabled (fires on schedule)+ </label>+ </section>++ {/* Brief */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Brief</h3>+ <div>+ <label className={labelCls} htmlFor="commission-intent">Intent</label>+ <textarea+ id="commission-intent"+ className={`${inputCls} min-h-[70px]`}+ value={form.brief.intent}+ maxLength={2000}+ onChange={(e) => patchForm(['brief', 'intent'], e.target.value)}+ placeholder="something surreal, dreamlike, unsettlingly beautiful"+ />+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-genre">Genre (optional)</label>+ <input+ id="commission-genre"+ className={inputCls}+ value={form.brief.genre}+ maxLength={120}+ onChange={(e) => patchForm(['brief', 'genre'], e.target.value)}+ placeholder="surrealism"+ />+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-style">Style notes (optional)</label>+ <input+ id="commission-style"+ className={inputCls}+ value={form.brief.styleSpec}+ maxLength={5000}+ onChange={(e) => patchForm(['brief', 'styleSpec'], e.target.value)}+ placeholder="flat color, Magritte"+ />+ </div>+ </div>+ </section>++ {/* Schedule */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Schedule</h3>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-kind">Cadence</label>+ <select+ id="commission-kind"+ className={inputCls}+ value={form.schedule.kind}+ onChange={(e) => patchForm(['schedule', 'kind'], e.target.value)}+ >+ <option value="DAILY">Daily</option>+ <option value="WEEKLY">Weekly</option>+ <option value="CUSTOM">Custom (cron)</option>+ </select>+ </div>+ {form.schedule.kind !== 'CUSTOM' && (+ <div>+ <label className={labelCls} htmlFor="commission-time">Time (24h, local)</label>+ <input+ id="commission-time"+ type="time"+ className={inputCls}+ value={form.schedule.atLocalTime}+ onChange={(e) => patchForm(['schedule', 'atLocalTime'], e.target.value)}+ />+ </div>+ )}+ {form.schedule.kind === 'WEEKLY' && (+ <div>+ <label className={labelCls} htmlFor="commission-weekday">Day of week</label>+ <select+ id="commission-weekday"+ className={inputCls}+ value={form.schedule.weekday}+ onChange={(e) => patchForm(['schedule', 'weekday'], Number(e.target.value))}+ >+ {WEEKDAYS.map((d, i) => <option key={i} value={i}>{d}</option>)}+ </select>+ </div>+ )}+ {form.schedule.kind === 'CUSTOM' && (+ <div>+ <label className={labelCls} htmlFor="commission-cron">Cron (5-field)</label>+ <input+ id="commission-cron"+ className={inputCls}+ value={form.schedule.cron}+ maxLength={120}+ onChange={(e) => patchForm(['schedule', 'cron'], e.target.value)}+ placeholder="0 2 * * *"+ />+ </div>+ )}+ </div>+ {form.schedule.kind === 'DAILY' && (+ <label className="flex items-center gap-2 text-sm text-gray-300">+ <input+ type="checkbox"+ checked={form.schedule.weekdaysOnly}+ onChange={(e) => patchForm(['schedule', 'weekdaysOnly'], e.target.checked)}+ />+ Weekdays only (Mon–Fri)+ </label>+ )}+ <p className="text-xs text-gray-500">{describeSchedule(form.schedule)}</p>+ </section>++ {/* Generation */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Generation (video)</h3>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-quality">Quality</label>+ <select+ id="commission-quality"+ className={inputCls}+ value={form.generation.quality}+ onChange={(e) => patchForm(['generation', 'quality'], e.target.value)}+ >+ <option value="draft">Draft</option>+ <option value="standard">Standard</option>+ <option value="high">High</option>+ </select>+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-aspect">Aspect ratio</label>+ <select+ id="commission-aspect"+ className={inputCls}+ value={form.generation.aspectRatio}+ onChange={(e) => patchForm(['generation', 'aspectRatio'], e.target.value)}+ >+ <option value="16:9">16:9</option>+ <option value="9:16">9:16</option>+ <option value="1:1">1:1</option>+ </select>+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-duration">Duration (sec)</label>+ <input+ id="commission-duration"+ type="number"+ min={5}+ max={600}+ className={inputCls}+ value={form.generation.targetDurationSeconds}+ onChange={(e) => patchForm(['generation', 'targetDurationSeconds'], e.target.value)}+ />+ </div>+ </div>+ </section>++ {/* AI provider & model — who processes this commission */}+ <section className="space-y-2 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">AI provider & model</h3>+ <p className="text-xs text-gray-500">+ Which AI writes the treatment and production plan each time this commission runs. Leave on the+ default to use your install's configured Creative Director assignment.+ </p>+ <AssignmentPicker+ assignment={form.assignment}+ onChange={(next) => patchForm(['assignment'], next)}+ />+ </section>++ {/* Feedback conditioning */}+ <section className="space-y-2 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Feedback conditioning</h3>+ <div className="flex items-center gap-3">+ <label className={`${labelCls} mb-0`} htmlFor="commission-feedback-window">Recent reactions to steer by</label>+ <input+ id="commission-feedback-window"+ type="number"+ min={0}+ max={50}+ className={`${inputCls} w-20`}+ value={form.feedbackWindow}+ onChange={(e) => patchForm(['feedbackWindow'], e.target.value)}+ />+ </div>+ <p className="text-xs text-gray-500">+ The last N ratings + notes are folded into the next run's brief. 0 disables conditioning.+ </p>+ </section>++ <div className="flex items-center gap-2 border-t border-port-border pt-4">+ <button+ onClick={onSave}+ disabled={saving}+ className="bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium"+ >+ {saving ? 'Saving…' : saveLabel}+ </button>+ {onCancel && (+ <button onClick={onCancel} className="text-gray-400 hover:text-gray-200 px-4 py-2 text-sm">Cancel</button>+ )}+ </div>+ </div>+ );+}++// AI provider/model picker for the commission's CD cognitive stages (treatment ++// plan). Mirrors SeriesLlmPicker: fetches the provider list, drives the shared+// ProviderModelSelector, and reports changes up to form state via `onChange`.+// Only agent-harness (CLI/TUI) providers are offered — an API-type provider+// injected into a CoS agent task trips the server's harness-boundary guard.+//+// The empty option deliberately does NOT name a specific provider: an unset pin+// resolves at fire time to `settings.creativeDirector.{treatment,plan}` (falling+// back to the active provider only when those stages are themselves unassigned),+// so naming the registry's active provider here would misreport the processor on+// installs that assign the CD stages separately. Label it neutrally; the section+// helper text points the user at their Creative Director assignment.+function AssignmentPicker({ assignment, onChange }) {+ const [providers, setProviders] = useState([]);++ useEffect(() => {+ getProviders({ silent: true })+ .then((data) => setProviders((data?.providers || []).filter(isProcessProvider)))+ .catch(() => { /* dropdowns fall back to the "install default" option */ });+ }, []);++ const availableModels = useMemo(() => {+ const p = providers.find((x) => x.id === assignment.providerId);+ return p?.models || [];+ }, [providers, assignment.providerId]);++ return (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={assignment.providerId || ''}+ selectedModel={assignment.model || ''}+ availableModels={availableModels}+ onProviderChange={(id) => onChange({ providerId: id || '', model: '' })}+ onModelChange={(model) => onChange({ ...assignment, model: model || '' })}+ label="Provider"+ modelDisabled={availableModels.length === 0}+ alwaysShowModel+ emptyProviderOption="Install default (Creative Director assignment)"+ emptyModelOption="Default model"+ />+ );+}diff --git a/client/src/components/creative-commission/RenderHistory.jsx b/client/src/components/creative-commission/RenderHistory.jsxnew file mode 100644index 0000000000..7f2bca65c3--- /dev/null+++ b/client/src/components/creative-commission/RenderHistory.jsx@@ -0,0 +1,184 @@+/**+ * Render history gallery for a Creative Commission's detail page (#2657).+ *+ * Every scheduled/manual fire records a run pointing at the Creative Director+ * project it produced (`run.projectId`). This gallery resolves each run's project+ * to its representative produced asset (via ProjectPreview / selectProjectPreview)+ * so the user SEES what the commission has made — video/image thumbnails with a+ * play affordance — instead of a list of text rows. Each card also carries the+ * run's status, a "View output" deep link into the Creative Director, and the+ * per-run 👍/👎 + note control that steers the next scheduled run.+ *+ * `projectsById` is a `Map<projectId, project>` the parent page fetches once (the+ * CD list route returns full, non-slim payloads, so previews compute with no+ * extra per-card fetch). A run whose project hasn't loaded yet (or was pruned)+ * degrades to a status-only card — the "View output" link still works.+ */++import { useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import { ExternalLink, Film, ThumbsUp, ThumbsDown } from 'lucide-react';+import ProjectPreview from '../creative-director/ProjectPreview.jsx';+import { previewAspectClass } from '../../lib/creativeDirectorPreview.js';+import { timeAgo } from '../../utils/formatters';++const STATUS_CLASS = {+ started: 'text-port-accent',+ skipped: 'text-port-warning',+ failed: 'text-port-error',+};++export default function RenderHistory({ runs, feedback, projectsById, onRate }) {+ // Newest-first, memoized so the copy+reverse doesn't run on every render.+ const orderedRuns = useMemo(() => [...(runs || [])].reverse(), [runs]);+ // Latest reaction per run (last write wins), so the run reflects its most+ // recent rating.+ const feedbackByRun = useMemo(() => {+ const map = {};+ for (const f of feedback || []) { if (f?.runId) map[f.runId] = f; }+ return map;+ }, [feedback]);++ if (orderedRuns.length === 0) {+ return (+ <div className="border border-dashed border-port-border rounded-lg p-10 text-center">+ <Film className="w-8 h-8 text-gray-600 mx-auto mb-3" aria-hidden="true" />+ <p className="text-gray-400 mb-1">No renders yet</p>+ <p className="text-gray-600 text-sm">+ When this commission fires — on its schedule or via “Run now” — each render shows up here.+ </p>+ </div>+ );+ }++ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">+ {orderedRuns.map((r) => {+ const project = r.projectId ? projectsById.get(r.projectId) : null;+ return (+ <div key={r.id} className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">+ {/* Produced-media preview (or a status-only placeholder). */}+ {project ? (+ <ProjectPreview project={project} to={`/creative-director/${encodeURIComponent(r.projectId)}`} />+ ) : (+ // `project` is null in this branch, so the placeholder falls back to+ // the default 16:9 box — a status-only card for a pruned/missing render.+ <div className={`${previewAspectClass()} bg-port-bg flex flex-col items-center justify-center gap-1 text-gray-600 text-xs`}>+ <Film className="w-4 h-4 opacity-50" aria-hidden="true" />+ <span>{r.projectId ? 'render unavailable' : 'no render'}</span>+ </div>+ )}++ <div className="p-3 flex flex-col gap-2 flex-1">+ <div className="flex items-center justify-between gap-2 text-xs">+ <span className="text-gray-400 flex items-center gap-1.5">+ {timeAgo(r.ranAt)}+ {/* Runs persisted before the trigger field exist only from cron ticks — no badge. */}+ {r.trigger === 'manual' && (+ <span className="text-[10px] uppercase px-1 py-0.5 rounded bg-port-accent/20 text-port-accent">manual</span>+ )}+ </span>+ <span className={STATUS_CLASS[r.status] || 'text-gray-400'}>+ {r.status}{r.reason ? ` · ${r.reason}` : ''}{r.error ? ` · ${r.error}` : ''}+ </span>+ </div>++ {r.projectId && (+ <Link+ to={`/creative-director/${encodeURIComponent(r.projectId)}`}+ className="text-port-accent hover:text-blue-400 inline-flex items-center gap-1 text-xs"+ >+ <ExternalLink className="w-3 h-3" /> View output+ </Link>+ )}++ {/* Rate/annotate — pushed to the bottom of the card so cards align. */}+ {r.projectId && onRate && (+ <div className="mt-auto pt-1">+ <RunFeedback runId={r.id} current={feedbackByRun[r.id]} onRate={onRate} />+ </div>+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+}++// Per-run rate/annotate control (#2657, Phase 2). Thumbs submit immediately,+// carrying whatever note is in the field; the current rating (if any) is shown+// highlighted. Note state is local so typing doesn't re-render the whole gallery.+//+// Note edits use an EXPLICIT Save affordance, not blur/focus autosave. Autosave+// on blur is a nest of edge cases — it races the vote request (blur during a+// busy window never retries), and can't reliably tell "tabbed through a thumb"+// from "clicked a thumb." A visible Save button (shown only while the note is+// dirty) makes the unsaved state obvious and unambiguous, and Enter is a+// shortcut for the same action. A note can't be saved before a rating exists (a+// rating is required), so the affordance only appears once the run is thumbed.+export function RunFeedback({ runId, current, onRate }) {+ const [note, setNote] = useState(current?.note || '');+ const [busy, setBusy] = useState(false);+ const rating = current?.rating;+ const isUp = rating === 'up' || (typeof rating === 'number' && rating > 0);+ const isDown = rating === 'down' || (typeof rating === 'number' && rating < 0);++ const submit = async (value) => {+ setBusy(true);+ try { await onRate(runId, value, note.trim()); }+ finally { setBusy(false); }+ };++ // A note edited after the run was rated is "dirty" until re-saved under the+ // existing rating. The Save button/Enter shortcut is gated on this.+ const noteDirty = !!rating && note.trim() !== (current?.note || '');+ const saveNote = () => { if (noteDirty && !busy) submit(rating); };++ return (+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ disabled={busy}+ onClick={() => submit('up')}+ aria-label="Like this result"+ aria-pressed={isUp}+ title="Like — steer future runs toward this"+ className={`p-1 rounded disabled:opacity-50 ${isUp ? 'text-port-success' : 'text-gray-500 hover:text-gray-300'}`}+ >+ <ThumbsUp className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ disabled={busy}+ onClick={() => submit('down')}+ aria-label="Dislike this result"+ aria-pressed={isDown}+ title="Dislike — steer future runs away from this"+ className={`p-1 rounded disabled:opacity-50 ${isDown ? 'text-port-error' : 'text-gray-500 hover:text-gray-300'}`}+ >+ <ThumbsDown className="w-3.5 h-3.5" />+ </button>+ <input+ className="flex-1 min-w-0 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 focus:outline-none focus:border-port-accent"+ value={note}+ maxLength={1000}+ placeholder={rating ? 'note (Enter to save)' : 'note — rate first'}+ aria-label={`Feedback note for run ${runId}`}+ onChange={(e) => setNote(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); saveNote(); } }}+ />+ {noteDirty && (+ <button+ type="button"+ disabled={busy}+ onClick={saveNote}+ aria-label={`Save note for run ${runId}`}+ className="text-xs text-port-accent hover:text-blue-400 disabled:opacity-50 px-1.5 py-1 whitespace-nowrap"+ >+ Save+ </button>+ )}+ </div>+ );+}diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.jsnew file mode 100644index 0000000000..169cbd5130--- /dev/null+++ b/client/src/components/creative-commission/commissionForm.js@@ -0,0 +1,126 @@+/**+ * Shared, pure helpers for the Creative Commission config form (#2657).+ *+ * These are the editable projection of a commission record — used by BOTH the+ * index page's "New Commission" create drawer (client/src/pages/CreativeCommissions.jsx)+ * and the routed detail page's editable config (client/src/pages/CreativeCommissionDetail.jsx).+ * Kept side-effect-free so both surfaces map record ↔ form identically.+ */++export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];++export const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-100 focus:outline-none focus:border-port-accent';+export const labelCls = 'block text-xs font-medium text-gray-400 mb-1';++// Human-readable cadence summary for the list card + detail header.+export function describeSchedule(schedule) {+ if (!schedule) return 'No schedule';+ const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;+ if (kind === 'CUSTOM') return `Custom · ${cron || '—'}`;+ if (kind === 'WEEKLY') return `Weekly · ${WEEKDAYS[weekday] ?? '—'} at ${atLocalTime || '—'}`;+ if (kind === 'DAILY') return `Daily${weekdaysOnly ? ' (weekdays)' : ''} at ${atLocalTime || '—'}`;+ return kind || 'No schedule';+}++// Compact "who processes this" summary. Unset → the install default assignment;+// set → the pinned provider (and model, when chosen).+export function describeAssignment(assignment) {+ const providerId = assignment?.providerId;+ if (!providerId) return 'Install default AI';+ return assignment.model ? `${providerId} · ${assignment.model}` : providerId;+}++// Map a stored record → editable form state (fills gaps so inputs stay controlled).+export function toForm(c) {+ return {+ name: c.name || '',+ enabled: c.enabled !== false,+ targetAbility: c.targetAbility || 'video',+ brief: {+ intent: c.brief?.intent || '',+ genre: c.brief?.genre || '',+ styleSpec: c.brief?.styleSpec || '',+ },+ schedule: {+ kind: c.schedule?.kind || 'DAILY',+ atLocalTime: c.schedule?.atLocalTime || '02:00',+ weekday: Number.isInteger(c.schedule?.weekday) ? c.schedule.weekday : 0,+ weekdaysOnly: c.schedule?.weekdaysOnly === true,+ cron: c.schedule?.cron || '',+ },+ generation: {+ quality: c.generation?.quality || 'standard',+ aspectRatio: c.generation?.aspectRatio || '16:9',+ targetDurationSeconds: c.generation?.targetDurationSeconds || 10,+ },+ // Which AI provider/model processes the commission's CD stages. Empty+ // providerId → the install's default AI Assignment.+ assignment: {+ providerId: c.assignment?.providerId || '',+ model: c.assignment?.model || '',+ },+ // How many recent reactions steer the next run (0 disables conditioning).+ feedbackWindow: Number.isInteger(c.feedbackWindow) ? c.feedbackWindow : 5,+ };+}++// A blank form is just the editable projection of an empty record.+export const blankForm = () => toForm({});++// Build the API payload from form state, dropping fields the schedule kind doesn't use.+export function toPayload(form) {+ const s = { kind: form.schedule.kind };+ if (form.schedule.kind === 'CUSTOM') {+ s.cron = form.schedule.cron.trim();+ } else {+ s.atLocalTime = form.schedule.atLocalTime;+ if (form.schedule.kind === 'WEEKLY') s.weekday = Number(form.schedule.weekday);+ if (form.schedule.kind === 'DAILY') s.weekdaysOnly = !!form.schedule.weekdaysOnly;+ }+ return {+ name: form.name.trim(),+ enabled: !!form.enabled,+ targetAbility: form.targetAbility,+ brief: {+ intent: form.brief.intent.trim(),+ genre: form.brief.genre.trim() || null,+ styleSpec: form.brief.styleSpec,+ },+ schedule: s,+ generation: {+ quality: form.generation.quality,+ aspectRatio: form.generation.aspectRatio,+ targetDurationSeconds: Number(form.generation.targetDurationSeconds),+ },+ // Send the full pin every save; a provider-less choice clears the model too+ // (the server drops a dangling model, but keeping the payload clean avoids a+ // pointless round-trip through the sanitizer's normalization).+ assignment: {+ providerId: form.assignment.providerId || null,+ model: form.assignment.providerId ? (form.assignment.model || null) : null,+ },+ feedbackWindow: Number(form.feedbackWindow),+ };+}++// A patch helper for one/two-level form paths, shared by both editors.+export function patchFormState(prev, path, value) {+ const next = { ...prev };+ if (path.length === 1) next[path[0]] = value;+ else next[path[0]] = { ...prev[path[0]], [path[1]]: value };+ return next;+}++// Validate the form before save. Returns an error string, or null when valid.+// A cleared feedbackWindow is '', which Number() coerces to 0 — and 0 is the+// valid "disable conditioning" value, so a blank field would silently turn+// feedback off. Reject it instead of guessing intent.+export function validateForm(form) {+ if (!form.name.trim()) return 'Name is required';+ if (!form.brief.intent.trim()) return 'Brief intent is required';+ const fw = Number(form.feedbackWindow);+ if (form.feedbackWindow === '' || !Number.isInteger(fw) || fw < 0 || fw > 50) {+ return 'Feedback window must be a whole number from 0 to 50';+ }+ return null;+}diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.jsnew file mode 100644index 0000000000..8719085482--- /dev/null+++ b/client/src/components/creative-commission/commissionForm.test.js@@ -0,0 +1,120 @@+import { describe, it, expect } from 'vitest';+import {+ toForm, toPayload, blankForm, patchFormState, validateForm,+ describeSchedule, describeAssignment,+} from './commissionForm.js';++describe('commissionForm helpers', () => {+ describe('toForm', () => {+ it('fills gaps so every input stays controlled from an empty record', () => {+ const f = toForm({});+ expect(f.name).toBe('');+ expect(f.enabled).toBe(true);+ expect(f.targetAbility).toBe('video');+ expect(f.brief).toEqual({ intent: '', genre: '', styleSpec: '' });+ expect(f.schedule.kind).toBe('DAILY');+ expect(f.schedule.atLocalTime).toBe('02:00');+ expect(f.generation).toEqual({ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 });+ expect(f.assignment).toEqual({ providerId: '', model: '' });+ expect(f.feedbackWindow).toBe(5);+ });++ it('projects a stored record, treating enabled:false and feedbackWindow:0 as intentional', () => {+ const f = toForm({ name: 'Nightly', enabled: false, feedbackWindow: 0, brief: { intent: 'surreal' } });+ expect(f.name).toBe('Nightly');+ expect(f.enabled).toBe(false);+ expect(f.feedbackWindow).toBe(0);+ expect(f.brief.intent).toBe('surreal');+ });+ });++ describe('toPayload', () => {+ it('drops schedule fields the cadence does not use (DAILY)', () => {+ const p = toPayload(toForm({ schedule: { kind: 'DAILY', atLocalTime: '03:00', weekdaysOnly: true } }));+ expect(p.schedule).toEqual({ kind: 'DAILY', atLocalTime: '03:00', weekdaysOnly: true });+ expect(p.schedule.cron).toBeUndefined();+ expect(p.schedule.weekday).toBeUndefined();+ });++ it('sends only cron for CUSTOM cadence', () => {+ const form = toForm({ schedule: { kind: 'CUSTOM', cron: '0 2 * * *' } });+ const p = toPayload(form);+ expect(p.schedule).toEqual({ kind: 'CUSTOM', cron: '0 2 * * *' });+ });++ it('nulls a provider-less model so a stored pin never dangles', () => {+ const form = { ...blankForm(), assignment: { providerId: '', model: 'gpt-x' } };+ expect(toPayload(form).assignment).toEqual({ providerId: null, model: null });+ });++ it('keeps the model when a provider is pinned', () => {+ const form = { ...blankForm(), assignment: { providerId: 'claude', model: 'opus' } };+ expect(toPayload(form).assignment).toEqual({ providerId: 'claude', model: 'opus' });+ });++ it('coerces a blank genre to null', () => {+ const form = { ...blankForm(), brief: { intent: 'x', genre: ' ', styleSpec: '' } };+ expect(toPayload(form).brief.genre).toBeNull();+ });+ });++ describe('validateForm', () => {+ const base = () => ({ ...blankForm(), name: 'A', brief: { intent: 'i', genre: '', styleSpec: '' } });+ it('passes a complete form', () => {+ expect(validateForm(base())).toBeNull();+ });+ it('requires a name', () => {+ expect(validateForm({ ...base(), name: ' ' })).toMatch(/name/i);+ });+ it('requires a brief intent', () => {+ expect(validateForm({ ...base(), brief: { intent: '', genre: '', styleSpec: '' } })).toMatch(/intent/i);+ });+ it('rejects a blank feedback window (would silently disable conditioning)', () => {+ expect(validateForm({ ...base(), feedbackWindow: '' })).toMatch(/feedback window/i);+ });+ it('accepts feedbackWindow 0 (explicit disable)', () => {+ expect(validateForm({ ...base(), feedbackWindow: 0 })).toBeNull();+ });+ it('rejects an out-of-range feedback window', () => {+ expect(validateForm({ ...base(), feedbackWindow: 99 })).toMatch(/feedback window/i);+ });+ });++ describe('patchFormState', () => {+ it('patches a one-level path immutably', () => {+ const prev = blankForm();+ const next = patchFormState(prev, ['name'], 'X');+ expect(next.name).toBe('X');+ expect(prev.name).toBe('');+ expect(next).not.toBe(prev);+ });+ it('patches a nested path without dropping siblings', () => {+ const prev = toForm({ brief: { intent: 'keep', genre: 'g' } });+ const next = patchFormState(prev, ['brief', 'genre'], 'new');+ expect(next.brief.genre).toBe('new');+ expect(next.brief.intent).toBe('keep');+ expect(prev.brief.genre).toBe('g');+ });+ });++ describe('describeSchedule', () => {+ it('summarizes each cadence kind', () => {+ expect(describeSchedule({ kind: 'DAILY', atLocalTime: '02:00' })).toBe('Daily at 02:00');+ expect(describeSchedule({ kind: 'DAILY', atLocalTime: '02:00', weekdaysOnly: true })).toBe('Daily (weekdays) at 02:00');+ expect(describeSchedule({ kind: 'WEEKLY', weekday: 1, atLocalTime: '09:00' })).toBe('Weekly · Monday at 09:00');+ expect(describeSchedule({ kind: 'CUSTOM', cron: '0 2 * * *' })).toBe('Custom · 0 2 * * *');+ expect(describeSchedule(null)).toBe('No schedule');+ });+ });++ describe('describeAssignment', () => {+ it('names the install default when unpinned', () => {+ expect(describeAssignment({})).toBe('Install default AI');+ expect(describeAssignment(null)).toBe('Install default AI');+ });+ it('names the provider and model when pinned', () => {+ expect(describeAssignment({ providerId: 'claude' })).toBe('claude');+ expect(describeAssignment({ providerId: 'claude', model: 'opus' })).toBe('claude · opus');+ });+ });+});diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsxnew file mode 100644index 0000000000..930b882385--- /dev/null+++ b/client/src/pages/CreativeCommissionDetail.jsx@@ -0,0 +1,285 @@+/**+ * Creative Commission detail page (#2657) — the routed replacement for the old+ * edit Drawer.+ *+ * /creative-commission/:id → this page (editable config + render history)+ *+ * Clicking a commission on the index no longer pops a sidebar edit form; it+ * navigates here, where the user sees EVERY render the commission has produced+ * (video/image thumbnails, newest first) alongside the editable brief/schedule/+ * generation config. The URL is the source of truth for what's open (the+ * ID-based deep-linking rule), so a render or its detail page is directly+ * shareable, bookmarkable, and reachable from ⌘K / voice / notification links.+ */++import { useEffect, useMemo, useRef, useState, useCallback } from 'react';+import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';+import { ArrowLeft, Sparkles, Clock, Cpu, Zap, Pause, Play, Trash2 } from 'lucide-react';+import toast from '../components/ui/Toast';+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';+import { useConfirmDelete } from '../hooks/useConfirmDelete';+import { timeAgo } from '../utils/formatters';+import CommissionConfigForm from '../components/creative-commission/CommissionConfigForm.jsx';+import RenderHistory from '../components/creative-commission/RenderHistory.jsx';+import {+ toForm, toPayload, patchFormState, validateForm, describeSchedule, describeAssignment,+} from '../components/creative-commission/commissionForm.js';+import {+ getCommission, updateCommission, deleteCommission,+ submitCommissionFeedback, runCommissionNow, listCreativeDirectorProjects,+} from '../services/api';++export default function CreativeCommissionDetail() {+ const navigate = useNavigate();+ const location = useLocation();+ const { id } = useParams();+ const [commission, setCommission] = useState(null);+ const [loading, setLoading] = useState(true);+ const [notFound, setNotFound] = useState(false);+ const [form, setForm] = useState(() => toForm({}));+ const [saving, setSaving] = useState(false);+ const [running, setRunning] = useState(false);+ const [projectsById, setProjectsById] = useState(() => new Map());+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ // Load (and refresh) the deep-linked commission. `location.key` is a dep so a+ // notification deep link to THIS already-open page (a same-path push) still+ // refetches and pulls in a just-fired run.+ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ getCommission(id, { silent: true })+ .then((fresh) => {+ if (cancelled) return;+ setCommission(fresh);+ setNotFound(false);+ })+ .catch(() => { if (!cancelled) setNotFound(true); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, [id, location.key]);++ // Sync the form to the loaded record ONLY when the target id first resolves —+ // never on the in-place record swaps that rating / Run Now / save trigger, or+ // they'd silently discard unsaved field edits. Keying on the last-synced id+ // makes an in-place update of the same id a no-op here.+ const syncedIdRef = useRef(null);+ useEffect(() => {+ if (commission && syncedIdRef.current !== commission.id) {+ setForm(toForm(commission));+ syncedIdRef.current = commission.id;+ }+ }, [commission]);++ // The set of CD projects referenced by this commission's runs. Fetch the full+ // project list once (the list route returns non-slim payloads, so previews+ // compute with no per-card fetch) and index the referenced ones. Re-runs when+ // the projectId set changes (e.g. a Run Now appends a new render).+ const projectIdsKey = useMemo(() => {+ const ids = (commission?.runs || []).map((r) => r.projectId).filter(Boolean);+ return [...new Set(ids)].sort().join(',');+ }, [commission]);++ useEffect(() => {+ if (!projectIdsKey) { setProjectsById(new Map()); return; }+ const wanted = new Set(projectIdsKey.split(','));+ let cancelled = false;+ listCreativeDirectorProjects()+ .then((projects) => {+ if (cancelled) return;+ const map = new Map();+ for (const p of Array.isArray(projects) ? projects : []) {+ if (wanted.has(p.id)) map.set(p.id, p);+ }+ setProjectsById(map);+ })+ .catch(() => { /* status-only cards degrade gracefully */ });+ return () => { cancelled = true; };+ }, [projectIdsKey]);++ const patchForm = useCallback((path, value) => setForm((prev) => patchFormState(prev, path, value)), []);++ const handleSave = async () => {+ const err = validateForm(form);+ if (err) { toast.error(err); return; }+ setSaving(true);+ try {+ const updated = await updateCommission(id, toPayload(form), { silent: true });+ setCommission((prev) => ({ ...updated, feedback: prev?.feedback ?? updated.feedback }));+ toast.success('Commission updated');+ } catch (e) {+ toast.error(e?.message || 'Save failed');+ } finally {+ setSaving(false);+ }+ };++ const handleDelete = async () => {+ try {+ await deleteCommission(id, { silent: true });+ toast.success('Commission deleted');+ navigate('/creative-commission');+ } catch (e) {+ toast.error(e?.message || 'Delete failed');+ }+ };++ // Rate/annotate a run's output — folds into the next scheduled run's directive.+ const handleRate = useCallback(async (runId, rating, note) => {+ try {+ const updated = await submitCommissionFeedback(id, { runId, rating, note: note || '' }, { silent: true });+ setCommission(updated);+ toast.success('Feedback saved — it steers the next run');+ } catch (e) {+ toast.error(e?.message || 'Failed to save feedback');+ }+ }, [id]);++ // Fire immediately, outside the schedule — the "does this actually work" test.+ // Runs the same gated path as a cron tick, so a skip (autonomy off, over+ // budget) is itself the result and is toasted with its reason.+ const handleRunNow = async () => {+ setRunning(true);+ try {+ const result = await runCommissionNow(id, { silent: true });+ // Merge only the run-history fields the response is authoritative for, so a+ // concurrent optimistic local change (e.g. a Pause toggle) isn't clobbered.+ if (result?.commission?.id) {+ const fresh = result.commission;+ setCommission((prev) => (prev ? { ...prev, runs: fresh.runs, feedback: fresh.feedback } : fresh));+ }+ if (result?.status === 'started') toast.success('Run started — the render will appear below');+ else if (result?.status === 'skipped') toast.error(`Run skipped: ${result.reason}`);+ else toast.error(`Run failed: ${result?.error || 'unknown error'}`);+ } catch (e) {+ toast.error(e?.message || 'Run failed');+ } finally {+ setRunning(false);+ }+ };++ const toggleEnabled = async () => {+ if (!commission) return;+ const next = !commission.enabled;+ setCommission((prev) => ({ ...prev, enabled: next }));+ setForm((prev) => ({ ...prev, enabled: next }));+ try {+ await updateCommission(id, { enabled: next }, { silent: true });+ } catch (e) {+ setCommission((prev) => ({ ...prev, enabled: !next }));+ setForm((prev) => ({ ...prev, enabled: !next }));+ toast.error(e?.message || 'Update failed');+ }+ };++ if (loading) {+ return <div className="max-w-6xl mx-auto text-gray-500 text-sm">Loading…</div>;+ }++ if (notFound || !commission) {+ return (+ <div className="max-w-6xl mx-auto text-center py-16">+ <p className="text-gray-300 mb-3">That commission no longer exists.</p>+ <Link to="/creative-commission" className="inline-flex items-center gap-2 bg-port-accent text-white px-3 py-1.5 rounded text-sm">+ <ArrowLeft className="w-4 h-4" /> Back to commissions+ </Link>+ </div>+ );+ }++ return (+ <div className="max-w-6xl mx-auto space-y-6">+ {/* Header */}+ <div>+ <Link to="/creative-commission" className="inline-flex items-center gap-1.5 text-sm text-gray-400 hover:text-gray-200 mb-3">+ <ArrowLeft className="w-4 h-4" /> Commissions+ </Link>+ <div className="flex items-start justify-between gap-3 flex-wrap">+ <div className="flex items-center gap-3 min-w-0">+ <Sparkles className="w-6 h-6 text-port-accent shrink-0" />+ <div className="min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <h1 className="text-xl font-semibold text-gray-100 truncate">{commission.name}</h1>+ <span className={`text-[10px] uppercase px-1.5 py-0.5 rounded ${commission.enabled ? 'bg-port-success/20 text-port-success' : 'bg-gray-700 text-gray-400'}`}>+ {commission.enabled ? 'Active' : 'Paused'}+ </span>+ <span className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent">{commission.targetAbility}</span>+ </div>+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-500 flex-wrap">+ <span className="flex items-center gap-1"><Clock className="w-3 h-3" /> {describeSchedule(commission.schedule)}</span>+ <span className="flex items-center gap-1" title="AI provider that writes the treatment & plan">+ <Cpu className="w-3 h-3" /> {describeAssignment(commission.assignment)}+ </span>+ {Array.isArray(commission.runs) && commission.runs.length > 0 && (+ <span>Last run {timeAgo(commission.runs[commission.runs.length - 1].ranAt)}</span>+ )}+ </div>+ </div>+ </div>+ <div className="flex items-center gap-1">+ <button+ onClick={handleRunNow}+ disabled={running}+ title="Run now (ignores schedule)"+ aria-label={`Run commission ${commission.name} now`}+ className="flex items-center gap-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-3 py-2 rounded text-sm font-medium"+ >+ <Zap className={`w-4 h-4 ${running ? 'animate-pulse' : ''}`} /> Run now+ </button>+ <button+ onClick={toggleEnabled}+ title={commission.enabled ? 'Pause' : 'Resume'}+ aria-label={commission.enabled ? 'Pause commission' : 'Resume commission'}+ className="p-2 text-gray-400 hover:text-gray-100"+ >+ {commission.enabled ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}+ </button>+ {isConfirming(commission.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ ariaLabel={`Confirm delete commission ${commission.name}`}+ onConfirm={() => confirmDelete(handleDelete)}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(commission.id)}+ title="Delete commission"+ aria-label={`Delete commission ${commission.name}`}+ className="p-2 text-gray-400 hover:text-port-error"+ >+ <Trash2 className="w-4 h-4" />+ </button>+ )}+ </div>+ </div>+ </div>++ {/* Renders — the headline: what this commission has actually produced. */}+ <section className="space-y-3">+ <h2 className="text-sm font-semibold text-gray-200">Renders</h2>+ <RenderHistory+ runs={commission.runs}+ feedback={commission.feedback}+ projectsById={projectsById}+ onRate={handleRate}+ />+ </section>++ {/* Configuration — the editable brief/schedule/generation. */}+ <section className="space-y-3 border-t border-port-border pt-6">+ <h2 className="text-sm font-semibold text-gray-200">Configuration</h2>+ <div className="bg-port-card border border-port-border rounded-lg p-4 max-w-2xl">+ <CommissionConfigForm+ form={form}+ patchForm={patchForm}+ saving={saving}+ onSave={handleSave}+ saveLabel="Save changes"+ />+ </div>+ </section>+ </div>+ );+}diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsxindex 11163f1630..9400c43989 100644--- a/client/src/pages/CreativeCommissions.jsx+++ b/client/src/pages/CreativeCommissions.jsx@@ -3,130 +3,36 @@** A Creative Commission is a standing, recurring creative brief the server fires* on a schedule through the Creative Director directive pipeline. This page lists- * every commission and hosts a deep-linked create/edit Drawer:+ * every commission and hosts the deep-linked create Drawer:* /creative-commission → index (list)* /creative-commission/new → create drawer- * /creative-commission/:id → edit drawer (with run history)+ * /creative-commission/:id → routed detail page (CreativeCommissionDetail.jsx)*+ * EDITING a commission is no longer a sidebar drawer — clicking a card navigates+ * to the routed detail page, which shows the render history + editable config.* The URL is the source of truth for what's open, per the ID-based deep-linking* rule. Mutations update local state directly (no full refetch).*/-import { useEffect, useMemo, useState, useCallback, useRef } from 'react';-import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';-import { Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, ThumbsUp, ThumbsDown, ExternalLink, Zap } from 'lucide-react';+import { useEffect, useMemo, useState, useCallback } from 'react';+import { useNavigate, useLocation } from 'react-router-dom';+import { Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, Zap } from 'lucide-react';import toast from '../components/ui/Toast';import Drawer from '../components/Drawer';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import { timeAgo } from '../utils/formatters';import { useConfirmDelete } from '../hooks/useConfirmDelete';-import { isProcessProvider } from '../utils/providers';-import ProviderModelSelector from '../components/ProviderModelSelector';+import CommissionConfigForm from '../components/creative-commission/CommissionConfigForm.jsx';import {- listCommissions, getCommission, createCommission, updateCommission, deleteCommission,- submitCommissionFeedback, runCommissionNow, getProviders,+ blankForm, toPayload, patchFormState, validateForm, describeSchedule, describeAssignment,+} from '../components/creative-commission/commissionForm.js';+import {+ listCommissions, createCommission, updateCommission, deleteCommission, runCommissionNow,} from '../services/api';-const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];--// Human-readable cadence summary for the list + drawer header.-function describeSchedule(schedule) {- if (!schedule) return 'No schedule';- const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;- if (kind === 'CUSTOM') return `Custom · ${cron || '—'}`;- if (kind === 'WEEKLY') return `Weekly · ${WEEKDAYS[weekday] ?? '—'} at ${atLocalTime || '—'}`;- if (kind === 'DAILY') return `Daily${weekdaysOnly ? ' (weekdays)' : ''} at ${atLocalTime || '—'}`;- return kind || 'No schedule';-}--// Compact "who processes this" summary for the list card. Unset → the install-// default assignment; set → the pinned provider (and model, when chosen).-function describeAssignment(assignment) {- const providerId = assignment?.providerId;- if (!providerId) return 'Install default AI';- return assignment.model ? `${providerId} · ${assignment.model}` : providerId;-}--// A blank form is just the editable projection of an empty record.-const blankForm = () => toForm({});--// Map a stored record → editable form state (fills gaps so inputs stay controlled).-function toForm(c) {- return {- name: c.name || '',- enabled: c.enabled !== false,- targetAbility: c.targetAbility || 'video',- brief: {- intent: c.brief?.intent || '',- genre: c.brief?.genre || '',- styleSpec: c.brief?.styleSpec || '',- },- schedule: {- kind: c.schedule?.kind || 'DAILY',- atLocalTime: c.schedule?.atLocalTime || '02:00',- weekday: Number.isInteger(c.schedule?.weekday) ? c.schedule.weekday : 0,- weekdaysOnly: c.schedule?.weekdaysOnly === true,- cron: c.schedule?.cron || '',- },- generation: {- quality: c.generation?.quality || 'standard',- aspectRatio: c.generation?.aspectRatio || '16:9',- targetDurationSeconds: c.generation?.targetDurationSeconds || 10,- },- // Which AI provider/model processes the commission's CD stages. Empty- // providerId → the install's default AI Assignment.- assignment: {- providerId: c.assignment?.providerId || '',- model: c.assignment?.model || '',- },- // How many recent reactions steer the next run (0 disables conditioning).- feedbackWindow: Number.isInteger(c.feedbackWindow) ? c.feedbackWindow : 5,- };-}--// Build the API payload from form state, dropping fields the schedule kind doesn't use.-function toPayload(form) {- const s = { kind: form.schedule.kind };- if (form.schedule.kind === 'CUSTOM') {- s.cron = form.schedule.cron.trim();- } else {- s.atLocalTime = form.schedule.atLocalTime;- if (form.schedule.kind === 'WEEKLY') s.weekday = Number(form.schedule.weekday);- if (form.schedule.kind === 'DAILY') s.weekdaysOnly = !!form.schedule.weekdaysOnly;- }- return {- name: form.name.trim(),- enabled: !!form.enabled,- targetAbility: form.targetAbility,- brief: {- intent: form.brief.intent.trim(),- genre: form.brief.genre.trim() || null,- styleSpec: form.brief.styleSpec,- },- schedule: s,- generation: {- quality: form.generation.quality,- aspectRatio: form.generation.aspectRatio,- targetDurationSeconds: Number(form.generation.targetDurationSeconds),- },- // Send the full pin every save; a provider-less choice clears the model too- // (the server drops a dangling model, but keeping the payload clean avoids a- // pointless round-trip through the sanitizer's normalization).- assignment: {- providerId: form.assignment.providerId || null,- model: form.assignment.providerId ? (form.assignment.model || null) : null,- },- feedbackWindow: Number(form.feedbackWindow),- };-}--const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-100 focus:outline-none focus:border-port-accent';-const labelCls = 'block text-xs font-medium text-gray-400 mb-1';-export default function CreativeCommissions() {const navigate = useNavigate();const location = useLocation();- const { id } = useParams();const [commissions, setCommissions] = useState([]);const [loading, setLoading] = useState(true);const [form, setForm] = useState(blankForm());@@ -134,14 +40,9 @@ export default function CreativeCommissions() {const [runningIds, setRunningIds] = useState(() => new Set()); // per-card "Run Now" in flightconst { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();- const drawerOpen = id != null; // '/new' or an id- const creating = id === 'new';- // Memoized so the O(n) lookup (and the sync effect that depends on it) only- // recomputes when the list or target id changes — not on every keystroke.- const editing = useMemo(- () => (drawerOpen && !creating ? commissions.find((c) => c.id === id) || null : null),- [drawerOpen, creating, commissions, id],- );+ // The create drawer is driven by the /creative-commission/new route (a static+ // segment, not an :id param — the :id route now renders the detail page).+ const creating = location.pathname.replace(/\/+$/, '').endsWith('/creative-commission/new');useEffect(() => {let cancelled = false;@@ -152,86 +53,23 @@ export default function CreativeCommissions() {return () => { cancelled = true; };}, []);- // Sync the form to the deep-linked record — but ONLY when the drawer TARGET- // changes (a new id / the create form / a first populate after load), never on- // every `editing` object-identity change. `handleRate`/`toggleEnabled` swap the- // record in local state, which changes `editing`'s reference; re-running- // `setForm(toForm(editing))` on that would silently discard any unsaved edits- // the user typed in the drawer. Keying on the last-synced id fixes that: an- // in-place update of the same id is a no-op here, while closing the drawer- // (id → null) resets the guard so reopening the same id re-syncs to the freshest- // persisted values.- const syncedTargetRef = useRef(null);- useEffect(() => {- if (creating) {- if (syncedTargetRef.current !== 'new') { setForm(blankForm()); syncedTargetRef.current = 'new'; }- } else if (editing) {- if (syncedTargetRef.current !== editing.id) { setForm(toForm(editing)); syncedTargetRef.current = editing.id; }- } else {- syncedTargetRef.current = null; // drawer closed / target not yet loaded- }- }, [id, creating, editing]);-- // Refresh the deep-linked commission when entering its detail route. The SPA- // does NOT remount when navigating index → :id (both routes render this same- // component), and the list is loaded only in the mount-only effect above — so- // a run added by a scheduled fire (surfaced via a notification deep link)- // wouldn't appear in the drawer's run history until a full reload. Refetch the- // single record and merge it in. The form-sync guard (syncedTargetRef) means- // this refresh updates the run/feedback shown in the drawer WITHOUT clobbering- // any unsaved field edits.- useEffect(() => {- if (!id || creating) return;- let cancelled = false;- getCommission(id, { silent: true })- .then((fresh) => {- if (cancelled || !fresh?.id) return;- setCommissions((prev) => (prev.some((c) => c.id === fresh.id)- ? prev.map((c) => (c.id === fresh.id ? fresh : c))- : [...prev, fresh]));- })- .catch(() => {}); // stale/deleted id → the not-found fallback handles it- return () => { cancelled = true; };- // `location.key` is in the deps so clicking the run's notification while its- // drawer is ALREADY open (a same-pathname push, where id/creating don't- // change) still re-runs the refetch and pulls in the just-fired run.- }, [id, creating, location.key]);+ // Reset the form to blank each time the create drawer opens.+ useEffect(() => { if (creating) setForm(blankForm()); }, [creating]);const closeDrawer = useCallback(() => navigate('/creative-commission'), [navigate]);+ const patchForm = useCallback((path, value) => setForm((prev) => patchFormState(prev, path, value)), []);- const patchForm = (path, value) => setForm((prev) => {- const next = { ...prev };- if (path.length === 1) next[path[0]] = value;- else { next[path[0]] = { ...prev[path[0]], [path[1]]: value }; }- return next;- });-- const handleSave = async () => {- if (!form.name.trim()) { toast.error('Name is required'); return; }- if (!form.brief.intent.trim()) { toast.error('Brief intent is required'); return; }- // A cleared number input is '', which Number() coerces to 0 — and 0 is the- // valid "disable conditioning" value, so a blank field would silently turn- // feedback off. Reject it instead of guessing intent.- const fw = Number(form.feedbackWindow);- if (form.feedbackWindow === '' || !Number.isInteger(fw) || fw < 0 || fw > 50) {- toast.error('Feedback window must be a whole number from 0 to 50');- return;- }- const payload = toPayload(form);+ const handleCreate = async () => {+ const err = validateForm(form);+ if (err) { toast.error(err); return; }setSaving(true);try {- if (creating) {- const created = await createCommission(payload, { silent: true });- setCommissions((prev) => [...prev, created]);- toast.success('Commission created');- } else if (editing) {- const updated = await updateCommission(editing.id, payload, { silent: true });- setCommissions((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));- toast.success('Commission updated');- }+ const created = await createCommission(toPayload(form), { silent: true });+ setCommissions((prev) => [...prev, created]);+ toast.success('Commission created');navigate('/creative-commission');- } catch (err) {- toast.error(err?.message || 'Save failed');+ } catch (e) {+ toast.error(e?.message || 'Save failed');} finally {setSaving(false);}@@ -243,47 +81,24 @@ export default function CreativeCommissions() {try {await deleteCommission(commission.id, { silent: true });toast.success('Commission deleted');- if (id === commission.id) navigate('/creative-commission');} catch (err) {setCommissions(prev); // rollbacktoast.error(err?.message || 'Delete failed');}};- // Rate/annotate a specific run's output (#2657, Phase 2). The reaction folds- // into the next scheduled run's directive. Reactive: swap the returned record- // into local state so the run immediately reflects its rating.- const handleRate = useCallback(async (runId, rating, note) => {- if (!editing) return;- try {- const updated = await submitCommissionFeedback(- editing.id, { runId, rating, note: note || '' }, { silent: true },- );- setCommissions((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));- toast.success('Feedback saved — it steers the next run');- } catch (err) {- toast.error(err?.message || 'Failed to save feedback');- }- }, [editing]);-- // Fire a commission immediately, outside its schedule — the "does this- // actually work" test button. Runs the same gated path as a cron tick, so a- // skip (autonomy off, over budget) is itself the test result and is toasted- // with its reason. The response carries the refreshed record (new run- // appended), which we swap into local state so run history updates reactively.+ // Fire a commission immediately, outside its schedule — the "does this actually+ // work" test button. Runs the same gated path as a cron tick, so a skip+ // (autonomy off, over budget) is itself the test result and is toasted.const handleRunNow = async (commission) => {setRunningIds((prev) => new Set(prev).add(commission.id));try {const result = await runCommissionNow(commission.id, { silent: true });- // Merge only the run-history fields the response is authoritative for —- // replacing the whole record would clobber a concurrent optimistic local- // mutation (e.g. a Pause click while the run was in flight) with the- // server re-read that predates it.if (result?.commission?.id) {const fresh = result.commission;setCommissions((prev) => prev.map((c) => (c.id === fresh.id ? { ...c, runs: fresh.runs, feedback: fresh.feedback } : c)));}- if (result?.status === 'started') toast.success('Run started — output will appear in run history');+ if (result?.status === 'started') toast.success('Run started — open the commission to watch the render');else if (result?.status === 'skipped') toast.error(`Run skipped: ${result.reason}`);else toast.error(`Run failed: ${result?.error || 'unknown error'}`);} catch (err) {@@ -309,9 +124,6 @@ export default function CreativeCommissions() {[commissions],);- // Deep link to a deleted/unknown id → not-found fallback (URL is source of truth).- const notFound = drawerOpen && !creating && !editing && !loading;-return (<div className="max-w-5xl mx-auto"><div className="flex items-center justify-between mb-6">@@ -413,435 +225,23 @@ export default function CreativeCommissions() {</div>)}- {notFound && (- <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/50" onClick={closeDrawer}>- <div className="bg-port-card border border-port-border rounded-lg p-6 text-center" onClick={(e) => e.stopPropagation()}>- <p className="text-gray-300 mb-3">That commission no longer exists.</p>- <button onClick={closeDrawer} className="bg-port-accent text-white px-3 py-1.5 rounded text-sm">Back to list</button>- </div>- </div>- )}-<Drawer- open={creating || !!editing}+ open={creating}onClose={closeDrawer}- title={creating ? 'New Commission' : 'Edit Commission'}- subtitle={!creating && editing ? editing.name : undefined}+ title="New Commission"size="md"closeOnEsc={false}closeOnBackdrop={false}>- <CommissionForm+ <CommissionConfigFormform={form}patchForm={patchForm}- runs={editing?.runs || []}- feedback={editing?.feedback || []}- onRate={editing ? handleRate : null}saving={saving}- onSave={handleSave}+ onSave={handleCreate}onCancel={closeDrawer}+ saveLabel="Create"/></Drawer></div>);}--function CommissionForm({ form, patchForm, runs, feedback, onRate, saving, onSave, onCancel }) {- // Newest-first, memoized so the copy+reverse doesn't run on every keystroke.- const orderedRuns = useMemo(() => [...runs].reverse(), [runs]);- // Latest reaction per run (last write wins), so the run row reflects the most- // recent rating the user gave it.- const feedbackByRun = useMemo(() => {- const map = {};- for (const f of feedback || []) { if (f?.runId) map[f.runId] = f; }- return map;- }, [feedback]);- return (- <div className="space-y-5">- {/* Identity */}- <section className="space-y-3">- <div>- <label className={labelCls} htmlFor="commission-name">Name</label>- <input- id="commission-name"- className={inputCls}- value={form.name}- maxLength={200}- onChange={(e) => patchForm(['name'], e.target.value)}- placeholder="Nightly Surreal"- />- </div>- <label className="flex items-center gap-2 text-sm text-gray-300">- <input- type="checkbox"- checked={form.enabled}- onChange={(e) => patchForm(['enabled'], e.target.checked)}- />- Enabled (fires on schedule)- </label>- </section>-- {/* Brief */}- <section className="space-y-3 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">Brief</h3>- <div>- <label className={labelCls} htmlFor="commission-intent">Intent</label>- <textarea- id="commission-intent"- className={`${inputCls} min-h-[70px]`}- value={form.brief.intent}- maxLength={2000}- onChange={(e) => patchForm(['brief', 'intent'], e.target.value)}- placeholder="something surreal, dreamlike, unsettlingly beautiful"- />- </div>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <div>- <label className={labelCls} htmlFor="commission-genre">Genre (optional)</label>- <input- id="commission-genre"- className={inputCls}- value={form.brief.genre}- maxLength={120}- onChange={(e) => patchForm(['brief', 'genre'], e.target.value)}- placeholder="surrealism"- />- </div>- <div>- <label className={labelCls} htmlFor="commission-style">Style notes (optional)</label>- <input- id="commission-style"- className={inputCls}- value={form.brief.styleSpec}- maxLength={5000}- onChange={(e) => patchForm(['brief', 'styleSpec'], e.target.value)}- placeholder="flat color, Magritte"- />- </div>- </div>- </section>-- {/* Schedule */}- <section className="space-y-3 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">Schedule</h3>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <div>- <label className={labelCls} htmlFor="commission-kind">Cadence</label>- <select- id="commission-kind"- className={inputCls}- value={form.schedule.kind}- onChange={(e) => patchForm(['schedule', 'kind'], e.target.value)}- >- <option value="DAILY">Daily</option>- <option value="WEEKLY">Weekly</option>- <option value="CUSTOM">Custom (cron)</option>- </select>- </div>- {form.schedule.kind !== 'CUSTOM' && (- <div>- <label className={labelCls} htmlFor="commission-time">Time (24h, local)</label>- <input- id="commission-time"- type="time"- className={inputCls}- value={form.schedule.atLocalTime}- onChange={(e) => patchForm(['schedule', 'atLocalTime'], e.target.value)}- />- </div>- )}- {form.schedule.kind === 'WEEKLY' && (- <div>- <label className={labelCls} htmlFor="commission-weekday">Day of week</label>- <select- id="commission-weekday"- className={inputCls}- value={form.schedule.weekday}- onChange={(e) => patchForm(['schedule', 'weekday'], Number(e.target.value))}- >- {WEEKDAYS.map((d, i) => <option key={i} value={i}>{d}</option>)}- </select>- </div>- )}- {form.schedule.kind === 'CUSTOM' && (- <div>- <label className={labelCls} htmlFor="commission-cron">Cron (5-field)</label>- <input- id="commission-cron"- className={inputCls}- value={form.schedule.cron}- maxLength={120}- onChange={(e) => patchForm(['schedule', 'cron'], e.target.value)}- placeholder="0 2 * * *"- />- </div>- )}- </div>- {form.schedule.kind === 'DAILY' && (- <label className="flex items-center gap-2 text-sm text-gray-300">- <input- type="checkbox"- checked={form.schedule.weekdaysOnly}- onChange={(e) => patchForm(['schedule', 'weekdaysOnly'], e.target.checked)}- />- Weekdays only (Mon–Fri)- </label>- )}- <p className="text-xs text-gray-500">{describeSchedule(form.schedule)}</p>- </section>-- {/* Generation */}- <section className="space-y-3 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">Generation (video)</h3>- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">- <div>- <label className={labelCls} htmlFor="commission-quality">Quality</label>- <select- id="commission-quality"- className={inputCls}- value={form.generation.quality}- onChange={(e) => patchForm(['generation', 'quality'], e.target.value)}- >- <option value="draft">Draft</option>- <option value="standard">Standard</option>- <option value="high">High</option>- </select>- </div>- <div>- <label className={labelCls} htmlFor="commission-aspect">Aspect ratio</label>- <select- id="commission-aspect"- className={inputCls}- value={form.generation.aspectRatio}- onChange={(e) => patchForm(['generation', 'aspectRatio'], e.target.value)}- >- <option value="16:9">16:9</option>- <option value="9:16">9:16</option>- <option value="1:1">1:1</option>- </select>- </div>- <div>- <label className={labelCls} htmlFor="commission-duration">Duration (sec)</label>- <input- id="commission-duration"- type="number"- min={5}- max={600}- className={inputCls}- value={form.generation.targetDurationSeconds}- onChange={(e) => patchForm(['generation', 'targetDurationSeconds'], e.target.value)}- />- </div>- </div>- </section>-- {/* AI provider & model — who processes this commission */}- <section className="space-y-2 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">AI provider & model</h3>- <p className="text-xs text-gray-500">- Which AI writes the treatment and production plan each time this commission runs. Leave on the- default to use your install's configured Creative Director assignment.- </p>- <AssignmentPicker- assignment={form.assignment}- onChange={(next) => patchForm(['assignment'], next)}- />- </section>-- {/* Feedback conditioning */}- <section className="space-y-2 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">Feedback conditioning</h3>- <div className="flex items-center gap-3">- <label className={`${labelCls} mb-0`} htmlFor="commission-feedback-window">Recent reactions to steer by</label>- <input- id="commission-feedback-window"- type="number"- min={0}- max={50}- className={`${inputCls} w-20`}- value={form.feedbackWindow}- onChange={(e) => patchForm(['feedbackWindow'], e.target.value)}- />- </div>- <p className="text-xs text-gray-500">- The last N ratings + notes are folded into the next run's brief. 0 disables conditioning.- </p>- </section>-- {/* Run history (edit only) */}- {runs.length > 0 && (- <section className="space-y-2 border-t border-port-border pt-4">- <h3 className="text-sm font-semibold text-gray-200">Run history</h3>- <div className="space-y-1 max-h-72 overflow-y-auto">- {orderedRuns.map((r) => (- <div key={r.id} className="text-xs bg-port-bg border border-port-border rounded px-2 py-1.5">- <div className="flex items-center justify-between gap-2">- <span className="text-gray-400">- {timeAgo(r.ranAt)}- {/* Runs persisted before the trigger field exist only from cron ticks — no badge. */}- {r.trigger === 'manual' && (- <span className="ml-1.5 text-[10px] uppercase px-1 py-0.5 rounded bg-port-accent/20 text-port-accent">manual</span>- )}- </span>- <span className={- r.status === 'started' ? 'text-port-accent'- : r.status === 'skipped' ? 'text-port-warning'- : r.status === 'failed' ? 'text-port-error' : 'text-gray-400'- }>- {r.status}{r.reason ? ` · ${r.reason}` : ''}{r.error ? ` · ${r.error}` : ''}- </span>- </div>- {/* Open the generated output so the user can inspect what they're- rating, then rate/annotate the run below. */}- {r.projectId && (- <div className="mt-1">- <Link- to={`/creative-director/${encodeURIComponent(r.projectId)}`}- className="text-port-accent hover:text-blue-400 inline-flex items-center gap-1"- >- <ExternalLink className="w-3 h-3" /> View output- </Link>- </div>- )}- {r.projectId && onRate && (- <RunFeedback runId={r.id} current={feedbackByRun[r.id]} onRate={onRate} />- )}- </div>- ))}- </div>- </section>- )}-- <div className="flex items-center gap-2 border-t border-port-border pt-4">- <button- onClick={onSave}- disabled={saving}- className="bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium"- >- {saving ? 'Saving…' : 'Save'}- </button>- <button onClick={onCancel} className="text-gray-400 hover:text-gray-200 px-4 py-2 text-sm">Cancel</button>- </div>- </div>- );-}--// AI provider/model picker for the commission's CD cognitive stages (treatment +-// plan). Mirrors SeriesLlmPicker: fetches the provider list, drives the shared-// ProviderModelSelector, and reports changes up to form state via `onChange`.-// Only agent-harness (CLI/TUI) providers are offered — an API-type provider-// injected into a CoS agent task trips the server's harness-boundary guard.-//-// The empty option deliberately does NOT name a specific provider: an unset pin-// resolves at fire time to `settings.creativeDirector.{treatment,plan}` (falling-// back to the active provider only when those stages are themselves unassigned),-// so naming the registry's active provider here would misreport the processor on-// installs that assign the CD stages separately. Label it neutrally; the section-// helper text points the user at their Creative Director assignment.-function AssignmentPicker({ assignment, onChange }) {- const [providers, setProviders] = useState([]);-- useEffect(() => {- getProviders({ silent: true })- .then((data) => setProviders((data?.providers || []).filter(isProcessProvider)))- .catch(() => { /* dropdowns fall back to the "install default" option */ });- }, []);-- const availableModels = useMemo(() => {- const p = providers.find((x) => x.id === assignment.providerId);- return p?.models || [];- }, [providers, assignment.providerId]);-- return (- <ProviderModelSelector- providers={providers}- selectedProviderId={assignment.providerId || ''}- selectedModel={assignment.model || ''}- availableModels={availableModels}- onProviderChange={(id) => onChange({ providerId: id || '', model: '' })}- onModelChange={(model) => onChange({ ...assignment, model: model || '' })}- label="Provider"- modelDisabled={availableModels.length === 0}- alwaysShowModel- emptyProviderOption="Install default (Creative Director assignment)"- emptyModelOption="Default model"- />- );-}--// Per-run rate/annotate control (#2657, Phase 2). Thumbs submit immediately,-// carrying whatever note is in the field; the current rating (if any) is shown-// highlighted. Note state is local so typing doesn't re-render the whole form.-//-// Note edits use an EXPLICIT Save affordance, not blur/focus autosave. Autosave-// on blur is a nest of edge cases — it races the vote request (blur during a-// busy window never retries), and can't reliably tell "tabbed through a thumb"-// from "clicked a thumb." A visible Save button (shown only while the note is-// dirty) makes the unsaved state obvious and unambiguous, and Enter is a-// shortcut for the same action. A note can't be saved before a rating exists (a-// rating is required), so the affordance only appears once the run is thumbed.-function RunFeedback({ runId, current, onRate }) {- const [note, setNote] = useState(current?.note || '');- const [busy, setBusy] = useState(false);- const rating = current?.rating;- const isUp = rating === 'up' || (typeof rating === 'number' && rating > 0);- const isDown = rating === 'down' || (typeof rating === 'number' && rating < 0);-- const submit = async (value) => {- setBusy(true);- try { await onRate(runId, value, note.trim()); }- finally { setBusy(false); }- };-- // A note edited after the run was rated is "dirty" until re-saved under the- // existing rating. The Save button/Enter shortcut is gated on this.- const noteDirty = !!rating && note.trim() !== (current?.note || '');- const saveNote = () => { if (noteDirty && !busy) submit(rating); };-- return (- <div className="mt-1.5 flex items-center gap-1.5">- <button- type="button"- disabled={busy}- onClick={() => submit('up')}- aria-label="Like this result"- aria-pressed={isUp}- title="Like — steer future runs toward this"- className={`p-1 rounded disabled:opacity-50 ${isUp ? 'text-port-success' : 'text-gray-500 hover:text-gray-300'}`}- >- <ThumbsUp className="w-3.5 h-3.5" />- </button>- <button- type="button"- disabled={busy}- onClick={() => submit('down')}- aria-label="Dislike this result"- aria-pressed={isDown}- title="Dislike — steer future runs away from this"- className={`p-1 rounded disabled:opacity-50 ${isDown ? 'text-port-error' : 'text-gray-500 hover:text-gray-300'}`}- >- <ThumbsDown className="w-3.5 h-3.5" />- </button>- <input- className="flex-1 min-w-0 bg-port-card border border-port-border rounded px-2 py-1 text-xs text-gray-200 focus:outline-none focus:border-port-accent"- value={note}- maxLength={1000}- placeholder={rating ? 'note (Enter to save)' : 'note — rate first, then add a note'}- aria-label={`Feedback note for run ${runId}`}- onChange={(e) => setNote(e.target.value)}- onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); saveNote(); } }}- />- {noteDirty && (- <button- type="button"- disabled={busy}- onClick={saveNote}- aria-label={`Save note for run ${runId}`}- className="text-xs text-port-accent hover:text-blue-400 disabled:opacity-50 px-1.5 py-1 whitespace-nowrap"- >- Save- </button>- )}- </div>- );-}