Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

14.9 KB
Raw Blame
/**
 * 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 state-only card ("Render removed" once loaded) with no "View output"
 * link; removed renders collapse into one expandable row below the live cards.
 */

import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router';
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';

// Launch status (`run.status`) is written once when the commission fires and never
// advances, so only a skipped/failed launch is worth printing. The render's real
// state comes from the Creative Director project.
const LAUNCH_PROBLEM_CLASS = {
  skipped: 'text-port-warning',
  failed: 'text-port-error',
};

const PROJECT_STATE = {
  complete: ['Complete', 'text-port-success'],
  rendering: ['Rendering', 'text-port-accent'],
  stitching: ['Stitching', 'text-port-accent'],
  planning: ['Planning', 'text-port-accent'],
  draft: ['Draft', 'text-gray-400'],
  paused: ['Paused', 'text-port-warning'],
  failed: ['Failed', 'text-port-error'],
};

function renderState(run, project, projectsLoading) {
  if (project) return PROJECT_STATE[project.status] || (project.status ? [project.status, 'text-gray-400'] : null);
  if (!run.projectId) return null;
  return projectsLoading ? ['Loading…', 'text-gray-500'] : ['Render removed', 'text-gray-500'];
}

const TASTE_FEEDBACK_OPTIONS = [
  ['more-familiar', 'More familiar'],
  ['more-experimental', 'More experimental'],
  ['keep-anchors', 'Keep anchors'],
  ['change-anchors', 'Change anchors'],
];

const TASTE_FEEDBACK_OPPOSITES = {
  'more-familiar': 'more-experimental',
  'more-experimental': 'more-familiar',
  'keep-anchors': 'change-anchors',
  'change-anchors': 'keep-anchors',
};

export default function RenderHistory({ runs, feedback, projectsById, projectsLoading, focusRunId, 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]);

  // Scroll the deep-linked run (`?run=<id>` from a scheduled-run notification)
  // into view once its card has rendered. Keyed on the run set too, so a card
  // that only appears after the run list loads still gets focused.
  const hasFocusRun = !!focusRunId && orderedRuns.some((r) => r.id === focusRunId);
  useEffect(() => {
    if (!hasFocusRun) return;
    const el = document.getElementById(`commission-run-${focusRunId}`);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }, [hasFocusRun, focusRunId]);

  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>
    );
  }

  const gridClass = 'grid grid-cols-1 sm:grid-cols-2 gap-3';
  const isRemoved = (r) => !!r.projectId && !projectsLoading && !projectsById.get(r.projectId);
  const liveRuns = orderedRuns.filter((r) => !isRemoved(r));
  const removedRuns = orderedRuns.filter(isRemoved);
  const focusIsRemoved = removedRuns.some((r) => r.id === focusRunId);
  const renderCard = (r) => (
    <RunCard
      key={r.id}
      run={r}
      project={r.projectId ? projectsById.get(r.projectId) : null}
      focused={r.id === focusRunId}
      projectsLoading={projectsLoading}
      current={feedbackByRun[r.id]}
      onRate={onRate}
    />
  );

  return (
    <div className="space-y-3">
      {liveRuns.length > 0 && <div className={gridClass}>{liveRuns.map(renderCard)}</div>}
      {removedRuns.length > 0 && (
        <details open={focusIsRemoved || undefined} className="border border-port-border rounded-lg bg-port-card/50">
          <summary className="cursor-pointer px-3 py-2 text-sm text-gray-400">
            {removedRuns.length === 1
              ? '1 older render is no longer available'
              : `${removedRuns.length} older renders are no longer available`}
          </summary>
          <div className={`${gridClass} p-3 pt-1`}>{removedRuns.map(renderCard)}</div>
        </details>
      )}
    </div>
  );
}

function RunCard({ run: r, project, focused, projectsLoading, current, onRate }) {
  const state = renderState(r, project, projectsLoading);
  const launchProblem = LAUNCH_PROBLEM_CLASS[r.status];
  return (
    <div
      id={`commission-run-${r.id}`}
      className={`bg-port-card border rounded-lg overflow-hidden flex flex-col ${focused ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'}`}
    >
      {/* Produced-media preview (or a status-only placeholder). Width-capped,
          not height-capped: ProjectPreview's box derives its height from an
          aspect-ratio class, so clamping height with overflow-hidden crops
          it — and pushes ProjectPreview's absolutely-centered play button
          and bottom label below the visible area for any non-16:9 ratio.
          Constraining width instead lets aspect-ratio derive a height that
          already fits, matching previewMaxWidthClass's documented approach
          in lib/creativeDirectorPreview.js. */}
      <div className="max-w-[220px] mx-auto">
        {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. Distinguish the transient load window (project
          // list still fetching) from a genuinely pruned/missing render — a real
          // render must not flash "unavailable" before the fetch resolves.
          <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 ? (projectsLoading ? 'loading…' : 'no preview') : 'no render'}</span>
          </div>
        )}
      </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="text-right">
            {state && <span className={state[1]}>{state[0]}</span>}
            {launchProblem && (
              <span className={launchProblem}>
                {state ? ' · ' : ''}{r.status}{r.reason ? ` · ${r.reason}` : ''}{r.error ? ` · ${r.error}` : ''}
              </span>
            )}
          </span>
        </div>

        {project && (
          <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>
        )}

        {r.tasteRecipe && (
          <TasteRecipeSummary recipe={r.tasteRecipe} output={r.musicOutput || project?.musicBed} />
        )}

        {/* Rate/annotate — pushed to the bottom of the card so cards align.
            Keyed on the persisted reaction's timestamp so an externally-changed
            note (a federated rating from another machine, arriving via a refetch)
            remounts the control and re-seeds its local note, instead of leaving a
            stale empty field that a Save could clobber the peer's note with. */}
        {r.projectId && onRate && (
          <div className="mt-auto pt-1">
            <RunFeedback
              key={current?.at || 'unrated'}
              runId={r.id}
              current={current}
              onRate={onRate}
              tasteAware={!!r.tasteRecipe}
            />
          </div>
        )}
      </div>
    </div>
  );
}

function TasteRecipeSummary({ recipe, output }) {
  return (
    <div className="rounded border border-port-border bg-port-bg/60 p-2 space-y-1.5 text-xs">
      <div className="flex flex-wrap gap-1">
        {(recipe.anchors || []).map((anchor, index) => (
          <span key={`${anchor.kind}-${anchor.name}-${index}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-blue-300">
            {anchor.name}{anchor.artist ? ` · ${anchor.artist}` : ''}
          </span>
        ))}
      </div>
      <p className="text-gray-400">
        {recipe.explorationPercent}% exploration · {recipe.window} window · recipe v{recipe.version}
      </p>
      <p className="text-gray-500 truncate" title={recipe.sourceVersion}>
        Source {recipe.sourceHash || 'unknown'}
      </p>
      {output && (
        <p className="text-gray-400">
          Rendered with {output.engine || 'default engine'}{output.modelId ? ` · ${output.modelId}` : ''}
        </p>
      )}
    </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, tasteAware = false }) {
  const [note, setNote] = useState(current?.note || '');
  const [tags, setTags] = useState(current?.tags || []);
  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(), tags); }
    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 currentTags = current?.tags || [];
  const tagsDirty = !!rating && JSON.stringify([...tags].sort()) !== JSON.stringify([...currentTags].sort());
  const feedbackDirty = noteDirty || tagsDirty;
  const saveNote = () => { if (feedbackDirty && !busy) submit(rating); };

  const toggleTag = (tag) => {
    setTags((value) => {
      if (value.includes(tag)) return value.filter((entry) => entry !== tag);
      const opposite = TASTE_FEEDBACK_OPPOSITES[tag];
      return [...value.filter((entry) => entry !== opposite), tag];
    });
  };

  return (
    <div className="space-y-2">
      {tasteAware && (
        <div className="flex flex-wrap gap-1" aria-label={`Taste steering for run ${runId}`}>
          {TASTE_FEEDBACK_OPTIONS.map(([tag, label]) => (
            <button
              key={tag}
              type="button"
              disabled={busy}
              aria-pressed={tags.includes(tag)}
              onClick={() => toggleTag(tag)}
              className={`rounded border px-1.5 py-0.5 text-[10px] disabled:opacity-50 ${tags.includes(tag) ? 'border-port-accent text-blue-300 bg-port-accent/15' : 'border-port-border text-gray-500'}`}
            >
              {label}
            </button>
          ))}
        </div>
      )}
      <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(); } }}
      />
      {feedbackDirty && (
        <button
          type="button"
          disabled={busy}
          onClick={saveNote}
          aria-label={`Save feedback 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>
    </div>
  );
}