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

10.8 KB
Raw Blame
/**
 * Creative Commissions page — the Autonomous Creation Engine index (#2657).
 *
 * 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 the deep-linked create Drawer:
 *   /creative-commission        → index (list)
 *   /creative-commission/new    → create drawer
 *   /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 } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { CalendarClock, Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, Zap } from 'lucide-react';
import PageHeader from '../components/PageHeader';
import PageSkeleton from '../components/ui/PageSkeleton';
import EmptyState from '../components/EmptyState';
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 CommissionConfigForm from '../components/creative-commission/CommissionConfigForm.jsx';
import { toastRunOutcome } from '../components/creative-commission/runOutcomeToast.jsx';
import {
  blankForm, toPayload, patchFormState, validateForm, describeSchedule, describeAssignment,
  COMMISSION_STOP_COPY,
} from '../components/creative-commission/commissionForm.js';
import {
  listCommissions, createCommission, updateCommission, deleteCommission, runCommissionNow,
} from '../services/api';

export default function CreativeCommissions() {
  const navigate = useNavigate();
  const location = useLocation();
  const [commissions, setCommissions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState(blankForm());
  const [saving, setSaving] = useState(false);
  const [runningIds, setRunningIds] = useState(() => new Set()); // per-card "Run Now" in flight
  const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();

  // 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;
    listCommissions({ silent: true })
      .then((data) => { if (!cancelled) setCommissions(Array.isArray(data) ? data : []); })
      .catch(() => { if (!cancelled) toast.error('Failed to load commissions'); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, []);

  // 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 handleCreate = async () => {
    const err = validateForm(form);
    if (err) { toast.error(err); return; }
    setSaving(true);
    try {
      const created = await createCommission(toPayload(form), { silent: true });
      setCommissions((prev) => [...prev, created]);
      toast.success('Commission created');
      navigate('/creative-commission');
    } catch (e) {
      toast.error(e?.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (commission) => {
    const prev = commissions;
    setCommissions((cur) => cur.filter((c) => c.id !== commission.id));
    try {
      await deleteCommission(commission.id, { silent: true });
      toast.success(COMMISSION_STOP_COPY.deletedToast);
    } catch (err) {
      setCommissions(prev); // rollback
      toast.error(err?.message || 'Delete failed');
    }
  };

  // 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 });
      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)));
      }
      toastRunOutcome(result, 'Run started — open the commission to watch the render');
    } catch (err) {
      toast.error(err?.message || 'Run failed');
    } finally {
      setRunningIds((prev) => { const next = new Set(prev); next.delete(commission.id); return next; });
    }
  };

  const toggleEnabled = async (commission) => {
    const next = !commission.enabled;
    setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: next } : c)));
    try {
      await updateCommission(commission.id, { enabled: next }, { silent: true });
      toast.success(next ? COMMISSION_STOP_COPY.resumedToast : COMMISSION_STOP_COPY.pausedToast);
    } catch (err) {
      setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: commission.enabled } : c)));
      toast.error(err?.message || 'Update failed');
    }
  };

  const sorted = useMemo(
    () => [...commissions].sort((a, b) => (a.name || '').localeCompare(b.name || '')),
    [commissions],
  );

  return (
    <div className="flex h-full min-h-0 flex-col">
      <PageHeader
        icon={CalendarClock}
        title="Creative Commissions"
        subtitle="Standing briefs that create on a schedule and steer by your taste"
        actions={(
          <button
            onClick={() => navigate('/creative-commission/new')}
            className="flex items-center gap-2 bg-port-accent hover:bg-blue-600 text-white px-3 py-2 rounded text-sm font-medium"
          >
            <Plus className="w-4 h-4" /> New Commission
          </button>
        )}
      />
      <div className="flex-1 min-h-0 overflow-auto p-4">
        {loading ? (
          <PageSkeleton header="none" label="Loading commissions" cards={3} sidebar={false} />
        ) : sorted.length === 0 ? (
          <EmptyState
            icon={Sparkles}
            title="No commissions yet"
            message="Create a standing brief like “every night at 2am, make me something surreal” and it runs unattended."
            actionTo="/creative-commission/new"
            actionLabel="Create your first commission"
          />
        ) : (
          <div className="space-y-2">
            {sorted.map((c) => (
              <div
                key={c.id}
                className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg p-3 hover:border-port-accent/50 transition-colors"
              >
                <button
                  className="flex-1 text-left min-w-0"
                  onClick={() => navigate(`/creative-commission/${encodeURIComponent(c.id)}`)}
                >
                  <div className="flex items-center gap-2">
                    <span className="text-gray-100 font-medium truncate">{c.name}</span>
                    <span className={`text-[10px] uppercase px-1.5 py-0.5 rounded ${c.enabled ? 'bg-port-success/20 text-port-success' : 'bg-gray-700 text-gray-400'}`}>
                      {c.enabled ? 'Active' : 'Paused'}
                    </span>
                    <span className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent">{c.targetAbility}</span>
                  </div>
                  <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
                    <span className="flex items-center gap-1"><Clock className="w-3 h-3" /> {describeSchedule(c.schedule)}</span>
                    <span className="flex items-center gap-1" title="AI provider that writes the treatment & plan">
                      <Cpu className="w-3 h-3" /> {describeAssignment(c.assignment)}
                    </span>
                    {Array.isArray(c.runs) && c.runs.length > 0 && (
                      <span>Last run {timeAgo(c.runs[c.runs.length - 1].ranAt)}</span>
                    )}
                  </div>
                </button>
                <button
                  onClick={() => handleRunNow(c)}
                  disabled={runningIds.has(c.id)}
                  title="Run now (ignores schedule)"
                  aria-label={`Run commission ${c.name} now`}
                  className="p-2 text-gray-400 hover:text-port-accent disabled:opacity-50"
                >
                  <Zap className={`w-4 h-4 ${runningIds.has(c.id) ? 'animate-pulse text-port-accent' : ''}`} />
                </button>
                <button
                  onClick={() => toggleEnabled(c)}
                  title={c.enabled ? COMMISSION_STOP_COPY.pauseTitle : COMMISSION_STOP_COPY.resumeTitle}
                  aria-label={c.enabled ? 'Pause' : 'Resume'}
                  className="p-2 text-gray-400 hover:text-gray-100"
                >
                  {c.enabled ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                </button>
                {isConfirming(c.id) ? (
                  <ConfirmButtonPair
                    prompt="Delete?"
                    ariaLabel={`Confirm delete commission ${c.name}`}
                    onConfirm={() => confirmDelete(() => handleDelete(c))}
                    onCancel={cancelDelete}
                  />
                ) : (
                  <button
                    type="button"
                    onClick={() => requestDelete(c.id)}
                    title={COMMISSION_STOP_COPY.deleteTitle}
                    aria-label={`Delete commission ${c.name}`}
                    className="p-2 text-gray-400 hover:text-port-error"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}

        <Drawer
          open={creating}
          onClose={closeDrawer}
          title="New Commission"
          size="md"
          closeOnEsc={false}
          closeOnBackdrop={false}
        >
          <CommissionConfigForm
            form={form}
            patchForm={patchForm}
            saving={saving}
            onSave={handleCreate}
            onCancel={closeDrawer}
            saveLabel="Create"
          />
        </Drawer>
      </div>
    </div>
  );
}