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

18.1 KB
Raw Blame
import { useState, useRef } from 'react';
import * as api from '../services/api';
import useListResource from './useListResource';
import { MAX_TAGS, MAX_TAG_LENGTH } from '../components/goals/goalConstants';

// Module-level so useListResource sees a stable fetcher. silent: the pickers
// render their own inline error + Retry, so the default toast would duplicate it.
const fetchActivities = () => api.getActivities({ silent: true });
const fetchSubcalendars = async () => {
  const accounts = await api.getCalendarAccounts({ silent: true });
  const scs = [];
  for (const account of (accounts || [])) {
    for (const sc of (account.subcalendars || [])) {
      if (sc.enabled && !sc.dormant) scs.push({ ...sc, accountName: account.name });
    }
  }
  return scs;
};

// State + handlers backing GoalDetailPanel. Extracted so the panel can stay a
// thin composition shell; behavior is identical to the prior inline logic.
export function useGoalDetail({ goal, allGoals, onClose, onRefresh }) {
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({});
  const [tagInput, setTagInput] = useState('');
  const [newMilestone, setNewMilestone] = useState({ title: '', targetDate: '' });
  const [milestoneSubmitting, setMilestoneSubmitting] = useState(false);
  const milestoneSubmittingRef = useRef(false);
  const [milestoneActions, setMilestoneActions] = useState(() => new Set());
  const activitiesList = useListResource(fetchActivities);
  const activities = activitiesList.items;
  const [selectedActivity, setSelectedActivity] = useState('');
  const [showProgressForm, setShowProgressForm] = useState(false);
  const todayISO = new Date().toISOString().slice(0, 10);
  const [progressForm, setProgressForm] = useState({ date: todayISO, note: '', durationMinutes: '' });
  const [progressSubmitting, setProgressSubmitting] = useState(false);
  const progressSubmittingRef = useRef(false);
  const subcalendarsList = useListResource(fetchSubcalendars);
  const subcalendars = subcalendarsList.items;
  const [selectedCalendar, setSelectedCalendar] = useState('');
  const [calendarMatchPattern, setCalendarMatchPattern] = useState('');
  const [newTodoTitle, setNewTodoTitle] = useState('');
  const [newTodoPriority, setNewTodoPriority] = useState('medium');
  const [newTodoEstimate, setNewTodoEstimate] = useState('');
  const [todoSubmitting, setTodoSubmitting] = useState(false);
  const todoSubmittingRef = useRef(false);
  // Plan & scheduling state
  const [planOpen, setPlanOpen] = useState(false);
  const [generatingPhases, setGeneratingPhases] = useState(false);
  const [proposedPhases, setProposedPhases] = useState(null);
  const [decomposing, setDecomposing] = useState(false);
  const [proposedDecomposition, setProposedDecomposition] = useState(null);
  const [schedulingBusy, setSchedulingBusy] = useState(false);
  const [checkInsOpen, setCheckInsOpen] = useState(false);
  const [checkingIn, setCheckingIn] = useState(false);

  const startEdit = () => {
    setForm({
      title: goal.title,
      description: goal.description || '',
      horizon: goal.horizon,
      category: goal.category,
      goalType: goal.goalType || 'standard',
      parentId: goal.parentId || '',
      tags: [...(goal.tags || [])],
      targetDate: goal.targetDate || '',
      timeBlockConfig: goal.timeBlockConfig || null,
      // Per-goal Daily Driver feature-area override (issue #2679). An empty
      // array = "no override" — getGoalFeatureAreas falls back to the category
      // default, so we don't need a separate null sentinel here.
      featureAreas: [...(goal.featureAreas || [])]
    });
    setEditing(true);
  };

  const saveEdit = async () => {
    if (saving) return;
    // featureAreas handling (issue #2679):
    //  - When the user did NOT touch the selector, OMIT featureAreas from the
    //    PATCH. The whole editor sends a startEdit snapshot, so re-sending an
    //    untouched featureAreas would let a stale value win the whole-record LWW
    //    merge and clobber a concurrent featureAreas edit from a federated peer.
    //    Omitting it lets the service preserve whatever is currently stored. (The
    //    pre-#2679 editor never sent this field at all, so this restores that
    //    immunity for the untouched case.)
    //  - When the user DID change it, send the full array — INCLUDING any
    //    forward-unknown ids preserved from startEdit (the known-id-only
    //    multi-select leaves them untouched). The update schema accepts unknown
    //    ids and getGoalFeatureAreas filters them at read time, so they are never
    //    dropped.
    const { featureAreas, ...rest } = form;
    const original = goal.featureAreas || [];
    const current = featureAreas || [];
    const featureAreasChanged =
      current.length !== original.length ||
      current.some((id, i) => id !== original[i]);
    const payload = {
      ...rest,
      parentId: form.parentId || null,
      targetDate: form.targetDate || null,
      timeBlockConfig: form.timeBlockConfig || null
    };
    if (featureAreasChanged) {
      payload.featureAreas = current;
    }
    setSaving(true);
    try {
      await api.updateGoal(goal.id, payload);
    } catch {
      return;
    } finally {
      setSaving(false);
    }
    setEditing(false);
    onRefresh();
  };

  // `try/catch/finally` rather than the `.catch(() => null)` used before, for the
  // same reason as runSchedulingAction below: a bare `.catch` only covers a
  // rejected promise, so a call that threw before returning one would skip the
  // reset and latch the button on "Generating..." until a full page reload. No
  // custom toast on purpose — `request()` already toasts the failure. The stale
  // proposal is cleared up front so a failed regenerate can't read as "generation
  // succeeded and returned the same plan again".
  const handleGeneratePhases = async () => {
    setGeneratingPhases(true);
    setProposedPhases(null);
    try {
      setProposedPhases(await api.generateGoalPhases(goal.id));
    } catch {
      // Deliberately swallowed — see the single-layer note above.
    } finally {
      setGeneratingPhases(false);
    }
  };

  const handleAcceptPhases = async () => {
    if (!proposedPhases?.length) return;
    await api.acceptGoalPhases(goal.id, proposedPhases);
    setProposedPhases(null);
    onRefresh();
  };

  // Same single-layer error handling as handleGeneratePhases above.
  const handleDecompose = async () => {
    setDecomposing(true);
    setProposedDecomposition(null);
    try {
      const milestones = await api.decomposeGoal(goal.id);
      // Stamp a stable client key so the reorderable/editable proposal list keys
      // on identity, not array index (index keys mis-associate controlled-input
      // state across a swap). `_key` is stripped by the accept Zod schema.
      setProposedDecomposition(milestones.map((m, i) => ({ ...m, _key: `prop-${i}` })));
    } catch {
      // Deliberately swallowed — see the single-layer note above.
    } finally {
      setDecomposing(false);
    }
  };

  const handleAcceptDecomposition = async () => {
    if (!proposedDecomposition?.length) return;
    await api.acceptGoalDecomposition(goal.id, proposedDecomposition);
    setProposedDecomposition(null);
    onRefresh();
  };

  const handleCompleteMilestoneTask = async (milestoneId, taskId) => {
    const actionKey = `task:${milestoneId}:${taskId}`;
    if (milestoneActions.has(actionKey)) return;
    setMilestoneActions(prev => new Set(prev).add(actionKey));
    try {
      await api.completeMilestoneTask(goal.id, milestoneId, taskId);
      onRefresh();
    } catch {
      // The request helper owns the toast; keep the task available for retry.
    } finally {
      setMilestoneActions(prev => {
        const next = new Set(prev);
        next.delete(actionKey);
        return next;
      });
    }
  };

  // The response is the signal (issue #3518): a failed check-in used to expand the
  // accordion onto an unchanged list and fire a pointless refresh, so the only
  // feedback the user got was an empty panel. Now the panel opens only when the
  // server actually returned the new check-in. No custom toast on purpose —
  // `request()` already toasts the failure, so this stays a single-layer error UI.
  // `try/finally` rather than the `.catch(() => null)` used elsewhere in this hook
  // for the same reason as runSchedulingAction below: a bare `.catch` only covers a
  // rejected promise, so a call that threw before returning one would skip the reset
  // and latch the button on "Checking in..." until a full page reload.
  const handleCheckIn = async () => {
    setCheckingIn(true);
    let checkIn = null;
    try {
      checkIn = await api.checkInGoal(goal.id);
    } catch {
      // Deliberately swallowed — see the single-layer note above.
    } finally {
      setCheckingIn(false);
    }
    if (checkIn == null) return;
    setCheckInsOpen(true);
    onRefresh();
  };

  // The three time-block actions share one busy flag, so they share one runner
  // (issue #3517). Swallowing the failure is what clears `schedulingBusy` — without
  // it the buttons latch on "Scheduling..." forever and the only recovery is a full
  // page reload. No custom toast here on purpose: `request()` already toasts the
  // failure, so this stays a single-layer error UI. The refresh runs either way,
  // because a failed schedule/reschedule can still have written some blocks before
  // erroring and the panel should show reality.
  // `finally` rather than the `.catch(() => null)` used elsewhere in this hook:
  // a bare `.catch` only covers a rejected promise, so an action that threw
  // before returning one would skip the reset and re-open this very bug.
  const runSchedulingAction = async (action) => {
    setSchedulingBusy(true);
    try {
      await action(goal.id);
    } catch {
      // Deliberately swallowed — see the single-layer note above.
    } finally {
      setSchedulingBusy(false);
      onRefresh();
    }
  };

  const handleSchedule = () => runSchedulingAction(api.scheduleGoalTimeBlocks);

  const handleRemoveSchedule = () => runSchedulingAction(api.removeGoalSchedule);

  const handleReschedule = () => runSchedulingAction(api.rescheduleGoalTimeBlocks);

  const handleDelete = async () => {
    await api.deleteGoal(goal.id);
    onClose();
    onRefresh();
  };

  const handleComplete = async () => {
    await api.updateGoal(goal.id, { status: 'completed' });
    onRefresh();
  };

  const handleAddMilestone = async () => {
    if (milestoneSubmittingRef.current || !newMilestone.title.trim()) return;
    milestoneSubmittingRef.current = true;
    setMilestoneSubmitting(true);
    try {
      await api.addGoalMilestone(goal.id, {
        title: newMilestone.title,
        ...(newMilestone.targetDate ? { targetDate: newMilestone.targetDate } : {})
      });
      setNewMilestone({ title: '', targetDate: '' });
      onRefresh();
    } catch {
      // Keep the form intact so the user can retry. The request helper owns the toast.
    } finally {
      milestoneSubmittingRef.current = false;
      setMilestoneSubmitting(false);
    }
  };

  const handleCompleteMilestone = async (milestoneId) => {
    const actionKey = `milestone:${milestoneId}`;
    if (milestoneActions.has(actionKey)) return;
    setMilestoneActions(prev => new Set(prev).add(actionKey));
    try {
      await api.completeGoalMilestone(goal.id, milestoneId);
      onRefresh();
    } catch {
      // The request helper owns the toast; keep the milestone available for retry.
    } finally {
      setMilestoneActions(prev => {
        const next = new Set(prev);
        next.delete(actionKey);
        return next;
      });
    }
  };

  const handleLinkActivity = async () => {
    if (!selectedActivity) return;
    await api.linkGoalActivity(goal.id, { activityName: selectedActivity });
    setSelectedActivity('');
    onRefresh();
  };

  const handleAddProgress = async () => {
    if (progressSubmittingRef.current || !progressForm.note.trim() || !progressForm.date) return;
    progressSubmittingRef.current = true;
    setProgressSubmitting(true);
    try {
      await api.addGoalProgress(goal.id, {
        date: progressForm.date,
        note: progressForm.note,
        ...(progressForm.durationMinutes ? { durationMinutes: parseInt(progressForm.durationMinutes, 10) } : {})
      });
      setProgressForm({ date: todayISO, note: '', durationMinutes: '' });
      setShowProgressForm(false);
      onRefresh();
    } catch {
      // Keep the form intact so the user can retry. The request helper owns the toast.
    } finally {
      progressSubmittingRef.current = false;
      setProgressSubmitting(false);
    }
  };

  const resetProgressForm = () => {
    setProgressForm({ date: todayISO, note: '', durationMinutes: '' });
    setShowProgressForm(false);
  };

  const handleDeleteProgress = async (entryId) => {
    await api.deleteGoalProgress(goal.id, entryId);
    onRefresh();
  };

  const handleUnlinkActivity = async (activityName) => {
    await api.unlinkGoalActivity(goal.id, activityName);
    onRefresh();
  };

  const handleLinkCalendar = async () => {
    if (!selectedCalendar) return;
    const sc = subcalendars.find(s => s.calendarId === selectedCalendar);
    if (!sc) return;
    await api.linkGoalCalendar(goal.id, {
      subcalendarId: sc.calendarId,
      subcalendarName: sc.name,
      matchPattern: calendarMatchPattern
    });
    setSelectedCalendar('');
    setCalendarMatchPattern('');
    onRefresh();
  };

  const handleUnlinkCalendar = async (subcalendarId) => {
    await api.unlinkGoalCalendar(goal.id, subcalendarId);
    onRefresh();
  };

  // The return value is the signal (issue #3520): ProgressSlider renders its own
  // dragged `draft`, so a failed PUT has to tell it to snap back — otherwise the
  // panel keeps showing a percentage the database never took. No custom toast on
  // purpose — `request()` already toasts the failure, so this stays a single-layer
  // error UI. `try/catch` rather than a bare `.catch()` for the same reason as
  // runSchedulingAction above: a call that throws before handing back a promise
  // would skip the catch and report a save that never happened.
  const handleProgressChange = async (value) => {
    try {
      await api.updateGoalProgress(goal.id, value);
    } catch {
      return false;
    }
    onRefresh();
    return true;
  };

  const handleAddTodo = async () => {
    if (todoSubmittingRef.current || !newTodoTitle.trim()) return;
    todoSubmittingRef.current = true;
    setTodoSubmitting(true);
    try {
      await api.addGoalTodo(goal.id, {
        title: newTodoTitle,
        priority: newTodoPriority,
        ...(newTodoEstimate ? { estimateMinutes: parseInt(newTodoEstimate, 10) } : {})
      });
      setNewTodoTitle('');
      setNewTodoPriority('medium');
      setNewTodoEstimate('');
      onRefresh();
    } catch {
      // Keep the form intact so the user can retry. The request helper owns the toast.
    } finally {
      todoSubmittingRef.current = false;
      setTodoSubmitting(false);
    }
  };

  const handleToggleTodo = async (todo) => {
    const nextStatus = todo.status === 'done' ? 'pending' : 'done';
    await api.updateGoalTodo(goal.id, todo.id, { status: nextStatus });
    onRefresh();
  };

  const handleDeleteTodo = async (todoId) => {
    await api.deleteGoalTodo(goal.id, todoId);
    onRefresh();
  };

  const addTag = () => {
    const tag = tagInput.trim().slice(0, MAX_TAG_LENGTH);
    if (tag && form.tags.length < MAX_TAGS && !form.tags.includes(tag)) {
      setForm({ ...form, tags: [...form.tags, tag] });
    }
    setTagInput('');
  };

  const removeTag = (tag) => {
    setForm({ ...form, tags: form.tags.filter(t => t !== tag) });
  };

  // Toggle a Daily Driver feature-area id in the per-goal override (issue #2679).
  // Mirrors addTag/removeTag: the form owns the list, the hook owns the mutation.
  const toggleFeatureArea = (areaId) => {
    setForm(prev => {
      const current = prev.featureAreas || [];
      const next = current.includes(areaId)
        ? current.filter(a => a !== areaId)
        : [...current, areaId];
      return { ...prev, featureAreas: next };
    });
  };

  // Exclude self and descendants from parent options to prevent cycles
  const getDescendantIds = (id) => {
    const ids = new Set([id]);
    const queue = [id];
    while (queue.length) {
      const current = queue.shift();
      for (const g of (allGoals || [])) {
        if (g.parentId === current && !ids.has(g.id)) {
          ids.add(g.id);
          queue.push(g.id);
        }
      }
    }
    return ids;
  };

  return {
    editing, setEditing, saving,
    form, setForm,
    tagInput, setTagInput,
    newMilestone, setNewMilestone,
    milestoneSubmitting, milestoneActions,
    activities, activitiesState: activitiesList.state, activitiesError: activitiesList.error, retryActivities: activitiesList.retry,
    selectedActivity, setSelectedActivity,
    showProgressForm, setShowProgressForm,
    progressForm, setProgressForm,
    progressSubmitting,
    subcalendars, subcalendarsState: subcalendarsList.state, subcalendarsError: subcalendarsList.error, retrySubcalendars: subcalendarsList.retry,
    selectedCalendar, setSelectedCalendar,
    calendarMatchPattern, setCalendarMatchPattern,
    newTodoTitle, setNewTodoTitle,
    newTodoPriority, setNewTodoPriority,
    newTodoEstimate, setNewTodoEstimate,
    todoSubmitting,
    planOpen, setPlanOpen,
    generatingPhases,
    proposedPhases, setProposedPhases,
    decomposing,
    proposedDecomposition, setProposedDecomposition,
    schedulingBusy,
    checkInsOpen, setCheckInsOpen,
    checkingIn,
    startEdit, saveEdit,
    handleGeneratePhases, handleAcceptPhases,
    handleDecompose, handleAcceptDecomposition, handleCompleteMilestoneTask,
    handleCheckIn, handleSchedule, handleRemoveSchedule, handleReschedule,
    handleDelete, handleComplete,
    handleAddMilestone, handleCompleteMilestone,
    handleLinkActivity, handleAddProgress, resetProgressForm, handleDeleteProgress,
    handleUnlinkActivity, handleLinkCalendar, handleUnlinkCalendar,
    handleProgressChange, handleAddTodo, handleToggleTodo, handleDeleteTodo,
    addTag, removeTag, toggleFeatureArea, getDescendantIds
  };
}