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

fix: preview goal organization before applying it in both views (#8417)

[._.]/ Adam Eivy0c180be011ca
diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsx
index d33862ab9a..f36b68916f 100644
--- a/client/src/components/goals/GoalsListView.jsx
+++ b/client/src/components/goals/GoalsListView.jsx
@@ -9,7 +9,8 @@ import { createFreeDroppableKeyboardCoordinates, keyboardAwareCollisionDetection
import * as api from '../../services/api';
import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';
import { GOALS_LIST_PATH, goalDetailPath } from './goalConstants';
-import { applyOrganizationSuggestion } from './applyOrganization';
+import OrganizePanel from './OrganizePanel';
+import { useGoalOrganize, useGoalCreate } from '../../hooks/useGoalOrganize';
import EmptyState from '../EmptyState';
import useProviderModels from '../../hooks/useProviderModels';
import ProviderModelSelector from '../ProviderModelSelector';
@@ -211,8 +212,8 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {
const [showNewGoal, setShowNewGoal] = useState(false);
const [newGoal, setNewGoal] = useState({ ...DEFAULT_NEW_GOAL });
const [quickAdd, setQuickAdd] = useState('');
- const [isCreating, setIsCreating] = useState(false);
- const [organizing, setOrganizing] = useState(false);
+ const { isCreating, createGoal, quickAddGoal } = useGoalCreate(onRefresh);
+ const { organizing, orgSuggestion, applyingOrg, requestOrganize, applySuggestion, dismiss } = useGoalOrganize(onRefresh);
const [draggedGoal, setDraggedGoal] = useState(null);
const {
providers, selectedProviderId, selectedModel, availableModels,
@@ -280,50 +281,17 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {
};
const handleCreateGoal = async () => {
- if (!newGoal.title.trim() || isCreating) return;
- setIsCreating(true);
- try {
- await api.createGoal(newGoal, { silent: true });
+ if (await createGoal(newGoal)) {
setNewGoal({ ...DEFAULT_NEW_GOAL });
setShowNewGoal(false);
- onRefresh();
- } catch {
- toast.error('Failed to create goal');
- } finally {
- setIsCreating(false);
}
};
const handleQuickAdd = async () => {
- if (!quickAdd.trim() || isCreating) return;
- setIsCreating(true);
- try {
- await api.createGoal({ ...DEFAULT_NEW_GOAL, title: quickAdd.trim() }, { silent: true });
- setQuickAdd('');
- onRefresh();
- } catch {
- toast.error('Failed to create goal');
- } finally {
- setIsCreating(false);
- }
+ if (await quickAddGoal(quickAdd, DEFAULT_NEW_GOAL)) setQuickAdd('');
};
- const handleOrganize = async () => {
- if (!selectedProviderId) { toast.error('No API provider available'); return; }
- setOrganizing(true);
- // `silent: true` — this handler owns the failure toast below; without it
- // request() also toasts and the user sees two stacked errors.
- const result = await api.organizeGoals({ providerId: selectedProviderId, model: selectedModel }, { silent: true }).catch(() => null);
- setOrganizing(false);
- if (!result) { toast.error('Failed to organize goals'); return; }
- const applied = await applyOrganizationSuggestion(result);
- // Refresh either way: a failed apply can still have created the apex or some
- // sub-apex goals before aborting, and leaving the stale list on screen is the
- // out-of-sync state this guard exists to prevent (issue #3516).
- onRefresh();
- if (!applied) { toast.error('Failed to apply goal hierarchy'); return; }
- toast.success('Goal hierarchy applied');
- };
+ const handleOrganize = () => requestOrganize({ providerId: selectedProviderId, model: selectedModel });
const handleDragStart = useCallback((event) => {
setDraggedGoal(event.active.data.current?.goal || null);
@@ -529,6 +497,14 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {
</div>
)}
+ <OrganizePanel
+ suggestion={orgSuggestion}
+ goals={data?.flat}
+ onApply={applySuggestion}
+ onClose={dismiss}
+ applying={applyingOrg}
+ />
+
{/* Tree list with drag-and-drop */}
<DndContext
sensors={sensors}
diff --git a/client/src/components/goals/GoalsListView.test.jsx b/client/src/components/goals/GoalsListView.test.jsx
index 2679116ec6..d72b5a220d 100644
--- a/client/src/components/goals/GoalsListView.test.jsx
+++ b/client/src/components/goals/GoalsListView.test.jsx
@@ -159,6 +159,10 @@ describe('handleOrganize apply-failure path', () => {
await clickOrganize(user);
+ expect(createGoal).not.toHaveBeenCalled();
+ expect(updateGoal).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'Apply Changes' }));
+
// The apply helper stays silent so this handler is the only toast source.
expect(createGoal).toHaveBeenCalledWith(expect.objectContaining({ goalType: 'apex' }), { silent: true });
expect(applyGoalOrganization).not.toHaveBeenCalled();
@@ -177,6 +181,9 @@ describe('handleOrganize apply-failure path', () => {
const onRefresh = await renderList();
await clickOrganize(user);
+ expect(createGoal).not.toHaveBeenCalled();
+ expect(updateGoal).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'Apply Changes' }));
expect(toastError).not.toHaveBeenCalled();
expect(toastSuccess).toHaveBeenCalledWith('Goal hierarchy applied');
@@ -184,6 +191,17 @@ describe('handleOrganize apply-failure path', () => {
});
});
+it('dismisses the suggestion without changing goals', async () => {
+ const user = userEvent.setup();
+ organizeGoals.mockResolvedValue(NEW_APEX_SUGGESTION);
+ await renderList();
+ await clickOrganize(user);
+ await user.click(screen.getByRole('button', { name: 'Dismiss' }));
+ expect(screen.queryByText('Goal Organization')).not.toBeInTheDocument();
+ expect(createGoal).not.toHaveBeenCalled();
+ expect(updateGoal).not.toHaveBeenCalled();
+});
+
// #4121: which goal is open lives in the URL, never in local state — so a specific goal is
// shareable, bookmarkable, reload-safe, and linkable from the Character sheet's Goals card.
describe('routed goal selection', () => {
diff --git a/client/src/components/goals/GoalsTreeView.jsx b/client/src/components/goals/GoalsTreeView.jsx
index 5c5a84aa81..1c117979e3 100644
--- a/client/src/components/goals/GoalsTreeView.jsx
+++ b/client/src/components/goals/GoalsTreeView.jsx
@@ -2,9 +2,7 @@ import { Suspense, useState, useEffect, useMemo, useRef, useCallback } from 'rea
import { Canvas, useFrame, useThree } from '@react-three/fiber';
import { Billboard, OrbitControls, Text } from '@react-three/drei';
import * as THREE from 'three';
-import { Search, Plus, Wand2, X, Check, Star, Crown, Type } from 'lucide-react';
-import toast from '../ui/Toast';
-import * as api from '../../services/api';
+import { Search, Plus, Wand2, Type } from 'lucide-react';
import { layoutGoalNodes } from './goalTreeLayout';
import {
DIMMED_LABEL_OPACITY,
@@ -21,7 +19,8 @@ import {
orbitDistanceLimits
} from './goalTreeScene';
import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';
-import { applyOrganizationSuggestion } from './applyOrganization';
+import OrganizePanel from './OrganizePanel';
+import { useGoalOrganize, useGoalCreate } from '../../hooks/useGoalOrganize';
import useProviderModels from '../../hooks/useProviderModels';
import ProviderModelSelector from '../ProviderModelSelector';
import { enabledApiProviderFilter } from '../../utils/providers';
@@ -262,112 +261,6 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover, showLabe
);
}
-function OrganizePanel({ suggestion, goals, onApply, onClose, applying }) {
- const goalMap = useMemo(() => new Map((goals || []).map(g => [g.id, g])), [goals]);
- if (!suggestion) return null;
-
- return (
- <div className="absolute top-12 right-3 z-20 bg-port-card border border-port-border rounded-lg p-4 w-96 max-w-[calc(100vw-1rem)] max-h-dvh-cap [--dvh-cap:80dvh] overflow-y-auto shadow-xl">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Wand2 className="w-4 h-4 text-port-accent" />
- <h3 className="text-sm font-semibold text-white">Goal Organization</h3>
- </div>
- <button onClick={onClose} aria-label="Close" className="p-1 text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center"><X className="w-4 h-4" /></button>
- </div>
-
- {suggestion.analysis && (
- <p className="text-xs text-gray-400 mb-3 leading-relaxed">{suggestion.analysis}</p>
- )}
-
- {/* Apex goal suggestion */}
- {suggestion.apexGoal && (
- <div className="mb-3 p-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
- <div className="flex items-center gap-1.5 mb-1">
- <Crown className="w-3.5 h-3.5 text-amber-400" />
- <span className="text-xs font-medium text-amber-400">Apex Goal (North Star)</span>
- </div>
- {suggestion.apexGoal.existingId ? (
- <p className="text-xs text-gray-300">{goalMap.get(suggestion.apexGoal.existingId)?.title || suggestion.apexGoal.existingId}</p>
- ) : (
- <div>
- <p className="text-xs text-white font-medium">{suggestion.apexGoal.suggestedTitle}</p>
- {suggestion.apexGoal.suggestedDescription && (
- <p className="text-xs text-gray-400 mt-0.5">{suggestion.apexGoal.suggestedDescription}</p>
- )}
- <span className="text-xs text-amber-500/60 italic">New goal — will be created when applied</span>
- </div>
- )}
- </div>
- )}
-
- {/* Organization */}
- {suggestion.organization?.length > 0 && (
- <div className="mb-3 space-y-1.5">
- <h4 className="text-xs font-medium text-gray-400">Proposed Hierarchy</h4>
- {suggestion.organization.map(item => {
- const goal = goalMap.get(item.id);
- const typeCfg = GOAL_TYPE_CONFIG[item.goalType] || GOAL_TYPE_CONFIG.standard;
- const parent = item.suggestedParentId ? goalMap.get(item.suggestedParentId) : null;
- return (
- <div key={item.id} className="p-2 rounded bg-port-bg/50 border border-port-border/50">
- <div className="flex items-center gap-1.5">
- <span className={`text-xs px-1.5 py-0.5 rounded ${typeCfg.bg} ${typeCfg.color}`}>
- {typeCfg.label}
- </span>
- <span className="text-xs text-white truncate">{goal?.title || item.id}</span>
- </div>
- {parent && (
- <div className="text-xs text-gray-500 mt-0.5 ml-1">
- under: {parent.title}
- </div>
- )}
- {item.reasoning && (
- <p className="text-xs text-gray-600 mt-0.5 ml-1">{item.reasoning}</p>
- )}
- </div>
- );
- })}
- </div>
- )}
-
- {/* Suggested sub-apex goals */}
- {suggestion.suggestedSubApex?.length > 0 && (
- <div className="mb-3 space-y-1.5">
- <h4 className="text-xs font-medium text-gray-400">Suggested Sub-Apex Goals</h4>
- {suggestion.suggestedSubApex.map((sg, i) => (
- <div key={i} className="p-2 rounded bg-purple-500/5 border border-purple-500/20">
- <div className="flex items-center gap-1.5">
- <Star className="w-3 h-3 text-purple-400" />
- <span className="text-xs text-white font-medium">{sg.title}</span>
- </div>
- <p className="text-xs text-gray-400 mt-0.5">{sg.description}</p>
- <span className="text-xs text-purple-500/60 italic">New goal — will be created when applied</span>
- </div>
- ))}
- </div>
- )}
-
- <div className="flex gap-2 pt-2 border-t border-port-border">
- <button
- onClick={onApply}
- disabled={applying}
- className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 min-h-[40px]"
- >
- <Check className="w-4 h-4" />
- {applying ? 'Applying...' : 'Apply Changes'}
- </button>
- <button
- onClick={onClose}
- className="px-3 py-2 text-sm rounded-lg bg-port-border text-gray-300 hover:bg-gray-600 min-h-[40px]"
- >
- Dismiss
- </button>
- </div>
- </div>
- );
-}
-
export default function GoalsTreeView({ data, onRefresh }) {
const [selectedNode, setSelectedNode] = useState(null);
const [hoveredNode, setHoveredNode] = useState(null);
@@ -380,10 +273,8 @@ export default function GoalsTreeView({ data, onRefresh }) {
const [showLabels, setShowLabels] = useState(true);
const [showNewGoal, setShowNewGoal] = useState(false);
const [newGoal, setNewGoal] = useState({ ...DEFAULT_NEW_GOAL });
- const [isCreating, setIsCreating] = useState(false);
- const [organizing, setOrganizing] = useState(false);
- const [orgSuggestion, setOrgSuggestion] = useState(null);
- const [applyingOrg, setApplyingOrg] = useState(false);
+ const { isCreating, createGoal } = useGoalCreate(onRefresh);
+ const { organizing, orgSuggestion, applyingOrg, requestOrganize, applySuggestion, dismiss } = useGoalOrganize(onRefresh);
const {
providers, selectedProviderId, selectedModel, availableModels,
setSelectedProviderId, setSelectedModel, loading: providersLoading
@@ -441,46 +332,13 @@ export default function GoalsTreeView({ data, onRefresh }) {
};
const handleCreateGoal = async () => {
- if (!newGoal.title.trim() || isCreating) return;
- setIsCreating(true);
- try {
- await api.createGoal(newGoal, { silent: true });
+ if (await createGoal(newGoal)) {
setNewGoal({ ...DEFAULT_NEW_GOAL });
setShowNewGoal(false);
- onRefresh();
- } catch {
- toast.error('Failed to create goal');
- } finally {
- setIsCreating(false);
}
};
- const handleOrganize = async () => {
- if (!selectedProviderId) { toast.error('No API provider available'); return; }
- setOrganizing(true);
- // `silent: true` — this handler owns the failure toast below; without it
- // request() also toasts and the user sees two stacked errors.
- const result = await api.organizeGoals({ providerId: selectedProviderId, model: selectedModel }, { silent: true }).catch(() => null);
- setOrganizing(false);
- if (result) {
- setOrgSuggestion(result);
- } else {
- toast.error('Failed to organize goals');
- }
- };
-
- const handleApplyOrganization = async () => {
- if (!orgSuggestion) return;
- setApplyingOrg(true);
- const applied = await applyOrganizationSuggestion(orgSuggestion);
- setApplyingOrg(false);
- setOrgSuggestion(null);
- // Refresh either way — a failed apply can still have landed part of the hierarchy
- // (issue #3516).
- onRefresh();
- if (!applied) { toast.error('Failed to apply goal hierarchy'); return; }
- toast.success('Goal hierarchy applied');
- };
+ const handleOrganize = () => requestOrganize({ providerId: selectedProviderId, model: selectedModel });
return (
<div className="h-full flex relative">
@@ -628,8 +486,8 @@ export default function GoalsTreeView({ data, onRefresh }) {
<OrganizePanel
suggestion={orgSuggestion}
goals={data?.flat}
- onApply={handleApplyOrganization}
- onClose={() => setOrgSuggestion(null)}
+ onApply={applySuggestion}
+ onClose={dismiss}
applying={applyingOrg}
/>
diff --git a/client/src/components/goals/OrganizePanel.jsx b/client/src/components/goals/OrganizePanel.jsx
new file mode 100644
index 0000000000..f7d24be62e
--- /dev/null
+++ b/client/src/components/goals/OrganizePanel.jsx
@@ -0,0 +1,110 @@
+import { useMemo } from 'react';
+import { Wand2, X, Check, Star, Crown } from 'lucide-react';
+import { GOAL_TYPE_CONFIG } from './GoalDetailPanel';
+
+export default function OrganizePanel({ suggestion, goals, onApply, onClose, applying }) {
+ const goalMap = useMemo(() => new Map((goals || []).map(g => [g.id, g])), [goals]);
+ if (!suggestion) return null;
+
+ return (
+ <div className="absolute top-12 right-3 z-20 bg-port-card border border-port-border rounded-lg p-4 w-96 max-w-[calc(100vw-1rem)] max-h-dvh-cap [--dvh-cap:80dvh] overflow-y-auto shadow-xl">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <Wand2 className="w-4 h-4 text-port-accent" />
+ <h3 className="text-sm font-semibold text-white">Goal Organization</h3>
+ </div>
+ <button onClick={onClose} aria-label="Close" className="p-1 text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center"><X className="w-4 h-4" /></button>
+ </div>
+
+ {suggestion.analysis && (
+ <p className="text-xs text-gray-400 mb-3 leading-relaxed">{suggestion.analysis}</p>
+ )}
+
+ {/* Apex goal suggestion */}
+ {suggestion.apexGoal && (
+ <div className="mb-3 p-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Crown className="w-3.5 h-3.5 text-amber-400" />
+ <span className="text-xs font-medium text-amber-400">Apex Goal (North Star)</span>
+ </div>
+ {suggestion.apexGoal.existingId ? (
+ <p className="text-xs text-gray-300">{goalMap.get(suggestion.apexGoal.existingId)?.title || suggestion.apexGoal.existingId}</p>
+ ) : (
+ <div>
+ <p className="text-xs text-white font-medium">{suggestion.apexGoal.suggestedTitle}</p>
+ {suggestion.apexGoal.suggestedDescription && (
+ <p className="text-xs text-gray-400 mt-0.5">{suggestion.apexGoal.suggestedDescription}</p>
+ )}
+ <span className="text-xs text-amber-500/60 italic">New goal — will be created when applied</span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Organization */}
+ {suggestion.organization?.length > 0 && (
+ <div className="mb-3 space-y-1.5">
+ <h4 className="text-xs font-medium text-gray-400">Proposed Hierarchy</h4>
+ {suggestion.organization.map(item => {
+ const goal = goalMap.get(item.id);
+ const typeCfg = GOAL_TYPE_CONFIG[item.goalType] || GOAL_TYPE_CONFIG.standard;
+ const parent = item.suggestedParentId ? goalMap.get(item.suggestedParentId) : null;
+ return (
+ <div key={item.id} className="p-2 rounded bg-port-bg/50 border border-port-border/50">
+ <div className="flex items-center gap-1.5">
+ <span className={`text-xs px-1.5 py-0.5 rounded ${typeCfg.bg} ${typeCfg.color}`}>
+ {typeCfg.label}
+ </span>
+ <span className="text-xs text-white truncate">{goal?.title || item.id}</span>
+ </div>
+ {parent && (
+ <div className="text-xs text-gray-500 mt-0.5 ml-1">
+ under: {parent.title}
+ </div>
+ )}
+ {item.reasoning && (
+ <p className="text-xs text-gray-600 mt-0.5 ml-1">{item.reasoning}</p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Suggested sub-apex goals */}
+ {suggestion.suggestedSubApex?.length > 0 && (
+ <div className="mb-3 space-y-1.5">
+ <h4 className="text-xs font-medium text-gray-400">Suggested Sub-Apex Goals</h4>
+ {suggestion.suggestedSubApex.map((sg, i) => (
+ <div key={i} className="p-2 rounded bg-purple-500/5 border border-purple-500/20">
+ <div className="flex items-center gap-1.5">
+ <Star className="w-3 h-3 text-purple-400" />
+ <span className="text-xs text-white font-medium">{sg.title}</span>
+ </div>
+ <p className="text-xs text-gray-400 mt-0.5">{sg.description}</p>
+ <span className="text-xs text-purple-500/60 italic">New goal — will be created when applied</span>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-2 border-t border-port-border">
+ <button
+ onClick={onApply}
+ disabled={applying}
+ className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 min-h-[40px]"
+ >
+ <Check className="w-4 h-4" />
+ {applying ? 'Applying...' : 'Apply Changes'}
+ </button>
+ <button
+ onClick={onClose}
+ className="px-3 py-2 text-sm rounded-lg bg-port-border text-gray-300 hover:bg-gray-600 min-h-[40px]"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ );
+}
+
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 1054ab04c1..eaa1c1c112 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -265,3 +265,5 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
+
+| `useGoalOrganize` / `useGoalCreate` | Shared goal suggestion preview, explicit apply, and guarded create flows for both Goals views. | Goals List and Tree views. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index fb471244c1..33c80c5c31 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -245,3 +245,4 @@ export * from './useAccountSyncStatus.js';
export * from './useActionQueue.js';
export * from './usePagedCollection.js';
+export * from './useGoalOrganize.js';
diff --git a/client/src/hooks/useGoalOrganize.js b/client/src/hooks/useGoalOrganize.js
new file mode 100644
index 0000000000..9fe8a17e3e
--- /dev/null
+++ b/client/src/hooks/useGoalOrganize.js
@@ -0,0 +1,66 @@
+import { useRef, useState } from 'react';
+import toast from '../components/ui/Toast';
+import * as api from '../services/api';
+import { applyOrganizationSuggestion } from '../components/goals/applyOrganization';
+
+export function useGoalOrganize(onRefresh) {
+ const [organizing, setOrganizing] = useState(false);
+ const [orgSuggestion, setOrgSuggestion] = useState(null);
+ const [applyingOrg, setApplyingOrg] = useState(false);
+ const busy = useRef(false);
+
+ const requestOrganize = async ({ providerId, model }) => {
+ if (busy.current) return;
+ if (!providerId) { toast.error('No API provider available'); return; }
+ busy.current = true;
+ setOrganizing(true);
+ const result = await api.organizeGoals({ providerId, model }, { silent: true }).catch(() => null);
+ busy.current = false;
+ setOrganizing(false);
+ if (result) setOrgSuggestion(result);
+ else toast.error('Failed to organize goals');
+ };
+
+ const applySuggestion = async () => {
+ if (!orgSuggestion || busy.current) return;
+ busy.current = true;
+ setApplyingOrg(true);
+ const applied = await applyOrganizationSuggestion(orgSuggestion);
+ busy.current = false;
+ setApplyingOrg(false);
+ setOrgSuggestion(null);
+ // A failed apply can still have created part of the hierarchy.
+ onRefresh();
+ if (!applied) { toast.error('Failed to apply goal hierarchy'); return; }
+ toast.success('Goal hierarchy applied');
+ };
+
+ const dismiss = () => { if (!busy.current) setOrgSuggestion(null); };
+ return { organizing, orgSuggestion, applyingOrg, requestOrganize, applySuggestion, dismiss };
+}
+
+export function useGoalCreate(onRefresh) {
+ const [isCreating, setIsCreating] = useState(false);
+ const busy = useRef(false);
+ const submit = async (goal) => {
+ if (!goal.title.trim() || busy.current) return false;
+ busy.current = true;
+ setIsCreating(true);
+ try {
+ await api.createGoal(goal, { silent: true });
+ onRefresh();
+ return true;
+ } catch {
+ toast.error('Failed to create goal');
+ return false;
+ } finally {
+ busy.current = false;
+ setIsCreating(false);
+ }
+ };
+ return {
+ isCreating,
+ createGoal: submit,
+ quickAddGoal: (title, defaults) => submit({ ...defaults, title: title.trim() }),
+ };
+}