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

11.4 KB
Raw Blame
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Timer, Play, StopCircle, X, FilePlus } from 'lucide-react';
import ListLoadError from '../ui/ListLoadError';
import toast from '../ui/Toast';
import {
  listWritersRoomExercises,
  createWritersRoomExercise,
  finishWritersRoomExercise,
  discardWritersRoomExercise,
  promoteWritersRoomExercise,
} from '../../services/apiWritersRoom';
import { formatCount, formatCountdown } from '../../utils/formatters';
import { countWords } from '../../lib/textUtils';
import { FormField } from '../ui/FormField';
import useListResource from '../../hooks/useListResource';
import useMounted from '../../hooks/useMounted';

const DURATION_PRESETS = [
  { label: '5 min', seconds: 300 },
  { label: '10 min', seconds: 600 },
  { label: '15 min', seconds: 900 },
  { label: '25 min', seconds: 1500 },
];

export default function ExercisePanel({ activeWork, onClose, editorDirty = false, onWorkChange, draftMutation = null, beginDraftMutation, endDraftMutation }) {
  const [duration, setDuration] = useState(600);
  const [prompt, setPrompt] = useState('');
  const [active, setActive] = useState(null); // { id, startedAt, durationSeconds, startingWords }
  const [now, setNow] = useState(Date.now());
  const [text, setText] = useState('');
  const tickRef = useRef(null);

  const mountedRef = useMounted();
  const promotingRef = useRef(false);
  const [promoting, setPromoting] = useState(false);
  const ownerKey = `${activeWork?.id || ''}:${activeWork?.activeDraftVersionId || ''}`;
  const ownerKeyRef = useRef(ownerKey);
  ownerKeyRef.current = ownerKey;

  // `useListResource` drops a response from a superseded work, so a slow
  // answer for the previous work can't overwrite the just-loaded history.
  const workId = activeWork?.id ?? null;
  const fetchHistory = useCallback(() => listWritersRoomExercises(workId, { silent: true }), [workId]);
  const {
    items: history, state: historyState, error: historyError, retry: refresh,
  } = useListResource(fetchHistory);

  // 1Hz tick while a session is running
  useEffect(() => {
    if (!active) return;
    tickRef.current = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(tickRef.current);
  }, [active]);

  const elapsed = active ? Math.floor((now - new Date(active.startedAt).getTime()) / 1000) : 0;
  const remaining = active ? active.durationSeconds - elapsed : duration;
  const wordsAdded = useMemo(() => countWords(text), [text]);
  const expired = active && remaining <= 0;

  const start = async () => {
    // Word count lives on the active draft metadata, not the work root, so
    // walk drafts → activeDraftVersionId before falling back to a top-level
    // wordCount (which only the listWorks summary exposes).
    const activeDraft = activeWork?.drafts?.find((d) => d.id === activeWork?.activeDraftVersionId);
    const startingWords = activeDraft?.wordCount ?? activeWork?.wordCount ?? 0;
    const session = await createWritersRoomExercise({
      workId: activeWork?.id ?? null,
      prompt: prompt.trim(),
      durationSeconds: duration,
      startingWords,
    }, { silent: true }).catch((err) => {
      toast.error(`Failed to start: ${err.message}`);
      return null;
    });
    if (!session) return;
    setActive(session);
    setText('');
    setNow(Date.now());
  };

  const finishSession = async ({ keep } = { keep: true }) => {
    if (!active) return;
    // Only clear local state + toast success after the server confirms; on
    // failure we keep the session active so the user can retry instead of
    // staring at a "logged 0 words" UI that's drifted from the server.
    if (keep) {
      const startingWords = active.startingWords || 0;
      const result = await finishWritersRoomExercise(active.id, {
        endingWords: startingWords + wordsAdded,
        appendedText: text || null,
      }, { silent: true }).catch((err) => {
        toast.error(`Finish failed: ${err.message}`);
        return null;
      });
      if (!result) return;
      toast.success(`Logged ${formatCount(wordsAdded)} words`);
    } else {
      const result = await discardWritersRoomExercise(active.id, { silent: true }).catch((err) => {
        toast.error(`Discard failed: ${err.message}`);
        return null;
      });
      if (!result) return;
    }
    setActive(null);
    setText('');
    await refresh();
  };

  const promote = async (exercise) => {
    if (promotingRef.current || editorDirty || draftMutation || exercise.workId !== activeWork?.id) return;
    const startOwner = ownerKeyRef.current;
    const transaction = beginDraftMutation?.(startOwner, 'exercise');
    if (beginDraftMutation && !transaction) return;
    promotingRef.current = true;
    setPromoting(true);
    const result = await promoteWritersRoomExercise(exercise.id, { silent: true }).catch((err) => {
      toast.error(`Could not add to draft: ${err.message}`);
      return null;
    });
    endDraftMutation?.(transaction);
    promotingRef.current = false;
    if (mountedRef.current) setPromoting(false);
    if (!result || ownerKeyRef.current !== startOwner) return;
    toast.success(`Added ${countWords(exercise.appendedText)} words to draft`);
    onWorkChange?.(result.work, { ownerKey: startOwner });
    if (mountedRef.current) await refresh();
  };

  // Toast once when the timer crosses into expired. The ref guards against
  // multiple fires if `expired` stays true across re-renders.
  const expiredToastedRef = useRef(false);
  useEffect(() => {
    if (!expired) {
      expiredToastedRef.current = false;
      return;
    }
    if (expiredToastedRef.current) return;
    expiredToastedRef.current = true;
    toast('Timer up — finish or keep going', { icon: '⏰' });
  }, [expired]);

  return (
    <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col h-full">
      <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border bg-port-bg/40">
        <Timer size={14} className="text-port-accent" />
        <h3 className="text-sm font-semibold text-white flex-1">Write for {Math.round(duration / 60)}</h3>
        <button onClick={onClose} className="text-gray-500 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center" aria-label="Close exercise">
          <X size={14} />
        </button>
      </div>

      {!active && (
        <div className="px-3 py-3 space-y-3">
          <div>
            <span className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Duration</span>
            <div className="flex flex-wrap gap-1">
              {DURATION_PRESETS.map(({ label, seconds }) => (
                <button
                  key={seconds}
                  onClick={() => setDuration(seconds)}
                  className={`px-2 py-1 text-xs rounded ${duration === seconds ? 'bg-port-accent text-white' : 'bg-port-bg border border-port-border text-gray-300'}`}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>

          <FormField
            labelClassName="block text-[10px] uppercase tracking-wider text-gray-500 mb-1"
            label={<>Prompt {activeWork && <span className="text-gray-600">(or leave blank to free-write {activeWork.title})</span>}</>}
          >
            <textarea
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="What should this session focus on?"
              rows={2}
              className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs"
            />
          </FormField>

          <button
            onClick={start}
            className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-port-accent text-white text-sm font-medium rounded hover:bg-port-accent/80"
          >
            <Play size={14} /> Start
          </button>
        </div>
      )}

      {active && (
        <div className="flex-1 flex flex-col min-h-0">
          <div className="px-3 py-2 border-b border-port-border bg-port-bg/40 flex items-center gap-3">
            <div className={`text-2xl font-mono ${expired ? 'text-port-error' : 'text-white'}`}>
              {formatCountdown(remaining)}
            </div>
            <div className="flex-1 text-xs text-gray-400">
              <div>{formatCount(wordsAdded)} words this session</div>
              {prompt && <div className="text-gray-500 italic truncate">{prompt}</div>}
            </div>
            <button onClick={() => finishSession({ keep: true })}
              className="flex items-center gap-1 px-2 py-1 bg-port-success/20 text-port-success text-xs rounded hover:bg-port-success/30"
              title="Save this session"
            >
              <StopCircle size={12} /> Finish
            </button>
            <button onClick={() => finishSession({ keep: false })}
              className="flex items-center gap-1 px-2 py-1 text-gray-500 text-xs rounded hover:text-port-error"
              title="Discard" aria-label="Discard"
            >
              <X size={12} />
            </button>
          </div>
          <textarea
            aria-label="Exercise text"
            autoFocus
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Just write…"
            className="flex-1 resize-none bg-port-bg text-gray-100 px-3 py-2 text-sm focus:outline-none"
            spellCheck
          />
        </div>
      )}

      <div className="border-t border-port-border bg-port-bg/40 px-3 py-2 max-h-40 overflow-y-auto">
        <h4 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Recent sessions</h4>
        {historyState === 'error' && <ListLoadError what="sessions" error={historyError} onRetry={refresh} />}
        {historyState === 'ready' && history.length === 0 && <p className="text-[11px] text-gray-600">No sessions yet</p>}
        <ul className="space-y-1">
          {history.slice(0, 8).map((ex) => (
            <li key={ex.id} className="text-[11px] flex items-center gap-2">
              <span className={`w-1.5 h-1.5 rounded-full ${
                ex.status === 'finished' ? 'bg-port-success' :
                ex.status === 'discarded' ? 'bg-gray-500' :
                'bg-port-warning animate-pulse'
              }`} />
              <span className="text-gray-300">
                {ex.status === 'finished' ? `${formatCount(ex.wordsAdded, { fallback: '0' })} words` : ex.status}
              </span>
              <span className="text-gray-600 truncate flex-1">{ex.prompt || '(free-write)'}</span>
              <span className="text-gray-600">{Math.round((ex.durationSeconds || 0) / 60)}m</span>
              {ex.promotedAt && <span className="text-port-success">✓ in draft</span>}
              {ex.status === 'finished' && ex.appendedText && ex.workId === activeWork?.id && !ex.promotedAt && (
                <button
                  onClick={() => promote(ex)}
                  disabled={editorDirty || promoting || !!draftMutation}
                  title={editorDirty ? 'Save first' : promoting || draftMutation ? 'Wait for the draft update' : 'Add to draft'}
                  aria-label="Add sprint text to draft"
                  className="min-h-[44px] min-w-[44px] flex items-center justify-center text-port-accent disabled:text-gray-600"
                >
                  <FilePlus size={15} />
                </button>
              )}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}