import { useState, useEffect, useCallback, useRef, lazy, Suspense, type CSSProperties, type MouseEvent } from "react"; import { Globe, Folder, RefreshCw, Star, HelpCircle, Loader2, CheckCircle, AlertTriangle } from "lucide-react"; import { AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, THINKING_LEVELS, getErrorMessage, isGlobalSettingsKey, isProjectSettingsKey, resolvePlanningSettingsModel, resolvePersistAgentThinkingLog, resolveProjectDefaultModel, resolveTitleSummarizerSettingsModel, } from "@fusion/core"; import type { AgentPermissionPolicyRules, Settings, GlobalSettings, ThemeMode, ColorTheme, ModelPreset, NtfyNotificationEvent, AgentPromptsConfig, ThinkingLevel } from "@fusion/core"; import { fetchSettings, fetchSettingsByScope, updateSettings, updateGlobalSettings, fetchAuthStatus, loginProvider, logoutProvider, cancelProviderLogin, saveApiKey, clearApiKey, fetchModels, testNotification, fetchBackups, createBackup, exportSettings, importSettings, fetchMemoryFile, fetchMemoryFiles, saveMemoryFile, compactMemory, fetchGlobalConcurrency, updateGlobalConcurrency, installQmd, testMemoryRetrieval, triggerMemoryDreams, fetchGitRemotes, fetchGitRemotesDetailed, fetchProjects, fetchDashboardHealth, checkForUpdates, fetchRemoteSettings, updateRemoteSettings, fetchRemoteStatus, installCloudflared, startRemoteTunnel, stopRemoteTunnel, killExternalTunnel, regenerateRemotePersistentToken, generateShortLivedRemoteToken, fetchRemoteQr, fetchRemoteUrl, submitProviderManualCode } from "../api"; import type { AuthProvider, ManualOAuthCodeInfo, ModelInfo, BackupListResponse, SettingsExportData, MemoryFileInfo, MemoryRetrievalTestResult, GitRemote, GitRemoteDetailed, ProjectInfo, RemoteSettings, RemoteStatus, UpdateCheckResponse, OAuthDeviceCodeInfo } from "../api"; import { useMemoryBackendStatus } from "../hooks/useMemoryBackendStatus"; import { useOverlayDismiss } from "../hooks/useOverlayDismiss"; import type { ToastType } from "../hooks/useToast"; import { ThemeSelector } from "./ThemeSelector"; import { useSessionBannersHidden, setSessionBannersHidden } from "../hooks/useSessionBannerPref"; import "./SettingsModal.css"; import { CustomModelDropdown } from "./CustomModelDropdown"; import { FileEditor } from "./FileEditor"; import { FileBrowser } from "./FileBrowser"; import { useWorkspaceFileBrowser } from "../hooks/useWorkspaceFileBrowser"; import { useModalResizePersist } from "../hooks/useModalResizePersist"; const PluginManager = lazy(() => import("./PluginManager").then((m) => ({ default: m.PluginManager }))); const PiExtensionsManager = lazy(() => import("./PiExtensionsManager").then((m) => ({ default: m.PiExtensionsManager }))); import { ClaudeCliProviderCard } from "./ClaudeCliProviderCard"; import { CursorCliProviderCard } from "./CursorCliProviderCard"; import { CliBinaryPanel } from "./CliBinaryPanel"; import { LlamaCppProviderCard } from "./LlamaCppProviderCard"; import { HermesRuntimeCard } from "./HermesRuntimeCard"; import { OpenClawRuntimeCard } from "./OpenClawRuntimeCard"; import { PaperclipRuntimeCard } from "./PaperclipRuntimeCard"; import { PluginSlot } from "./PluginSlot"; import { AgentPromptsManager } from "./AgentPromptsManager"; import { LoginInstructions } from "./LoginInstructions"; import { OAuthManualCodeForm } from "./OAuthManualCodeForm"; import { ProviderIcon } from "./ProviderIcon"; import { CustomProvidersSection } from "./CustomProvidersSection"; import { AgentPermissionPolicyEditor } from "./AgentPermissionPolicyEditor"; import { AgentProvisioningPolicyEditor } from "./AgentProvisioningPolicyEditor"; import { applyPresetToSelection, generateUniquePresetId } from "../utils/modelPresets"; import { appendTokenQuery } from "../auth"; import { useConfirm } from "../hooks/useConfirm"; import { useMobileKeyboard } from "../hooks/useMobileKeyboard"; import { useMobileScrollLock } from "../hooks/useMobileScrollLock"; import { useNodes } from "../hooks/useNodes"; import { useViewportMode } from "../hooks/useViewportMode"; import { useWorktrunkInstallStatus } from "../hooks/useWorktrunkInstallStatus"; import { NodeHealthDot } from "./NodeHealthDot"; import { TrackingRepoSelect, type TrackingRepoOption } from "./TrackingRepoSelect"; import { filterVisibleOnboardingAndSettingsProviders } from "./providerVisibility"; // --------------------------------------------------------------------------- // GitHub star count — fetched once per session, cached in localStorage (1 h). // --------------------------------------------------------------------------- const GITHUB_STAR_CACHE_KEY = "fusion_github_star_count"; const GITHUB_STAR_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour const GITHUB_STAR_CLICKED_KEY = "fusion:github-star-clicked"; function toCompleteAgentPermissionRules(rules?: Partial): AgentPermissionPolicyRules { return AGENT_PERMISSION_POLICY_ACTION_CATEGORIES.reduce((acc, category) => { acc[category] = rules?.[category] ?? "allow"; return acc; }, {} as AgentPermissionPolicyRules); } function getNodeStatusLabel(status: "online" | "offline" | "connecting" | "error"): string { if (status === "online") return "Online"; if (status === "connecting") return "Connecting"; if (status === "error") return "Error"; return "Offline"; } function toTrackingRepoOptions(remotes: GitRemote[]): TrackingRepoOption[] { const byValue = new Map(); for (const remote of remotes) { const value = `${remote.owner}/${remote.repo}`; if (!byValue.has(value)) { byValue.set(value, { value, label: value }); } } return [...byValue.values()].sort((a, b) => a.value.localeCompare(b.value)); } /** * Has the user already clicked the "Star on GitHub" button at any point in * the past? Used to permanently hide the button afterward — clicking opens * the repo where the actual star happens, so we treat that click as intent * to star and stop nagging. */ function useStarClickedFlag(): [boolean, () => void] { const [clicked, setClicked] = useState(() => { try { return localStorage.getItem(GITHUB_STAR_CLICKED_KEY) === "true"; } catch { return false; } }); const markClicked = useCallback(() => { setClicked(true); try { localStorage.setItem(GITHUB_STAR_CLICKED_KEY, "true"); } catch { // quota / private mode — best-effort } }, []); return [clicked, markClicked]; } interface StarCache { count: number; fetchedAt: number; } function useGitHubStarCount(): number | null { const [count, setCount] = useState(() => { try { const raw = localStorage.getItem(GITHUB_STAR_CACHE_KEY); if (raw) { const parsed: StarCache = JSON.parse(raw) as StarCache; if (Date.now() - parsed.fetchedAt < GITHUB_STAR_CACHE_TTL_MS) { return parsed.count; } } } catch { // ignore malformed cache } return null; }); useEffect(() => { // If we already have a fresh count from the initial state, skip the fetch. try { const raw = localStorage.getItem(GITHUB_STAR_CACHE_KEY); if (raw) { const parsed: StarCache = JSON.parse(raw) as StarCache; if (Date.now() - parsed.fetchedAt < GITHUB_STAR_CACHE_TTL_MS) { return; } } } catch { // ignore } fetch("https://api.github.com/repos/Runfusion/Fusion") .then((res) => { if (!res.ok) return; return res.json() as Promise<{ stargazers_count?: number }>; }) .then((data) => { if (data && typeof data.stargazers_count === "number") { const cache: StarCache = { count: data.stargazers_count, fetchedAt: Date.now() }; try { localStorage.setItem(GITHUB_STAR_CACHE_KEY, JSON.stringify(cache)); } catch { // quota exceeded — just skip } setCount(data.stargazers_count); } }) .catch(() => { // Network failure — hide count gracefully, no update }); }, []); return count; } /** * Settings sections configuration. * * Each section groups related settings fields under a sidebar nav item. * Sections have a `scope` to indicate where their settings are stored: * - "global": User-level settings stored in ~/.fusion/settings.json (shared across projects) * - "project": Project-specific settings stored in .fusion/config.json * - undefined: Section operates independently of settings storage (e.g. authentication) * * Group headers (isGroupHeader: true) are non-clickable labels that visually group sections. * The sidebar is organized into three groups: * - Account: Scope-less sections (authentication) * - Global: Global-scoped sections (appearance, notifications, node-sync, global-models) * - Project: Project-scoped sections (project-models, general, scheduling, node-routing, * worktrees, commands, merge, memory, experimental, prompts, backups, plugins) * * To add a new section: * 1. Add an entry to SETTINGS_SECTIONS with a unique id, label, and scope * 2. Add a corresponding case in renderSectionFields() */ /** Section entry type with optional icon */ type SettingsSection = { id: string; label: string; scope: "global" | "project" | undefined; icon?: typeof Globe; isGroupHeader?: boolean; }; const MOBILE_SETTINGS_MEDIA_QUERY = "(max-width: 768px)"; const DEFAULT_MEMORY_EDITOR_PATH = ".fusion/memory/DREAMS.md"; const MEMORY_FILE_OPTION_LABEL_MAX_CHARS = 72; function truncateMiddle(value: string, maxChars: number): string { if (value.length <= maxChars) { return value; } const visibleChars = Math.max(1, maxChars - 1); const startChars = Math.ceil(visibleChars / 2); const endChars = Math.floor(visibleChars / 2); return `${value.slice(0, startChars)}…${value.slice(value.length - endChars)}`; } function formatMemoryFileOptionLabel(file: MemoryFileInfo): string { const fullLabel = `${file.label} — ${file.path}`; return truncateMiddle(fullLabel, MEMORY_FILE_OPTION_LABEL_MAX_CHARS); } function toCommaSeparatedInput(values?: string[]): string { return values?.join(", ") ?? ""; } function fromCommaSeparatedInput(value: string): string[] { return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0); } const SETTINGS_SECTIONS: SettingsSection[] = [ // Account group (scope-less items — independent of settings storage) { id: "__account_header", label: "Account", scope: undefined, isGroupHeader: true }, { id: "authentication", label: "Authentication", scope: undefined, icon: Globe }, // Global group (shared across all Fusion projects) { id: "__global_header", label: "Global", scope: undefined, isGroupHeader: true }, { id: "global-general", label: "General", scope: "global" }, { id: "appearance", label: "Appearance", scope: "global" }, { id: "notifications", label: "Notifications", scope: "global" }, { id: "node-sync", label: "Node Sync", scope: "global" }, { id: "global-models", label: "Models", scope: "global" }, { id: "research-global", label: "Research Defaults", scope: "global" }, { id: "experimental", label: "Experimental Features", scope: "global" }, { id: "remote", label: "Remote Access", scope: "global" }, // Runtimes group (plugin runtimes with their own settings) { id: "__runtimes_header", label: "Runtimes", scope: undefined, isGroupHeader: true }, { id: "hermes-runtime", label: "Hermes", scope: "global" }, { id: "openclaw-runtime", label: "OpenClaw", scope: "global" }, { id: "paperclip-runtime", label: "Paperclip", scope: "global" }, // Project group (specific to this project) { id: "__project_header", label: "Project", scope: undefined, isGroupHeader: true }, { id: "general", label: "Project General", scope: "project" }, { id: "project-models", label: "Project Models", scope: "project" }, { id: "scheduling", label: "Scheduling", scope: "project" }, { id: "scheduled-evals", label: "Scheduled Evals", scope: "project" }, { id: "node-routing", label: "Node Routing", scope: "project" }, { id: "worktrees", label: "Worktrees", scope: "project" }, { id: "commands", label: "Commands", scope: "project" }, { id: "merge", label: "Merge", scope: "project" }, { id: "agent-permissions", label: "Agent Permissions", scope: "project" }, { id: "memory", label: "Memory", scope: "project" }, { id: "research-project", label: "Research", scope: "project" }, { id: "prompts", label: "Prompts", scope: "project" }, { id: "backups", label: "Backups", scope: "project" }, { id: "plugins", label: "Plugins", scope: "project" }, ]; const MS_PER_DAY = 24 * 60 * 60 * 1000; const AUTO_ARCHIVE_DEFAULT_AFTER_DAYS = 2; const DEFAULT_NTFY_EVENTS: NtfyNotificationEvent[] = [ "in-review", "merged", "failed", "awaiting-approval", "awaiting-user-review", "planning-awaiting-input", "gridlock", "fallback-used", "memory-dreams-processed", "message:agent-to-user", "message:agent-to-agent", "message:room", "oauth-token-expired", ]; const NOTIFICATION_EVENT_OPTIONS: Array<{ event: NtfyNotificationEvent; label: string; description: string }> = [ { event: "in-review", label: "Task completed (in-review)", description: "When a task moves to In Review (ready for review)" }, { event: "merged", label: "Task merged", description: "When a task is successfully merged to main" }, { event: "failed", label: "Task failed", description: "When a task fails during execution (high priority)" }, { event: "awaiting-approval", label: "Plan needs approval", description: "When a task specification needs manual approval before execution" }, { event: "awaiting-user-review", label: "User review needed", description: "When an agent hands off a task for human review (high priority)" }, { event: "planning-awaiting-input", label: "Planning needs input", description: "When planning mode is waiting for your response to continue" }, { event: "gridlock", label: "Pipeline gridlocked", description: "When all schedulable todo tasks are blocked and work cannot advance" }, { event: "fallback-used", label: "Fallback model used (recovered)", description: "When Fusion recovers from a retryable model failure by switching to a fallback model" }, { event: "memory-dreams-processed", label: "DREAMS.md entry added", description: "When manual dream processing writes a new entry to project or agent DREAMS.md" }, { event: "message:agent-to-user", label: "Agent → user message", description: "An agent sent you a direct message" }, { event: "message:agent-to-agent", label: "Agent → agent message", description: "Agents are talking to each other (including replies)" }, { event: "message:room", label: "Agent message in room", description: "An agent posted a reply in a chat room you're watching" }, { event: "oauth-token-expired", label: "OAuth token expired", description: "Notify when a provider OAuth token (Codex, Claude, etc.) expires." }, ]; /** Well-known experimental feature flags with display labels. * These always appear in the Experimental Features settings tab, * regardless of whether they exist in the project's settings blob. * IMPORTANT: Dev Server is canonically keyed by `devServerView`; `devServer` * is treated as a legacy alias and must never render as a second row. */ const KNOWN_EXPERIMENTAL_FEATURES: Record = { insights: "Insights", roadmap: "Roadmaps", memoryView: "Memory Editor", remoteAccess: "Remote Access", skillsView: "Skills View", nodesView: "Nodes View", devServerView: "Dev Server", todoView: "Todo List", researchView: "Research View", evalsView: "Evals View", goalsView: "Goals View", sandbox: "Sandbox (command isolation)", chatRooms: "Chat Rooms", agentOnboarding: "Planning-style Agent Onboarding", }; const EXPERIMENTAL_FEATURE_LEGACY_ALIASES: Record = { devServer: "devServerView", }; function getCanonicalExperimentalFeatureKey(key: string): string { return EXPERIMENTAL_FEATURE_LEGACY_ALIASES[key] ?? key; } function isExperimentalFeatureEnabled(features: Record, key: string): boolean { if (features[key] === true) { return true; } return Object.entries(EXPERIMENTAL_FEATURE_LEGACY_ALIASES).some( ([legacyKey, canonicalKey]) => canonicalKey === key && features[legacyKey] === true, ); } function normalizeExperimentalFeaturesForSave(features?: Record): Record { if (!features) { return {}; } const normalized: Record = {}; for (const [key, enabled] of Object.entries(features)) { normalized[getCanonicalExperimentalFeatureKey(key)] = enabled; } for (const [legacyKey, canonicalKey] of Object.entries(EXPERIMENTAL_FEATURE_LEGACY_ALIASES)) { if (normalized[canonicalKey] !== undefined && !(legacyKey in normalized)) { normalized[legacyKey] = null; } } return normalized; } type LegacySectionId = "pi-extensions"; export type SectionId = SettingsSection["id"] | LegacySectionId; const DEFAULT_SETTINGS_SECTION: SectionId = "global-general"; type PluginsSubsectionId = "fusion-plugins" | "pi-extensions"; /** Local form state extends Settings with a worktreeInitCommand override and lets tokenCap carry null (delete semantic). */ type SettingsFormState = Settings & { worktreeInitCommand?: string; tokenCap?: number | null }; interface SettingsModalProps { onClose: () => void; addToast: (message: string, type?: ToastType) => void; projectId?: string; /** Optional section to show when the modal first opens. Defaults to the global General section. */ initialSection?: SectionId; /** Current theme mode */ themeMode?: ThemeMode; /** Current color theme */ colorTheme?: ColorTheme; /** Called when theme mode changes */ onThemeModeChange?: (mode: ThemeMode) => void; /** Called when color theme changes */ onColorThemeChange?: (theme: ColorTheme) => void; /** Current dashboard font scale percentage */ dashboardFontScalePct?: number; /** Called when dashboard font scale changes */ onDashboardFontScaleChange?: (scalePct: number) => void; /** Optional callback when user wants to reopen the onboarding guide */ onReopenOnboarding?: () => void; /** Optional callback to open approvals/mailbox view. */ onOpenApprovals?: (approvalId?: string) => void; } export function SettingsModal({ onClose, addToast, projectId, initialSection, themeMode = "dark", colorTheme = "default", onThemeModeChange, onColorThemeChange, dashboardFontScalePct = 100, onDashboardFontScaleChange, onReopenOnboarding, onOpenApprovals, }: SettingsModalProps) { const { confirm } = useConfirm(); const worktrunkInstall = useWorktrunkInstallStatus(projectId); const worktrunkInstallVerified = worktrunkInstall.status === "installed"; const viewportMode = useViewportMode(); useMobileScrollLock(true); const { keyboardOverlap, viewportHeight, viewportOffsetTop, keyboardOpen } = useMobileKeyboard({ enabled: viewportMode === "mobile", }); const keyboardStyle: CSSProperties = keyboardOpen ? ({ "--keyboard-overlap": `${keyboardOverlap}px`, "--vv-offset-top": `${viewportOffsetTop}px`, ...(viewportHeight !== null ? { "--vv-height": `${viewportHeight}px` } : {}), } as CSSProperties) : {}; const modalRef = useRef(null); const settingsContentRef = useRef(null); useModalResizePersist(modalRef, true, "fusion:settings-modal-size"); const sessionBannersHidden = useSessionBannersHidden(); const [form, setForm] = useState({ maxConcurrent: 2, maxTriageConcurrent: 2, maxWorktrees: 4, pollIntervalMs: 15000, heartbeatMultiplier: 1, groupOverlappingFiles: true, overlapIgnorePaths: [], autoMerge: true, mergeStrategy: "direct", recycleWorktrees: false, executorAllowSiblingBranchRename: false, worktreeNaming: "random", worktreesDir: "", worktrunk: { enabled: false, binaryPath: "", onFailure: "fail", }, includeTaskIdInCommit: true, worktreeInitCommand: "", ntfyEnabled: false, ntfyTopic: undefined, ntfyAccessToken: undefined, failureNotificationMode: "sticky-only", failureNotificationDelayMs: 30000, webhookEnabled: false, webhookUrl: undefined, webhookFormat: "generic", webhookEvents: undefined, }); const [loading, setLoading] = useState(true); // Track initial values to detect explicit clears for null-as-delete semantics const [initialValues, setInitialValues] = useState(null); // Track scoped settings for inheritance detection (fetched alongside merged settings) // This stores the raw { global, project } structure from the API const [scopedSettings, setScopedSettings] = useState<{ global: GlobalSettings; project: Partial } | null>(null); // Track initial scoped values for null-as-delete semantics on project overrides const [initialScopedValues, setInitialScopedValues] = useState<{ global: GlobalSettings; project: Partial } | null>(null); // Find the first non-group-header section for visibility fallback handling const firstNonHeaderSection = SETTINGS_SECTIONS.find((s) => !s.isGroupHeader); const [activeSection, setActiveSection] = useState(() => { if (initialSection === "pi-extensions") { return "plugins"; } return initialSection ?? DEFAULT_SETTINGS_SECTION; }); // Deterministic default: opening Plugins starts on Fusion Plugins unless legacy // `initialSection="pi-extensions"` is explicitly provided. const [activePluginsSubsection, setActivePluginsSubsection] = useState(() => initialSection === "pi-extensions" ? "pi-extensions" : "fusion-plugins", ); const [showMobileSectionPicker, setShowMobileSectionPicker] = useState(() => typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(MOBILE_SETTINGS_MEDIA_QUERY)?.matches === true : false, ); const [appVersion, setAppVersion] = useState(null); const [updateCheckLoading, setUpdateCheckLoading] = useState(false); const [updateCheckResult, setUpdateCheckResult] = useState(null); const gitHubStarCount = useGitHubStarCount(); const [starClicked, markStarClicked] = useStarClickedFlag(); const [prefixError, setPrefixError] = useState(null); const [researchLimitError, setResearchLimitError] = useState(null); const [overlapPathPickerIndex, setOverlapPathPickerIndex] = useState(null); const [worktreesDirPickerOpen, setWorktreesDirPickerOpen] = useState(false); const { entries: overlapPathPickerEntries, currentPath: overlapPathPickerCurrentPath, setPath: setOverlapPathPickerPath, loading: overlapPathPickerLoading, error: overlapPathPickerError, refresh: refreshOverlapPathPicker, } = useWorkspaceFileBrowser("project", overlapPathPickerIndex !== null, projectId); const { entries: worktreesDirPickerEntries, currentPath: worktreesDirPickerCurrentPath, setPath: setWorktreesDirPickerPath, loading: worktreesDirPickerLoading, error: worktreesDirPickerError, refresh: refreshWorktreesDirPicker, } = useWorkspaceFileBrowser("project", worktreesDirPickerOpen, projectId); const { nodes } = useNodes(); const experimentalFeatures = form.experimentalFeatures ?? {}; const remoteAccessEnabled = isExperimentalFeatureEnabled(experimentalFeatures, "remoteAccess"); const researchViewEnabled = isExperimentalFeatureEnabled(experimentalFeatures, "researchView"); const evalsViewEnabled = isExperimentalFeatureEnabled(experimentalFeatures, "evalsView"); const visibleSections = SETTINGS_SECTIONS.filter((section) => { if (section.id === "remote") { return remoteAccessEnabled; } if (section.id === "research-global" || section.id === "research-project") { return researchViewEnabled; } if (section.id === "scheduled-evals") { return evalsViewEnabled; } return true; }); const firstVisibleSectionId = visibleSections.some((section) => section.id === DEFAULT_SETTINGS_SECTION) ? DEFAULT_SETTINGS_SECTION : (visibleSections.find((section) => !section.isGroupHeader)?.id ?? firstNonHeaderSection?.id ?? "general"); /** Get the scope of the currently active section */ const activeSectionScope = visibleSections.find((s) => s.id === activeSection)?.scope; useEffect(() => { if (activeSection === "remote" && !remoteAccessEnabled) { setActiveSection(firstVisibleSectionId); return; } if ((activeSection === "research-global" || activeSection === "research-project") && !researchViewEnabled) { setActiveSection(firstVisibleSectionId); return; } if (activeSection === "scheduled-evals" && !evalsViewEnabled) { setActiveSection(firstVisibleSectionId); return; } if (!visibleSections.some((section) => section.id === activeSection)) { setActiveSection(firstVisibleSectionId); } }, [activeSection, remoteAccessEnabled, researchViewEnabled, evalsViewEnabled, firstVisibleSectionId, visibleSections]); // Auth state (independent of the settings save flow) const [authProviders, setAuthProviders] = useState([]); const [authLoading, setAuthLoading] = useState(false); const [authActionInProgress, setAuthActionInProgress] = useState(null); const [loginInstructions, setLoginInstructions] = useState>({}); const [manualCodeConfigs, setManualCodeConfigs] = useState>({}); const [deviceCodes, setDeviceCodes] = useState>({}); const [manualCodeInputs, setManualCodeInputs] = useState>({}); const [manualCodeSubmitInProgress, setManualCodeSubmitInProgress] = useState(null); const [apiKeyInputs, setApiKeyInputs] = useState>({}); const [apiKeyErrors, setApiKeyErrors] = useState>({}); const pollIntervalRef = useRef | null>(null); const lastAutoCopiedDeviceCodesRef = useRef>({}); // Model state const [availableModels, setAvailableModels] = useState([]); const [modelsLoading, setModelsLoading] = useState(false); const [favoriteProviders, setFavoriteProviders] = useState([]); const [favoriteModels, setFavoriteModels] = useState([]); // Test notification state const [testNotificationLoading, setTestNotificationLoading] = useState>({}); const [testNotificationResult, setTestNotificationResult] = useState>({}); const [editingPresetId, setEditingPresetId] = useState(null); const [presetDraft, setPresetDraft] = useState(null); // Backup state const [backupInfo, setBackupInfo] = useState(null); const [backupLoading, setBackupLoading] = useState(false); // Remote access state const [remoteStatus, setRemoteStatus] = useState(null); const [externalTunnel, setExternalTunnel] = useState<{ provider: string; url: string | null } | null>(null); const [remoteBusyAction, setRemoteBusyAction] = useState(null); const [cloudflaredInstalling, setCloudflaredInstalling] = useState(false); const [cloudflaredInstallError, setCloudflaredInstallError] = useState(null); const [remoteAuthLinkTokenType, setRemoteAuthLinkTokenType] = useState<"persistent" | "short-lived">("persistent"); const [remoteUrlPreview, setRemoteUrlPreview] = useState<{ url: string; expiresAt: string | null; tokenType: "persistent" | "short-lived" } | null>(null); const [remoteQrSvg, setRemoteQrSvg] = useState(null); const [remoteShortLivedToken, setRemoteShortLivedToken] = useState<{ token: string; expiresAt: string; ttlMs: number } | null>(null); const [tunnelShareLink, setTunnelShareLink] = useState<{ url: string; qrSvg: string | null } | null>(null); // Project memory state const [memoryContent, setMemoryContent] = useState(""); const [memoryLoading, setMemoryLoading] = useState(false); const [memoryDirty, setMemoryDirty] = useState(false); // Git remotes for the worktree rebase dropdown. Loaded lazily; empty list // is a valid state (fresh repo, no remotes configured yet). const [gitRemotes, setGitRemotes] = useState([]); const [projectTrackingRepoOptions, setProjectTrackingRepoOptions] = useState([]); const [projectTrackingRepoLoading, setProjectTrackingRepoLoading] = useState(false); const [projectTrackingRepoError, setProjectTrackingRepoError] = useState(null); const [globalTrackingRepoOptions, setGlobalTrackingRepoOptions] = useState([]); const [globalTrackingRepoLoading, setGlobalTrackingRepoLoading] = useState(false); const [globalTrackingRepoError, setGlobalTrackingRepoError] = useState(null); const globalTrackingRepoLoadedRef = useRef(false); const [memoryFiles, setMemoryFiles] = useState([]); const [selectedMemoryPath, setSelectedMemoryPath] = useState(DEFAULT_MEMORY_EDITOR_PATH); const [memoryTestQuery, setMemoryTestQuery] = useState(""); const [memoryTestLoading, setMemoryTestLoading] = useState(false); const [memoryTestResult, setMemoryTestResult] = useState(null); const [dreamRunning, setDreamRunning] = useState(false); const [memoryCompactLoading, setMemoryCompactLoading] = useState(false); const [qmdInstallLoading, setQmdInstallLoading] = useState(false); const skipNextMemoryReloadRef = useRef(false); // Global concurrency state const [globalMaxConcurrent, setGlobalMaxConcurrent] = useState(4); const initialGlobalMaxConcurrentRef = useRef(4); const hasFetchedGlobalConcurrencyRef = useRef(false); const globalConcurrencyDirtyRef = useRef(false); // Import/Export state const [importDialogOpen, setImportDialogOpen] = useState(false); const [, setImportFile] = useState(null); const [importPreview, setImportPreview] = useState(null); const [importLoading, setImportLoading] = useState(false); const [importScope, setImportScope] = useState<'global' | 'project' | 'both'>('both'); const [importMerge, setImportMerge] = useState(true); const fileInputRef = useRef(null); // Memory backend status - called at component top level to comply with React Rules of Hooks const { status: memoryBackendStatus, capabilities: memoryCapabilities, loading: memoryBackendLoading, error: memoryBackendError, refresh: refreshMemoryBackend, } = useMemoryBackendStatus({ projectId, enabled: activeSection === "memory", }); useEffect(() => { if (typeof window === "undefined" || typeof window.matchMedia !== "function") { return; } const mediaQuery = window.matchMedia(MOBILE_SETTINGS_MEDIA_QUERY); if (!mediaQuery) { return; } const updateMobilePicker = (event?: MediaQueryListEvent) => { setShowMobileSectionPicker(event ? event.matches : mediaQuery.matches); }; updateMobilePicker(); mediaQuery.addEventListener("change", updateMobilePicker); return () => mediaQuery.removeEventListener("change", updateMobilePicker); }, []); useEffect(() => { // Load both merged and scoped settings to enable inheritance detection Promise.all([fetchSettings(projectId), fetchSettingsByScope(projectId)]) .then(([s, scoped]) => { setForm(s); setInitialValues(s); // Store initial values to detect explicit clears setScopedSettings(scoped); setInitialScopedValues(scoped); // Store initial scoped values for null-as-delete setLoading(false); }) .catch((err) => { addToast(getErrorMessage(err), "error"); setLoading(false); }); }, [addToast, projectId]); useEffect(() => { if (activeSection !== "scheduling" || hasFetchedGlobalConcurrencyRef.current) { return; } let cancelled = false; fetchGlobalConcurrency() .then((state) => { if (cancelled) { return; } if (!globalConcurrencyDirtyRef.current) { setGlobalMaxConcurrent(state.globalMaxConcurrent); } initialGlobalMaxConcurrentRef.current = state.globalMaxConcurrent; hasFetchedGlobalConcurrencyRef.current = true; }) .catch(() => { // Silently fail — global concurrency may not be available }); return () => { cancelled = true; }; }, [activeSection]); useEffect(() => { let cancelled = false; fetchDashboardHealth() .then((health) => { if (cancelled) { return; } if (typeof health.version === "string" && health.version.trim().length > 0) { setAppVersion(health.version); } }) .catch(() => { // Non-blocking metadata only — settings remains usable when unavailable. }); return () => { cancelled = true; }; }, []); const handleCheckForUpdates = useCallback(async () => { setUpdateCheckLoading(true); try { const result = await checkForUpdates(); setUpdateCheckResult(result); if (result.error) { addToast(result.error, "error"); } } catch (error) { const message = getErrorMessage(error) || "Failed to check for updates"; setUpdateCheckResult({ currentVersion: appVersion ?? "unknown", latestVersion: null, updateAvailable: false, error: message, }); addToast(message, "error"); } finally { setUpdateCheckLoading(false); } }, [addToast, appVersion]); const renderUpdateCheckResultContent = useCallback(() => { if (!updateCheckResult) { return null; } if (updateCheckResult.error) { return updateCheckResult.error; } if (updateCheckResult.updateAvailable && updateCheckResult.latestVersion) { return ( <> v{updateCheckResult.latestVersion} available ·{" "} Learn more ); } return "You're up to date ✓"; }, [updateCheckResult]); // Load auth status when the authentication section is active const loadAuthStatus = useCallback(async () => { try { const { providers } = await fetchAuthStatus(); const visibleProviders = filterVisibleOnboardingAndSettingsProviders(providers); setAuthProviders(visibleProviders); setLoginInstructions((prev) => { const next: Record = {}; for (const [providerId, instructions] of Object.entries(prev)) { const provider = visibleProviders.find((candidate) => candidate.id === providerId); if (provider && !provider.authenticated) { next[providerId] = instructions; } } return Object.keys(next).length === Object.keys(prev).length ? prev : next; }); } catch { // Silently fail — auth may not be configured } }, []); useEffect(() => { if (activeSection === "global-models" || activeSection === "project-models") { setModelsLoading(true); fetchModels() .then((response) => { setAvailableModels(response.models); setFavoriteProviders(response.favoriteProviders); setFavoriteModels(response.favoriteModels); }) .catch(() => setAvailableModels([])) .finally(() => setModelsLoading(false)); } }, [activeSection]); useEffect(() => { if (activeSection === "backups") { setBackupLoading(true); fetchBackups(projectId) .then((info) => setBackupInfo(info)) .catch(() => setBackupInfo(null)) .finally(() => setBackupLoading(false)); } }, [activeSection, projectId]); const loadRemoteData = useCallback(async () => { const [settingsResult, statusResult] = await Promise.allSettled([ fetchRemoteSettings(projectId), fetchRemoteStatus(projectId), ]); if (settingsResult.status === "fulfilled") { setForm((prev) => ({ ...prev, ...(settingsResult.value.settings as unknown as Partial) })); } if (statusResult.status === "fulfilled") { setRemoteStatus(statusResult.value); setExternalTunnel(statusResult.value.externalTunnel ?? null); } }, [projectId]); useEffect(() => { const state = remoteStatus?.state; if (state === "running" || state === "starting") { setExternalTunnel(null); } }, [remoteStatus?.state]); useEffect(() => { if (activeSection !== "remote") { return; } loadRemoteData().catch(() => { setRemoteStatus(null); }); }, [activeSection, loadRemoteData]); // Poll remote status while the tunnel is starting so the UI flips to // "running" without the user closing/reopening the modal. Stops polling // once it reaches a terminal state. useEffect(() => { if (activeSection !== "remote") return; const state = remoteStatus?.state; if (state !== "starting" && state !== "stopping") return; const interval = setInterval(() => { fetchRemoteStatus(projectId) .then((status) => { setRemoteStatus(status); setExternalTunnel(status.externalTunnel ?? null); }) .catch(() => {}); }, 1000); return () => clearInterval(interval); }, [activeSection, projectId, remoteStatus?.state]); // When the tunnel is running, fetch a persistent-token authenticated URL + // QR so the user can share/scan it without digging into Advanced Settings. useEffect(() => { if (activeSection !== "remote") return; if (remoteStatus?.state !== "running") { setTunnelShareLink(null); return; } let cancelled = false; (async () => { try { const qr = await fetchRemoteQr("image/svg", { projectId, tokenType: "persistent" }); if (cancelled) return; setTunnelShareLink({ url: qr.url, qrSvg: qr.data ?? null }); } catch { if (cancelled) return; try { const link = await fetchRemoteUrl({ projectId, tokenType: "persistent" }); if (cancelled) return; setTunnelShareLink({ url: link.url, qrSvg: null }); } catch { if (!cancelled) setTunnelShareLink(null); } } })(); return () => { cancelled = true; }; }, [activeSection, projectId, remoteStatus?.state, remoteStatus?.url]); useEffect(() => { if (activeSection !== "remote") return; const tunnelUrl = externalTunnel?.url; if (remoteStatus?.state !== "stopped" || !tunnelUrl) { return; } let cancelled = false; (async () => { try { const qr = await fetchRemoteQr("image/svg", { projectId, tokenType: "persistent" }); if (cancelled) return; setTunnelShareLink({ url: tunnelUrl, qrSvg: qr.data ?? null }); } catch { if (!cancelled) { setTunnelShareLink({ url: tunnelUrl, qrSvg: null }); } } })(); return () => { cancelled = true; }; }, [activeSection, externalTunnel?.url, projectId, remoteStatus?.state]); // Lazy-load git remotes for the rebase-remote dropdown when the Worktrees // section becomes visible. Failure is non-fatal: the dropdown falls back // to just "Use git default". useEffect(() => { if (activeSection !== "worktrees") return; fetchGitRemotesDetailed(projectId) .then((remotes) => setGitRemotes(remotes)) .catch(() => setGitRemotes([])); }, [activeSection, projectId]); useEffect(() => { if (activeSection !== "general") { return; } let cancelled = false; setProjectTrackingRepoLoading(true); setProjectTrackingRepoError(null); fetchGitRemotes(projectId) .then((remotes) => { if (cancelled) { return; } setProjectTrackingRepoOptions(toTrackingRepoOptions(remotes)); }) .catch(() => { if (cancelled) { return; } setProjectTrackingRepoOptions([]); setProjectTrackingRepoError("Could not load detected remotes. Enter a custom owner/repo value."); }) .finally(() => { if (!cancelled) { setProjectTrackingRepoLoading(false); } }); return () => { cancelled = true; }; }, [activeSection, projectId]); useEffect(() => { if (activeSection !== "global-general" || globalTrackingRepoLoadedRef.current) { return; } let cancelled = false; setGlobalTrackingRepoLoading(true); setGlobalTrackingRepoError(null); fetchProjects() .then(async (projects) => { const results = await Promise.allSettled( projects.map(async (project: ProjectInfo) => { const remotes = await fetchGitRemotes(project.id); return remotes.map((remote) => ({ value: `${remote.owner}/${remote.repo}`, label: `${remote.owner}/${remote.repo}`, source: project.name, })); }), ); if (cancelled) { return; } const optionsByValue = new Map(); let successCount = 0; for (const result of results) { if (result.status !== "fulfilled") { continue; } successCount += 1; for (const option of result.value) { if (!optionsByValue.has(option.value)) { optionsByValue.set(option.value, option); } } } const flattenedOptions = [...optionsByValue.values()].sort((a, b) => a.value.localeCompare(b.value)); setGlobalTrackingRepoOptions(flattenedOptions); if (projects.length > 0 && successCount === 0) { setGlobalTrackingRepoError("Could not load remotes from registered projects. Enter a custom owner/repo value."); } globalTrackingRepoLoadedRef.current = true; }) .catch(() => { if (cancelled) { return; } setGlobalTrackingRepoOptions([]); setGlobalTrackingRepoError("Could not load project list. Enter a custom owner/repo value."); globalTrackingRepoLoadedRef.current = true; }) .finally(() => { if (!cancelled) { setGlobalTrackingRepoLoading(false); } }); return () => { cancelled = true; }; }, [activeSection, projectId]); useEffect(() => { if (activeSection !== "memory" || memoryDirty) { return; } if (skipNextMemoryReloadRef.current) { skipNextMemoryReloadRef.current = false; return; } let cancelled = false; setMemoryLoading(true); fetchMemoryFiles(projectId) .then(async ({ files }) => { if (cancelled) return; setMemoryFiles(files); const nextPath = files.some((file) => file.path === selectedMemoryPath) ? selectedMemoryPath : files.find((file) => file.path === DEFAULT_MEMORY_EDITOR_PATH)?.path ?? files.find((file) => file.layer === "dreams")?.path ?? files[0]?.path ?? DEFAULT_MEMORY_EDITOR_PATH; setSelectedMemoryPath(nextPath); const { content } = await fetchMemoryFile(nextPath, projectId); if (cancelled) return; setMemoryContent(content); setMemoryDirty(false); }) .catch((err) => { if (cancelled) return; addToast(getErrorMessage(err) || "Failed to load project memory", "error"); setMemoryContent(""); }) .finally(() => { if (!cancelled) { setMemoryLoading(false); } }); return () => { cancelled = true; }; }, [activeSection, memoryDirty, selectedMemoryPath, projectId, addToast]); useEffect(() => { if (activeSection === "authentication" || activeSection === "research-global") { setAuthLoading(true); loadAuthStatus().finally(() => setAuthLoading(false)); } // Clean up polling when leaving auth section return () => { if (pollIntervalRef.current) { clearInterval(pollIntervalRef.current); pollIntervalRef.current = null; } }; }, [activeSection, loadAuthStatus]); useEffect(() => { if (activeSection !== "authentication") { return; } const hasPendingServerLogin = authProviders.some((provider) => provider.type !== "api_key" && provider.loginInProgress); if (!hasPendingServerLogin) { return; } const interval = setInterval(() => { void loadAuthStatus(); }, 2000); return () => clearInterval(interval); }, [activeSection, authProviders, loadAuthStatus]); const scrollSettingsToTop = useCallback(() => { settingsContentRef.current?.scrollTo({ top: 0, behavior: "smooth" }); }, []); const clearAuthLoginUiState = useCallback((providerId: string) => { if (providerId in lastAutoCopiedDeviceCodesRef.current) { const next = { ...lastAutoCopiedDeviceCodesRef.current }; delete next[providerId]; lastAutoCopiedDeviceCodesRef.current = next; } setLoginInstructions((prev) => { if (!(providerId in prev)) { return prev; } const next = { ...prev }; delete next[providerId]; return next; }); setManualCodeConfigs((prev) => { if (!(providerId in prev)) { return prev; } const next = { ...prev }; delete next[providerId]; return next; }); setManualCodeInputs((prev) => { if (!(providerId in prev)) { return prev; } const next = { ...prev }; delete next[providerId]; return next; }); setDeviceCodes((prev) => { if (!(providerId in prev)) { return prev; } const next = { ...prev }; delete next[providerId]; return next; }); }, []); useEffect(() => { const copilotDeviceCode = deviceCodes["github-copilot"]; if (!copilotDeviceCode?.userCode) { return; } if (lastAutoCopiedDeviceCodesRef.current["github-copilot"] === copilotDeviceCode.userCode) { return; } lastAutoCopiedDeviceCodesRef.current["github-copilot"] = copilotDeviceCode.userCode; void navigator.clipboard?.writeText(copilotDeviceCode.userCode); }, [deviceCodes]); const handleLogin = useCallback(async (providerId: string) => { const provider = authProviders.find((entry) => entry.id === providerId); if (provider?.requiresManualCode === true) { const shouldContinue = await confirm({ title: "Heads up — manual paste-back required", message: `After you sign in with ${provider.name}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?`, confirmLabel: "Continue to login", cancelLabel: "Cancel", }); if (!shouldContinue) { return; } } setAuthActionInProgress(providerId); clearAuthLoginUiState(providerId); try { const { url, instructions, manualCode, deviceCode } = await loginProvider(providerId); if (instructions?.trim() && !(providerId === "github-copilot" && deviceCode)) { setLoginInstructions((prev) => ({ ...prev, [providerId]: instructions })); } if (manualCode) { setManualCodeConfigs((prev) => ({ ...prev, [providerId]: manualCode })); } if (deviceCode && providerId === "github-copilot") { setDeviceCodes((prev) => ({ ...prev, [providerId]: deviceCode })); } if (providerId !== "github-copilot" || !deviceCode) { window.open(appendTokenQuery(deviceCode?.verificationUri ?? url), "_blank"); } // Poll for auth completion every 2 seconds pollIntervalRef.current = setInterval(async () => { try { const { providers } = await fetchAuthStatus(); const visibleProviders = filterVisibleOnboardingAndSettingsProviders(providers); setAuthProviders(visibleProviders); const provider = visibleProviders.find((p) => p.id === providerId); if (provider?.authenticated) { if (pollIntervalRef.current) { clearInterval(pollIntervalRef.current); pollIntervalRef.current = null; } setAuthActionInProgress(null); clearAuthLoginUiState(providerId); addToast("Login successful", "success"); scrollSettingsToTop(); return; } if (!provider?.loginInProgress) { if (pollIntervalRef.current) { clearInterval(pollIntervalRef.current); pollIntervalRef.current = null; } setAuthActionInProgress(null); clearAuthLoginUiState(providerId); addToast("Login did not complete. Please try again.", "error"); } } catch { // Continue polling on transient errors } }, 2000); } catch (err) { const message = getErrorMessage(err) || "Login failed"; const isConflict = message.includes("already in progress") || (typeof err === "object" && err !== null && "status" in err && (err as { status?: number }).status === 409); if (isConflict) { addToast("Login already in progress. You can cancel it and retry.", "warning"); await loadAuthStatus(); } else { addToast(message, "error"); } setAuthActionInProgress(null); clearAuthLoginUiState(providerId); } }, [addToast, authProviders, clearAuthLoginUiState, confirm, loadAuthStatus, scrollSettingsToTop]); const handleSubmitManualCode = useCallback(async (providerId: string) => { const code = manualCodeInputs[providerId]?.trim(); if (!code) { addToast("Paste the full redirect URL or authorization code first.", "warning"); return; } setManualCodeSubmitInProgress(providerId); try { const result = await submitProviderManualCode(providerId, code); if (result.submitted) { setManualCodeInputs((prev) => { if (!(providerId in prev)) { return prev; } const next = { ...prev }; delete next[providerId]; return next; }); addToast("Authorization code received. Finishing login…", "success"); } else { addToast("That authorization code was already submitted. Waiting for login…", "warning"); } } catch (err) { addToast(getErrorMessage(err) || "Failed to submit authorization code", "error"); } finally { setManualCodeSubmitInProgress(null); } }, [addToast, manualCodeInputs]); const handleCancelLogin = useCallback(async (providerId: string) => { setAuthActionInProgress(providerId); setAuthProviders((prev) => prev.map((provider) => provider.id === providerId ? { ...provider, loginInProgress: false } : provider, )); try { await cancelProviderLogin(providerId); clearAuthLoginUiState(providerId); await loadAuthStatus().catch(() => {}); addToast("Login cancelled", "success"); } catch (err) { addToast(getErrorMessage(err) || "Failed to cancel login", "error"); } finally { setAuthActionInProgress(null); setManualCodeSubmitInProgress((prev) => prev === providerId ? null : prev); if (pollIntervalRef.current) { clearInterval(pollIntervalRef.current); pollIntervalRef.current = null; } } }, [addToast, clearAuthLoginUiState, loadAuthStatus]); const handleLogout = useCallback(async (providerId: string) => { setAuthActionInProgress(providerId); try { await logoutProvider(providerId); await loadAuthStatus(); addToast("Logged out", "success"); } catch (err) { addToast(getErrorMessage(err) || "Logout failed", "error"); } finally { setAuthActionInProgress(null); } }, [addToast, loadAuthStatus]); const handleSaveApiKey = useCallback(async (providerId: string) => { const key = apiKeyInputs[providerId]?.trim(); if (!key) { setApiKeyErrors((prev) => ({ ...prev, [providerId]: "API key is required" })); return; } setAuthActionInProgress(providerId); setApiKeyErrors((prev) => { const next = { ...prev }; delete next[providerId]; return next; }); try { await saveApiKey(providerId, key); setApiKeyInputs((prev) => { const next = { ...prev }; delete next[providerId]; return next; }); await loadAuthStatus(); addToast("API key saved", "success"); scrollSettingsToTop(); } catch (err) { setApiKeyErrors((prev) => ({ ...prev, [providerId]: getErrorMessage(err) || "Failed to save API key" })); } finally { setAuthActionInProgress(null); } }, [apiKeyInputs, addToast, loadAuthStatus, scrollSettingsToTop]); const handleClearApiKey = useCallback(async (providerId: string) => { setAuthActionInProgress(providerId); try { await clearApiKey(providerId); setApiKeyInputs((prev) => { const next = { ...prev }; delete next[providerId]; return next; }); setApiKeyErrors((prev) => { const next = { ...prev }; delete next[providerId]; return next; }); await loadAuthStatus(); addToast("API key cleared", "success"); } catch (err) { addToast(getErrorMessage(err) || "Failed to clear API key", "error"); } finally { setAuthActionInProgress(null); } }, [addToast, loadAuthStatus]); const handleTestProviderNotification = useCallback(async (providerId: "ntfy" | "webhook" | "ntfy-message" | "ntfy-room") => { if (providerId === "ntfy" || providerId === "ntfy-message" || providerId === "ntfy-room") { if (!form.ntfyEnabled || !form.ntfyTopic || !/^[a-zA-Z0-9_-]{1,64}$/.test(form.ntfyTopic)) { return; } } if (providerId === "webhook") { if (!form.webhookEnabled || !form.webhookUrl?.trim()) { return; } try { const parsed = new URL(form.webhookUrl.trim()); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { return; } } catch { return; } } setTestNotificationLoading((prev) => ({ ...prev, [providerId]: true })); setTestNotificationResult((prev) => { const next = { ...prev }; delete next[providerId]; return next; }); try { const config = providerId === "ntfy" ? { ntfyEnabled: form.ntfyEnabled, ntfyTopic: form.ntfyTopic, ...(form.ntfyBaseUrl?.trim() ? { ntfyBaseUrl: form.ntfyBaseUrl.trim() } : {}), ...(form.ntfyAccessToken?.trim() ? { ntfyAccessToken: form.ntfyAccessToken.trim() } : {}), } : providerId === "ntfy-message" ? { messageEventType: "message:agent-to-user" } : providerId === "ntfy-room" ? { messageEventType: "message:room" } : { webhookUrl: form.webhookUrl, webhookFormat: form.webhookFormat || "generic", }; const result = await testNotification( providerId === "ntfy-message" || providerId === "ntfy-room" ? "ntfy" : providerId, config, projectId, ); if (result.success) { const successMessage = providerId === "ntfy" ? "Test notification sent — check your ntfy app!" : providerId === "ntfy-message" ? "Message inbox test sent — check your ntfy inbox for the agent-to-user message." : providerId === "ntfy-room" ? "Room reply test sent — check your ntfy inbox for the room reply." : "Test notification sent — check your webhook endpoint!"; setTestNotificationResult((prev) => ({ ...prev, [providerId]: { status: "success", message: successMessage } })); addToast(successMessage, "success"); } else { const failureMessage = providerId === "ntfy-message" ? "Failed to send message inbox test" : providerId === "ntfy-room" ? "Failed to send room reply test" : "Failed to send test notification"; setTestNotificationResult((prev) => ({ ...prev, [providerId]: { status: "error", message: failureMessage } })); addToast(failureMessage, "error"); } } catch (err) { const failureMessage = getErrorMessage(err) || "Failed to send test notification"; setTestNotificationResult((prev) => ({ ...prev, [providerId]: { status: "error", message: failureMessage } })); addToast(failureMessage, "error"); } finally { setTestNotificationLoading((prev) => ({ ...prev, [providerId]: false })); } }, [ addToast, form.ntfyAccessToken, form.ntfyBaseUrl, form.ntfyEnabled, form.ntfyTopic, form.webhookEnabled, form.webhookFormat, form.webhookUrl, projectId, ]); const handleBackupNow = useCallback(async () => { setBackupLoading(true); try { const result = await createBackup(projectId); if (result.success) { addToast("Backup created successfully", "success"); // Refresh backup list const info = await fetchBackups(projectId); setBackupInfo(info); } else { addToast(result.error || "Failed to create backup", "error"); } } catch (err) { addToast(getErrorMessage(err) || "Failed to create backup", "error"); } finally { setBackupLoading(false); } }, [addToast, projectId]); // Export/Import handlers const handleExport = useCallback(async () => { try { // Default scope based on active section const scope = activeSectionScope === "global" ? "global" : activeSectionScope === "project" ? "project" : "both"; const data = await exportSettings(scope, projectId); // Create and download the JSON file const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); const filename = `fusion-settings-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)}.json`; link.href = url; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); const scopeLabel = scope === "global" ? "global" : scope === "project" ? "project" : "all"; addToast(`Settings exported (${scopeLabel} scope)`, "success"); } catch (err) { addToast(getErrorMessage(err) || "Failed to export settings", "error"); } }, [addToast, activeSectionScope, projectId]); const handleFileSelect = useCallback(async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setImportFile(file); setImportLoading(true); try { const text = await file.text(); const data = JSON.parse(text) as SettingsExportData; setImportPreview(data); setImportDialogOpen(true); } catch (err) { addToast(`Invalid JSON file: ${getErrorMessage(err)}`, "error"); setImportFile(null); } finally { setImportLoading(false); } }, [addToast]); const handleImport = useCallback(async () => { if (!importPreview) return; setImportLoading(true); try { const result = await importSettings(importPreview, { scope: importScope, merge: importMerge }, projectId); if (result.success) { const parts: string[] = []; if (result.globalCount > 0) parts.push(`${result.globalCount} global`); if (result.projectCount > 0) parts.push(`${result.projectCount} project`); addToast(`Imported ${parts.join(", ")} setting(s)`, "success"); setImportDialogOpen(false); setImportPreview(null); setImportFile(null); // Refresh settings to show imported values const refreshed = await fetchSettings(projectId); setForm(refreshed); } else { addToast(result.error || "Import failed", "error"); } } catch (err) { addToast(getErrorMessage(err) || "Failed to import settings", "error"); } finally { setImportLoading(false); } }, [addToast, importPreview, importScope, importMerge, projectId]); const handleToggleFavorite = useCallback(async (provider: string) => { const currentFavorites = favoriteProviders; const isFavorite = currentFavorites.includes(provider); const newFavorites = isFavorite ? currentFavorites.filter((p) => p !== provider) : [provider, ...currentFavorites]; setFavoriteProviders(newFavorites); try { await updateGlobalSettings({ favoriteProviders: newFavorites, favoriteModels }); } catch { setFavoriteProviders(currentFavorites); } }, [favoriteProviders, favoriteModels]); const handleToggleModelFavorite = useCallback(async (modelId: string) => { const currentFavorites = favoriteModels; const isFavorite = currentFavorites.includes(modelId); const newFavorites = isFavorite ? currentFavorites.filter((m) => m !== modelId) : [modelId, ...currentFavorites]; setFavoriteModels(newFavorites); try { await updateGlobalSettings({ favoriteProviders, favoriteModels: newFavorites }); } catch { setFavoriteModels(currentFavorites); } }, [favoriteModels, favoriteProviders]); useEffect(() => { const handleKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; document.addEventListener("keydown", handleKey); return () => document.removeEventListener("keydown", handleKey); }, [onClose]); const overlayDismissProps = useOverlayDismiss(onClose); /** * Lane status types: * - "overridden": Both provider and model keys are explicitly set in project scope * - "inherited": Provider/model keys are not set in project scope (fallback to global) */ type LaneStatus = "overridden" | "inherited"; /** * Model lane keys that can be overridden at the project level. * Each lane has global baseline keys and project override keys. */ interface ModelLane { laneId: string; label: string; globalProviderKey: keyof GlobalSettings; globalModelKey: keyof GlobalSettings; projectProviderKey: keyof Settings; projectModelKey: keyof Settings; helperText: string; fallbackOrder: string; } /** All five model lanes with their global and project override keys */ const MODEL_LANES: ModelLane[] = [ { laneId: "default", label: "Default Model", globalProviderKey: "defaultProvider", globalModelKey: "defaultModelId", projectProviderKey: "defaultProviderOverride", projectModelKey: "defaultModelIdOverride", helperText: "Default AI model used for task execution when no per-task override is set.", fallbackOrder: "Project override → Global default lane → Automatic resolution", }, { laneId: "execution", label: "Execution Model", globalProviderKey: "executionGlobalProvider", globalModelKey: "executionGlobalModelId", projectProviderKey: "executionProvider", projectModelKey: "executionModelId", helperText: "AI model used for task implementation (executor agent).", fallbackOrder: "Project override → Global execution lane → Global default lane → Automatic resolution", }, { laneId: "planning", label: "Planning Model", globalProviderKey: "planningGlobalProvider", globalModelKey: "planningGlobalModelId", projectProviderKey: "planningProvider", projectModelKey: "planningModelId", helperText: "AI model used for task planning.", fallbackOrder: "Project override → Global planning lane → Global default lane → Automatic resolution", }, { laneId: "validator", label: "Reviewer Model", globalProviderKey: "validatorGlobalProvider", globalModelKey: "validatorGlobalModelId", projectProviderKey: "validatorProvider", projectModelKey: "validatorModelId", helperText: "AI model used for code and specification review.", fallbackOrder: "Project override → Global reviewer lane → Global default lane → Automatic resolution", }, { laneId: "summarization", label: "Title and Git Commit Message Summarization Model", globalProviderKey: "titleSummarizerGlobalProvider", globalModelKey: "titleSummarizerGlobalModelId", projectProviderKey: "titleSummarizerProvider", projectModelKey: "titleSummarizerModelId", helperText: "AI model used for auto-generating task titles and merge commit summaries.", fallbackOrder: "Project override → Global summarization lane → Project planning lane → Project default lane → Global default lane → Automatic resolution", }, ]; /** * Compute the status of a model lane from scoped project data. * Returns "overridden" when both project lane keys are explicitly set, * "inherited" when they are absent (fallback to global lane). */ function getLaneStatus(lane: ModelLane): LaneStatus { if (!scopedSettings?.project) return "inherited"; const provider = scopedSettings.project[lane.projectProviderKey as keyof Settings]; const model = scopedSettings.project[lane.projectModelKey as keyof Settings]; return provider !== undefined || model !== undefined ? "overridden" : "inherited"; } /** * Compute the display value for a model lane dropdown. * Returns the provider/model pair when explicitly set, or empty string for inherited. */ function getLaneValue(lane: ModelLane): string { const provider = form[lane.projectProviderKey as keyof Settings] as string | undefined; const model = form[lane.projectModelKey as keyof Settings] as string | undefined; if (provider && model) { return `${provider}/${model}`; } return ""; } /** * Update a model lane's provider and model values in the form. */ function updateLaneValue(lane: ModelLane, value: string): void { if (!value) { // Clearing the dropdown - check if this is an inherited lane const status = getLaneStatus(lane); if (status === "inherited") { // Don't write anything to form for inherited lanes return; } // For overridden lanes, setting to undefined clears the override (null-as-delete) setForm((f) => ({ ...f, [lane.projectProviderKey]: undefined, [lane.projectModelKey]: undefined, })); } else { const slashIdx = value.indexOf("/"); setForm((f) => ({ ...f, [lane.projectProviderKey]: value.slice(0, slashIdx), [lane.projectModelKey]: value.slice(slashIdx + 1), })); } } /** * Reset a model lane back to inherited state (null-as-delete for project override). */ function resetLaneValue(lane: ModelLane): void { const status = getLaneStatus(lane); if (status === "inherited") return; // Nothing to reset // Set to undefined to trigger null-as-delete on save setForm((f) => ({ ...f, [lane.projectProviderKey]: undefined, [lane.projectModelKey]: undefined, })); } const openOverlapPathPicker = useCallback((index: number) => { setOverlapPathPickerIndex(index); setOverlapPathPickerPath("."); }, [setOverlapPathPickerPath]); const closeOverlapPathPicker = useCallback(() => { setOverlapPathPickerIndex(null); }, []); const selectOverlapIgnorePath = useCallback((path: string) => { if (overlapPathPickerIndex === null) return; setForm((f) => { const currentPaths = f.overlapIgnorePaths && f.overlapIgnorePaths.length > 0 ? [...f.overlapIgnorePaths] : [""]; currentPaths[overlapPathPickerIndex] = path; return { ...f, overlapIgnorePaths: currentPaths }; }); closeOverlapPathPicker(); }, [overlapPathPickerIndex, closeOverlapPathPicker]); const handleSelectCurrentDirectoryForOverlapIgnore = useCallback(() => { if (overlapPathPickerCurrentPath === ".") { return; } const directoryPath = overlapPathPickerCurrentPath.endsWith("/") ? overlapPathPickerCurrentPath : `${overlapPathPickerCurrentPath}/`; selectOverlapIgnorePath(directoryPath); }, [overlapPathPickerCurrentPath, selectOverlapIgnorePath]); const handleOverlapPathPickerOverlayClick = useCallback((event: MouseEvent) => { if (event.target === event.currentTarget) { closeOverlapPathPicker(); } }, [closeOverlapPathPicker]); const openWorktreesDirPicker = useCallback(() => { setWorktreesDirPickerPath("."); setWorktreesDirPickerOpen(true); }, [setWorktreesDirPickerPath]); const closeWorktreesDirPicker = useCallback(() => { setWorktreesDirPickerOpen(false); }, []); const selectWorktreesDirFromPicker = useCallback((path: string) => { const normalizedPath = path.endsWith("/") ? path : `${path}/`; setForm((f) => ({ ...f, worktreesDir: normalizedPath })); closeWorktreesDirPicker(); }, [closeWorktreesDirPicker]); const selectCurrentWorktreesDir = useCallback(() => { const normalizedPath = worktreesDirPickerCurrentPath === "." ? "./" : (worktreesDirPickerCurrentPath.endsWith("/") ? worktreesDirPickerCurrentPath : `${worktreesDirPickerCurrentPath}/`); setForm((f) => ({ ...f, worktreesDir: normalizedPath })); closeWorktreesDirPicker(); }, [worktreesDirPickerCurrentPath, closeWorktreesDirPicker]); const handleWorktreesDirPickerOverlayClick = useCallback((event: MouseEvent) => { if (event.target === event.currentTarget) { closeWorktreesDirPicker(); } }, [closeWorktreesDirPicker]); const handleOverlapIgnorePathChange = useCallback((index: number, value: string) => { setForm((f) => { const currentPaths = f.overlapIgnorePaths && f.overlapIgnorePaths.length > 0 ? [...f.overlapIgnorePaths] : [""]; currentPaths[index] = value; return { ...f, overlapIgnorePaths: currentPaths }; }); }, []); const handleRemoveOverlapIgnorePath = useCallback((index: number) => { setForm((f) => { const currentPaths = f.overlapIgnorePaths && f.overlapIgnorePaths.length > 0 ? [...f.overlapIgnorePaths] : [""]; const nextPaths = currentPaths.filter((_, i) => i !== index); return { ...f, overlapIgnorePaths: nextPaths.length > 0 ? nextPaths : [] }; }); if (overlapPathPickerIndex === index) { closeOverlapPathPicker(); return; } if (overlapPathPickerIndex !== null && overlapPathPickerIndex > index) { setOverlapPathPickerIndex(overlapPathPickerIndex - 1); } }, [overlapPathPickerIndex, closeOverlapPathPicker]); const handleAddOverlapIgnorePath = useCallback(() => { setForm((f) => { const currentPaths = f.overlapIgnorePaths && f.overlapIgnorePaths.length > 0 ? f.overlapIgnorePaths : [""]; return { ...f, overlapIgnorePaths: [...currentPaths, ""] }; }); }, []); const handleSave = useCallback(async () => { if (prefixError || presetDraft) return; const limits = form.researchSettings?.limits; if (limits?.maxConcurrentRuns !== undefined && (!Number.isFinite(limits.maxConcurrentRuns) || limits.maxConcurrentRuns < 1)) { setResearchLimitError("Research max concurrent runs must be at least 1."); return; } if (limits?.maxSourcesPerRun !== undefined && (!Number.isFinite(limits.maxSourcesPerRun) || limits.maxSourcesPerRun < 1)) { setResearchLimitError("Research max sources per run must be at least 1."); return; } if (limits?.maxDurationMs !== undefined && (!Number.isFinite(limits.maxDurationMs) || limits.maxDurationMs < 1000)) { setResearchLimitError("Research max duration must be at least 1000 ms."); return; } if (limits?.requestTimeoutMs !== undefined && (!Number.isFinite(limits.requestTimeoutMs) || limits.requestTimeoutMs < 1000)) { setResearchLimitError("Research request timeout must be at least 1000 ms."); return; } setResearchLimitError(null); try { const payload = { ...form, worktreeInitCommand: form.worktreeInitCommand?.trim() || undefined, worktreesDir: form.worktreesDir?.trim() || undefined, worktrunk: { enabled: worktrunkInstallVerified && form.worktrunk?.enabled === true, binaryPath: form.worktrunk?.binaryPath?.trim() || undefined, onFailure: form.worktrunk?.onFailure ?? "fail", }, taskPrefix: form.taskPrefix?.trim() || undefined, githubTrackingDefaultRepo: form.githubTrackingDefaultRepo?.trim() || undefined, githubAuthToken: form.githubAuthToken?.trim() || undefined, overlapIgnorePaths: (form.overlapIgnorePaths ?? []).map((path) => path.trim()).filter((path) => path.length > 0), experimentalFeatures: normalizeExperimentalFeaturesForSave(form.experimentalFeatures), }; // Always save both global and project settings with strict scope separation. // // SCOPE RULES: // - Global lane keys (executionGlobalProvider, planningGlobalProvider, etc.) // go to updateGlobalSettings // - Project override lane keys (executionProvider, planningProvider, etc.) // go to updateSettings ONLY when explicitly changed from initial state // - Inherited project lanes (unset in project scope) are NOT written to project payload // - Resetting a project lane sends null to delete it from project scope const globalPatch: Partial = {}; for (const [key, value] of Object.entries(payload)) { if (key === "githubTrackingDefaultRepo" && activeSection !== "global-general") { continue; } if (key === "persistAgentThinkingLog") { continue; } if (isGlobalSettingsKey(key)) { // Implement null-as-delete semantics for global settings: // - undefined values are dropped during JSON serialization // - To explicitly clear a field, send null instead // - We detect explicit clears by comparing with initial values: // if current value is undefined AND initial was defined, use null const initialValue = initialValues?.[key as keyof GlobalSettings]; if (value === undefined && initialValue !== undefined) { (globalPatch as Record)[key] = null; // null means "explicitly clear" } else { (globalPatch as Record)[key] = value; } } } // Project settings: Only include keys that were explicitly changed. // This prevents inherited effective values from being persisted as explicit overrides. const projectPatch: Partial = {}; for (const [key, value] of Object.entries(payload)) { if (key === "githubTokenConfigured" || key === "prAuthAvailable") continue; // server-only fields if (key === "githubTrackingDefaultRepo" && activeSection === "global-general") continue; if (!isProjectSettingsKey(key)) continue; // Get the initial project-scoped value (null if not set) const initialProjectValue = initialScopedValues?.project?.[key as keyof Settings]; // Check if this value is a model lane key that tracks inheritance const isModelLaneKey = [ "planningProvider", "planningModelId", "validatorProvider", "validatorModelId", "executionProvider", "executionModelId", "titleSummarizerProvider", "titleSummarizerModelId", "defaultProviderOverride", "defaultModelIdOverride", "planningFallbackProvider", "planningFallbackModelId", "validatorFallbackProvider", "validatorFallbackModelId", "titleSummarizerFallbackProvider", "titleSummarizerFallbackModelId", ].includes(key); if (isModelLaneKey) { // For model lanes: only write if explicitly changed from initial project state if (value !== initialProjectValue) { // Detect explicit reset: current is undefined/null but initial was set if ((value === undefined || value === null) && initialProjectValue !== undefined && initialProjectValue !== null) { (projectPatch as Record)[key] = null; // null-as-delete } else if (value !== undefined) { (projectPatch as Record)[key] = value; } } } else { // For non-model settings: existing behavior (projectPatch as Record)[key] = value; } } // Save both scopes in parallel if they have changes. // Note: themeMode/colorTheme may also be write-through via useTheme callbacks // in the Appearance section; duplicate global writes are intentional/idempotent, // while this save path persists the full settings form in one action. await Promise.all([ Object.keys(globalPatch).length > 0 ? updateGlobalSettings(globalPatch) : Promise.resolve(), Object.keys(projectPatch).length > 0 ? updateSettings(projectPatch, projectId) : Promise.resolve(), globalMaxConcurrent !== initialGlobalMaxConcurrentRef.current ? updateGlobalConcurrency({ globalMaxConcurrent: globalMaxConcurrent ?? 4 }) : Promise.resolve(), ]); addToast("Settings saved", "success"); onClose(); } catch (err) { addToast(getErrorMessage(err), "error"); } }, [form, globalMaxConcurrent, prefixError, presetDraft, initialValues, initialScopedValues, onClose, addToast, projectId, activeSection]); const handleSaveMemory = useCallback(async () => { try { await saveMemoryFile(selectedMemoryPath, memoryContent, projectId); setMemoryDirty(false); addToast("Memory saved", "success"); } catch (err) { addToast(getErrorMessage(err) || "Failed to save memory", "error"); } }, [selectedMemoryPath, memoryContent, projectId, addToast]); const handleCompactMemory = useCallback(async () => { setMemoryCompactLoading(true); try { const { path, content } = await compactMemory(selectedMemoryPath, projectId); const nextPath = path ?? selectedMemoryPath; if (selectedMemoryPath !== nextPath) { skipNextMemoryReloadRef.current = true; } setSelectedMemoryPath(nextPath); setMemoryContent(content); setMemoryDirty(false); const { files } = await fetchMemoryFiles(projectId); setMemoryFiles(files); addToast("Memory file compacted", "success"); } catch (err) { addToast(getErrorMessage(err) || "Failed to compact memory", "error"); } finally { setMemoryCompactLoading(false); } }, [selectedMemoryPath, projectId, addToast]); const handleTestMemoryRetrieval = useCallback(async () => { setMemoryTestLoading(true); setMemoryTestResult(null); try { const result = await testMemoryRetrieval(memoryTestQuery, projectId); setMemoryTestResult(result); addToast( result.qmdAvailable ? "Memory retrieval test complete" : "qmd is not installed; local fallback was used", result.qmdAvailable ? "success" : "warning", ); } catch (err) { addToast(getErrorMessage(err) || "Failed to test memory retrieval", "error"); } finally { setMemoryTestLoading(false); } }, [memoryTestQuery, projectId, addToast]); const handleDreamNow = useCallback(async () => { setDreamRunning(true); try { await triggerMemoryDreams(projectId); addToast("Dream processing completed", "success"); } catch (error) { addToast(error instanceof Error ? error.message : "Failed to run dream processing", "error"); } finally { setDreamRunning(false); } }, [projectId, addToast]); const handleInstallQmd = useCallback(async () => { setQmdInstallLoading(true); try { const result = await installQmd(projectId); await refreshMemoryBackend(); addToast( result.qmdAvailable ? "qmd installed successfully" : "qmd install finished, but qmd is still unavailable", result.qmdAvailable ? "success" : "warning", ); } catch (err) { addToast(getErrorMessage(err) || "Failed to install qmd", "error"); } finally { setQmdInstallLoading(false); } }, [projectId, refreshMemoryBackend, addToast]); const savePresetDraft = () => { if (!presetDraft) return; const nextName = presetDraft.name.trim(); if (!nextName) { addToast("Preset name is required", "error"); return; } const presets = form.modelPresets || []; // For new presets, generate unique ID from name; for edits, keep existing ID let nextId: string; if (editingPresetId) { nextId = editingPresetId; } else { nextId = generateUniquePresetId(nextName, presets); } const normalizedDraft: ModelPreset = { id: nextId, name: nextName, executorProvider: presetDraft.executorProvider, executorModelId: presetDraft.executorModelId, validatorProvider: presetDraft.validatorProvider, validatorModelId: presetDraft.validatorModelId, }; setForm((current) => { const existing = current.modelPresets || []; const nextPresets = editingPresetId ? existing.map((preset) => (preset.id === editingPresetId ? normalizedDraft : preset)) : [...existing, normalizedDraft]; return { ...current, modelPresets: nextPresets }; }); setEditingPresetId(null); setPresetDraft(null); }; const runRemoteAction = useCallback(async (label: string, action: () => Promise) => { setRemoteBusyAction(label); try { await action(); await loadRemoteData(); } catch (err) { addToast(getErrorMessage(err) || `Failed to ${label}`, "error"); } finally { setRemoteBusyAction(null); } }, [addToast, loadRemoteData]); const cloudflaredManualInstallCommand = useCallback(() => { if (typeof navigator !== "undefined" && navigator.userAgent.includes("Windows")) { return "winget install Cloudflare.cloudflared"; } const platform = typeof navigator !== "undefined" ? navigator.platform : ""; const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : ""; const isMac = /(Mac|iPhone|iPad|iPod)/i.test(platform); const isArm = /(arm64|aarch64)/i.test(`${platform} ${userAgent}`); if (isMac) { return "brew install cloudflared"; } const linuxArch = isArm ? "arm64" : "amd64"; return `curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${linuxArch} && chmod +x /tmp/cloudflared && sudo mv /tmp/cloudflared /usr/local/bin/cloudflared # If sudo is unavailable, use: mkdir -p ~/.local/bin && mv /tmp/cloudflared ~/.local/bin/cloudflared`; }, []); const cloudflaredMacFallbackCommand = useCallback(() => { if (typeof navigator === "undefined") { return null; } if (!/(Mac|iPhone|iPad|iPod)/i.test(navigator.platform)) { return null; } const arch = /(arm64|aarch64)/i.test(`${navigator.platform} ${navigator.userAgent}`) ? "arm64" : "amd64"; return `curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${arch} && chmod +x /tmp/cloudflared && sudo mv /tmp/cloudflared /usr/local/bin/cloudflared`; }, []); const handleInstallCloudflared = useCallback(async () => { setCloudflaredInstalling(true); setCloudflaredInstallError(null); try { const result = await installCloudflared(projectId); if (!result.success) { setCloudflaredInstallError(result.error ?? "Installation failed"); return; } const status = await fetchRemoteStatus(projectId); setRemoteStatus(status); addToast("cloudflared installed successfully", "success"); } catch (err) { setCloudflaredInstallError(err instanceof Error ? err.message : "Installation failed"); } finally { setCloudflaredInstalling(false); } }, [addToast, projectId]); /** Render a scope indicator banner for the current section with theme-aware Lucide icons */ const renderScopeBanner = () => { if (activeSectionScope === "global") { return (
These settings are shared across all your Fusion projects.
); } if (activeSectionScope === "project") { return (
These settings only affect this project.
); } return null; }; const renderSectionFields = () => { switch (activeSection) { case "general": return ( <> {renderScopeBanner()}

General

{ const val = e.target.value; setForm((f) => ({ ...f, taskPrefix: val || undefined })); if (val && !/^[A-Z]{1,10}$/.test(val)) { setPrefixError("Prefix must be 1–10 uppercase letters"); } else { setPrefixError(null); } }} /> {prefixError && {prefixError}} {!prefixError && Prefix for new task IDs (e.g. KB, PROJ)}
When enabled, AI-generated task specifications require manual approval before moving to Todo
When enabled (default), Fusion spawns short-lived executor-FN-XXXX agents to run each task. When disabled, only permanent agents execute tasks and the scheduler auto-assigns work using the agent reporting chain. Tasks with no eligible permanent agent stay queued.
Controls how future task specs handle release-note artifacts at completion. Use changeset mode for repositories that follow .changeset workflows, or changelog mode when contributors should update an existing changelog file.
Show the floating chat button in the dashboard. Chat is still accessible from the Chat tab in the mobile navigation.

Chat history

Delete chat sessions and rooms that have been idle for this many days. Default: Off.
Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting.

Chat Rooms

setForm((f) => ({ ...f, chatRoomRecentVerbatimMessages: Number(e.target.value) || undefined })) } /> Number of most-recent chat-room messages kept verbatim in the responder transcript. Older messages are compacted into a summary block. Default: 12.
setForm((f) => ({ ...f, chatRoomCompactionFetchLimit: Number(e.target.value) || undefined })) } /> Upper bound on messages fetched from the room store for compaction consideration. Default: 80.
setForm((f) => ({ ...f, chatRoomSummaryMaxChars: Number(e.target.value) || undefined })) } /> Hard cap on the synthesized "Earlier room context" summary block. Default: 1500.

Capacity Risk Banner

Warn on the board when todo work exceeds the threshold and no idle agents are available.
setForm((f) => ({ ...f, capacityRiskTodoThreshold: e.target.value === "" ? 0 : Math.max(0, Number.parseInt(e.target.value, 10) || 0), })) } /> Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled.

GitHub Tracking

Controls whether newly created tasks have GitHub issue tracking enabled by default. Individual tasks can still override this from the task detail modal. Tracking issues use this task's title. If a task has no title yet, Fusion can summarize its description using the title summarization model in Project Models. {!form.autoSummarizeTitles && !form.useAiMergeCommitSummary && !form.githubTrackingEnabledByDefault ? " Enable summarization in Project Models to configure that model." : ""}
setForm((f) => ({ ...f, githubTrackingDefaultRepo: nextValue || undefined })) } /> Default repo used when creating GitHub issues for tracked tasks. Falls back to the global default if blank.
When enabled, Fusion checks open and closed issues in the target repo for likely duplicates (using File Scope paths and key symptoms) before creating a new tracking issue. Uncheck to always create a new issue.
); case "global-general": return ( <> {renderScopeBanner()}

General

Once you click the Star button it's hidden automatically. Uncheck this to keep it hidden even before clicking.
setForm((f) => ({ ...f, githubTrackingDefaultRepo: nextValue || undefined })) } /> Projects inherit this value when they do not set a project default tracking repo.
When disabled, tool rows are still logged but detailed tool payloads are omitted. Very large tool payloads may still be clipped even when this stays enabled.
Save AI thinking logs
Leave both thinking toggles off to keep the original default behavior. This only controls persisted thinking rows and does not affect assistant text or tool rows.
When enabled, the dashboard probes for a globally-installed{" "} fn / fusion CLI by spawning{" "} <bin> --version. Disable this if your local dev process is the source of truth and you don't want any outdated globally-installed binary executed during the probe.

Updates

When enabled, Fusion checks npm for new versions of{" "} @runfusion/fusion and shows update notices in the CLI and dashboard. Cadence is governed by the frequency below.
Controls how often the dashboard re-fetches the npm registry. Use the version + refresh control in the header to trigger an immediate check at any time.
When enabled (default), the dashboard automatically reloads when it detects a new build version — either from server rebuilds or service worker updates. Disable this to stay on the current version until you manually refresh.
); case "global-models": { const selectedValue = form.defaultProvider && form.defaultModelId ? `${form.defaultProvider}/${form.defaultModelId}` : ""; const globalModelLanes = MODEL_LANES.filter( (lane) => lane.laneId !== "default", ); return ( <> {renderScopeBanner()} {/* --- Default Model --- */}

Default Model

{modelsLoading ? (
Loading available models…
) : availableModels.length === 0 ? (
No models available. Configure authentication first.
) : ( <>
{ if (!val) { setForm((f) => ({ ...f, defaultProvider: undefined, defaultModelId: undefined })); } else { const slashIdx = val.indexOf("/"); setForm((f) => ({ ...f, defaultProvider: val.slice(0, slashIdx), defaultModelId: val.slice(slashIdx + 1), })); } }} placeholder="Use default" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> Default AI model used for task execution when no per-task override is set. "Use default" lets the engine choose automatically.
{ if (!val) { setForm((f) => ({ ...f, fallbackProvider: undefined, fallbackModelId: undefined })); } else { const slashIdx = val.indexOf("/"); setForm((f) => ({ ...f, fallbackProvider: val.slice(0, slashIdx), fallbackModelId: val.slice(slashIdx + 1), })); } }} placeholder="No fallback" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> Used automatically if the primary default model hits a retryable provider error like rate limiting or overload.
)} {(() => { const selectedModel = availableModels.find( (m) => m.provider === form.defaultProvider && m.id === form.defaultModelId, ); if (selectedModel && !selectedModel.reasoning) return null; return (
Controls how much reasoning effort the AI model uses. Higher levels produce better results but cost more.
); })()} {availableModels.length > 0 && ( <>

Model Lanes

Global baseline models for each AI role. Project settings can override these per-project.

{globalModelLanes.map((lane) => { const provider = form[lane.globalProviderKey as keyof Settings] as string | undefined; const model = form[lane.globalModelKey as keyof Settings] as string | undefined; const value = provider && model ? `${provider}/${model}` : ""; return (
{ if (!selected) { setForm((f) => ({ ...f, [lane.globalProviderKey]: undefined, [lane.globalModelKey]: undefined, })); return; } const slashIdx = selected.indexOf("/"); setForm((f) => ({ ...f, [lane.globalProviderKey]: selected.slice(0, slashIdx), [lane.globalModelKey]: selected.slice(slashIdx + 1), })); }} placeholder="Use default" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> {lane.helperText}
); })} )} {/* --- Startup Model Sync --- */}

Startup Model Sync

When enabled, startup fetches the latest available models from the OpenRouter API so model pickers always include the newest catalog.
When enabled, startup refreshes models through the local opencode models opencode --refresh flow and publishes them under the opencode-go provider in model pickers.
OpenRouter advanced
setForm((f) => ({ ...f, openrouterAppAttribution: { ...(f.openrouterAppAttribution || {}), referer: e.target.value, }, }))} /> Leave empty to omit this header. Default: https://runfusion.ai.
setForm((f) => ({ ...f, openrouterAppAttribution: { ...(f.openrouterAppAttribution || {}), title: e.target.value, }, }))} /> Leave empty to omit this header. Default: Fusion.
{ const parsed = fromCommaSeparatedInput(e.target.value); setForm((f) => ({ ...f, openrouterModelFilters: { ...(f.openrouterModelFilters || {}), supported_parameters: parsed.length > 0 ? parsed : undefined, }, })); }} /> Comma-separated values sent to OpenRouter model sync.
{ const parsed = fromCommaSeparatedInput(e.target.value); setForm((f) => ({ ...f, openrouterModelFilters: { ...(f.openrouterModelFilters || {}), output_modalities: parsed.length > 0 ? parsed : undefined, }, })); }} /> Comma-separated values sent to OpenRouter model sync.
{ const parsed = fromCommaSeparatedInput(e.target.value); setForm((f) => ({ ...f, openrouterProviderPreferences: { ...(f.openrouterProviderPreferences || {}), order: parsed.length > 0 ? parsed : undefined, }, })); }} />
{ const parsed = fromCommaSeparatedInput(e.target.value); setForm((f) => ({ ...f, openrouterProviderPreferences: { ...(f.openrouterProviderPreferences || {}), ignore: parsed.length > 0 ? parsed : undefined, }, })); }} />
{ const parsed = fromCommaSeparatedInput(e.target.value); setForm((f) => ({ ...f, openrouterProviderPreferences: { ...(f.openrouterProviderPreferences || {}), only: parsed.length > 0 ? parsed : undefined, }, })); }} />
); } case "project-models": { const presets = form.modelPresets || []; const presetOptions = presets.map((preset) => ({ id: preset.id, name: preset.name })); const inUsePresetIds = new Set(Object.values(form.defaultPresetBySize || {}).filter(Boolean)); // Filter model lanes to show in project scope. // The "summarization" lane is intentionally excluded here — it has a // dedicated picker further down ("AI Title and Git Commit Message // Summarization") so the project tab doesn't surface the same model // setting twice. const projectModelLanes = MODEL_LANES.filter( (lane) => lane.laneId === "default" || lane.laneId === "execution" || lane.laneId === "planning" || lane.laneId === "validator", ); const resolvedPlanningModel = resolvePlanningSettingsModel(form); const resolvedDefaultModel = resolveProjectDefaultModel(form); const resolvedTitleSummarizerModel = resolveTitleSummarizerSettingsModel(form); const getProjectLaneLabel = (lane: ModelLane) => lane.laneId === "default" ? "Project Default Model" : lane.label; const getProjectLaneHelperText = (lane: ModelLane) => lane.laneId === "default" ? "Project-wide default AI model used when no more specific task or project lane override is set." : lane.helperText; return ( <> {renderScopeBanner()} {/* --- Token Cap --- */}

Token Cap

{ const val = e.target.value; setForm((f) => ({ ...f, tokenCap: val ? parseInt(val, 10) : null } as SettingsFormState)); }} /> {form.tokenCap != null && ( )}
Automatically compact context when approaching this token count. Leave empty for no cap (compact only on overflow errors). Set a number to proactively compact when reaching this token count.
{/* --- Project Model Lanes --- */}

Model Lanes

Override global model settings at the project level. Each lane controls a specific AI usage context. Unset lanes inherit from the corresponding global lane. The Project Default Model is the fallback for this project when a more specific lane is unset.

{modelsLoading ? (
Loading available models…
) : availableModels.length === 0 ? (
No models available. Configure authentication first.
) : ( <> {projectModelLanes.map((lane) => { const status = getLaneStatus(lane); const value = getLaneValue(lane); const isOverridden = status === "overridden"; const laneLabel = getProjectLaneLabel(lane); return (
{isOverridden ? "Override (Project)" : "Inherited (Global)"}
updateLaneValue(lane, val)} placeholder={lane.laneId === "default" ? "Use global default" : "Use global"} favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} />
{isOverridden && ( )}
{getProjectLaneHelperText(lane)} Falls back to: {lane.fallbackOrder}.
); })} )} {/* --- Fallback Models --- */}

Fallback Models

{modelsLoading ? (
Loading available models…
) : availableModels.length === 0 ? (
No models available.
) : ( <>
{ if (!val) { setForm((f) => ({ ...f, planningFallbackProvider: undefined, planningFallbackModelId: undefined })); } else { const slashIdx = val.indexOf("/"); setForm((f) => ({ ...f, planningFallbackProvider: val.slice(0, slashIdx), planningFallbackModelId: val.slice(slashIdx + 1), })); } }} placeholder="Use global fallback" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> Used if the planning model fails due to rate limits or provider overload. Defaults to the global fallback model.
{ if (!val) { setForm((f) => ({ ...f, validatorFallbackProvider: undefined, validatorFallbackModelId: undefined })); } else { const slashIdx = val.indexOf("/"); setForm((f) => ({ ...f, validatorFallbackProvider: val.slice(0, slashIdx), validatorFallbackModelId: val.slice(slashIdx + 1), })); } }} placeholder="Use global fallback" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> Used if the reviewer model fails due to rate limits or provider overload. Defaults to the global fallback model.
)} {/* --- Model Presets --- */}

Model Presets

{presets.length === 0 ? (
No presets configured yet.
) : (
{presets.map((preset) => { const selection = applyPresetToSelection(preset); const summary = `${selection.executorValue || "default"} / ${selection.validatorValue || "default"}`; return (
{preset.name} {summary}
); })}
)} {!presetDraft ? (
) : null}
{presetDraft ? (
{ const name = e.target.value; setPresetDraft((current) => current ? { ...current, name } : current); }} />
{availableModels.length === 0 ? ( No models available. Configure authentication first. ) : ( <>
{ if (!val) { setPresetDraft((current) => current ? { ...current, executorProvider: undefined, executorModelId: undefined } : current); return; } const slashIdx = val.indexOf("/"); setPresetDraft((current) => current ? { ...current, executorProvider: val.slice(0, slashIdx), executorModelId: val.slice(slashIdx + 1), } : current); }} placeholder="Use default" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} />
{ if (!val) { setPresetDraft((current) => current ? { ...current, validatorProvider: undefined, validatorModelId: undefined } : current); return; } const slashIdx = val.indexOf("/"); setPresetDraft((current) => current ? { ...current, validatorProvider: val.slice(0, slashIdx), validatorModelId: val.slice(slashIdx + 1), } : current); }} placeholder="Use default" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} />
)}
) : null}
{form.autoSelectModelPreset ? (
{(["S", "M", "L"] as const).map((sizeKey) => (
))}
) : null} {/* --- AI Title and Git Commit Message Summarization --- */}

AI Title and Git Commit Message Summarization

Configures the model used for two short-summary jobs: auto-generating task titles from long descriptions, and generating merge commit summaries from step commits and diff stats.

When enabled, tasks created without a title but with descriptions over 200 characters will automatically get an AI-generated title (max 60 characters). The same model is also used to generate fallback merge commit message bodies when the branch's commit log is empty (e.g. squash merges with no unique commits), and GitHub tracking issue titles when a tracked task has no title yet.
When enabled, merge commit messages will include an AI-generated summary of the changes instead of just listing step commit subjects. Uses the title summarization model.
{(form.autoSummarizeTitles || form.useAiMergeCommitSummary || form.githubTrackingEnabledByDefault || false) && ( <>
{modelsLoading ? ( Loading available models... ) : availableModels.length === 0 ? ( No models available. Configure authentication first. ) : ( { if (!val) { setForm((f) => ({ ...f, titleSummarizerProvider: undefined, titleSummarizerModelId: undefined, })); return; } const slashIdx = val.indexOf("/"); setForm((f) => ({ ...f, titleSummarizerProvider: val.slice(0, slashIdx), titleSummarizerModelId: val.slice(slashIdx + 1), })); }} placeholder="Use fallback model" favoriteProviders={favoriteProviders} onToggleFavorite={handleToggleFavorite} favoriteModels={favoriteModels} onToggleModelFavorite={handleToggleModelFavorite} /> )} Also used to summarize task descriptions into GitHub tracking issue titles when a task has no title yet. {form.titleSummarizerProvider && form.titleSummarizerModelId ? "Using explicitly configured model" : resolvedTitleSummarizerModel.provider && resolvedTitleSummarizerModel.modelId ? resolvedTitleSummarizerModel.provider === resolvedPlanningModel.provider && resolvedTitleSummarizerModel.modelId === resolvedPlanningModel.modelId ? "(using planning model)" : resolvedTitleSummarizerModel.provider === resolvedDefaultModel.provider && resolvedTitleSummarizerModel.modelId === resolvedDefaultModel.modelId ? form.defaultProviderOverride && form.defaultModelIdOverride ? "(using project default model)" : "(using global default model)" : "(using global summarization model)" : "(using automatic model selection)"}
)} ); } case "appearance": return ( <> {renderScopeBanner()}

Appearance

{ setForm((f) => ({ ...f, themeMode: mode })); onThemeModeChange?.(mode); }} onColorThemeChange={(theme) => { setForm((f) => ({ ...f, colorTheme: theme })); onColorThemeChange?.(theme); }} onDashboardFontScaleChange={(scalePct) => { setForm((f) => ({ ...f, dashboardFontScalePct: scalePct })); onDashboardFontScaleChange?.(scalePct); }} />
Suppress the “needs your input” banner that appears when AI sessions are awaiting input or have failed.
); case "scheduling": return ( <> {renderScopeBanner()}

Scheduling

{ const val = e.target.value; globalConcurrencyDirtyRef.current = true; setGlobalMaxConcurrent(val === "" ? undefined : Number(val)); }} /> Maximum concurrent agents across all projects
{ const val = e.target.value; setForm((f) => ({ ...f, maxConcurrent: val === "" ? undefined : Number(val) } as SettingsFormState)); }} />
{ const val = e.target.value; setForm((f) => ({ ...f, maxTriageConcurrent: val === "" ? undefined : Number(val) } as SettingsFormState)); }} /> Maximum concurrent planning agents
{ const val = e.target.value; setForm((f) => ({ ...f, pollIntervalMs: val === "" ? undefined : Number(val) } as SettingsFormState)); }} />
Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.
{ const val = e.target.value; const num = Number(val); setForm((f) => ({ ...f, taskStuckTimeoutMs: val && num > 0 ? num * 60000 : undefined })); }} /> Timeout in minutes for detecting stuck tasks. When a task's agent session shows no activity for longer than this duration, the task is terminated and retried. Leave empty to disable. Suggested: 10.
{ const val = e.target.value; const num = Number(val); setForm((f) => ({ ...f, staleHighFanoutBlockerAgeThresholdMs: val && num > 0 ? num * 3600000 : undefined, })); }} /> Escalate high fan-out blockers only after they remain in in-progress or in-review for this many hours (age source: columnMovedAt, fallback updatedAt). Default: 2 hours.
When the stuck detector kills and re-queues a task, keep completed step statuses so the agent can resume from where it left off. Disable to reset every step to pending on each stuck retry. Default: enabled.
When enabled, tasks with stale plans (PROMPT.md older than the threshold) are automatically sent back to planning for replanning
{ const val = e.target.value; const num = Number(val); setForm((f) => ({ ...f, specStalenessMaxAgeMs: val !== "" ? num * 3600000 : undefined })); }} disabled={!form.specStalenessEnabled} /> Maximum age in hours before a plan is considered stale. Default: 6 hours.
Completed tasks older than the threshold are moved out of the active task database.
{ const val = e.target.value; const num = Number(val); setForm((f) => ({ ...f, autoArchiveDoneAfterMs: val === "" ? undefined : num * MS_PER_DAY, })); }} disabled={form.autoArchiveDoneTasksEnabled === false} /> Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours).
Compact mode keeps archive size low while preserving recent agent activity for context.
{ const val = e.target.value; const num = Number(val); setForm((f) => ({ ...f, maxStuckKills: val && num > 0 ? num : undefined })); }} /> Maximum stuck-detector retries before a task is marked failed. Default: 6.
When enabled, tasks that modify the same files are queued serially to avoid merge conflicts
Optional file or directory paths to ignore when overlap serialization is enabled. Paths are project-relative (for example docs/ or generated/*).
{(form.overlapIgnorePaths && form.overlapIgnorePaths.length > 0 ? form.overlapIgnorePaths : [""]).map((path, index) => (
handleOverlapIgnorePathChange(index, e.target.value)} />
))}
Step Execution
Run each task step in its own fresh agent session for better isolation and error recovery. Failed steps can be retried individually.
{ const val = e.target.value; setForm((f) => ({ ...f, maxParallelSteps: val === "" ? undefined : Number(val) })); }} disabled={!form.runStepsInNewSessions} /> Maximum number of steps to run in parallel when file scopes don't overlap (1-4)
); case "scheduled-evals": { const evalSettings = form.evalSettings ?? {}; const isScheduledEvalEnabled = evalSettings.enabled ?? false; return ( <> {renderScopeBanner()}

Scheduled Evals

setForm((current) => ({ ...current, evalSettings: { ...(current.evalSettings ?? {}), intervalMs: event.target.value === "" ? undefined : Number(event.target.value), }, })) } />
setForm((current) => ({ ...current, evalSettings: { ...(current.evalSettings ?? {}), evaluatorProvider: event.target.value.trim() === "" ? undefined : event.target.value, }, })) } placeholder="openai" />
setForm((current) => ({ ...current, evalSettings: { ...(current.evalSettings ?? {}), evaluatorModelId: event.target.value.trim() === "" ? undefined : event.target.value, }, })) } placeholder="gpt-5" /> Leave provider and model blank to inherit the project validator lane model settings.
setForm((current) => ({ ...current, evalSettings: { ...(current.evalSettings ?? {}), retentionDays: event.target.value === "" ? undefined : Number(event.target.value), }, })) } />
); } case "node-routing": return ( <> {renderScopeBanner()}

Node Routing

Configure how tasks are routed to execution nodes.

These settings apply at the project level.

{(() => { const selectedNode = nodes.find((node) => node.id === form.defaultNodeId); if (!selectedNode) return null; return (
Selected node:
); })()} Used when a task has no node override. Node status is shown for safer routing selection.
); case "worktrees": return ( <> {renderScopeBanner()}

Worktrees

{ const val = e.target.value; setForm((f) => ({ ...f, maxWorktrees: val === "" ? undefined : Number(val) } as SettingsFormState)); }} /> Limits total git worktrees including in-review tasks
setForm((f) => ({ ...f, worktreeInitCommand: e.target.value })) } /> Shell command to run in each new worktree after creation
When enabled, completed task worktrees are returned to an idle pool instead of being deleted, preserving build caches for faster startup
Discouraged. This restores the legacy behavior where a live fusion/<task-id> branch collision silently forks work onto sibling branches like -2 and can hide prior commits from the default recovery flow.
{form.recycleWorktrees ? "Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names" : "How to name fresh worktree directories. Only applies when recycling is off."}
setForm((f) => ({ ...f, worktreesDir: e.target.value })) } />
{form.worktrunk?.enabled === true ? "Disabled because Worktrunk integration is enabled — worktrunk manages the worktree directory layout. Disable worktrunk integration to use a custom directory." : <> Optional. Supports ~ and {"{repo}"}. Defaults to <projectRoot>/.worktrees when unset. Only affects newly-created worktrees. }
When enabled, the merger fetches from the configured remote and rebases the task branch onto the latest default-branch tip before merging — catching concurrent pushes from other collaborators or fusion workers. Any conflicts the rebase surfaces flow into the existing smart/AI resolve pipeline.
{form.worktreeRebaseBeforeMerge !== false && (
Which remote to fetch for the pre-merge rebase. "Use git default" falls back to the remote configured for the default branch (typically origin).
)}
In addition to the remote rebase above, also rebase the task branch onto the local default-branch HEAD (rootDir). This catches sibling tasks that merged locally but haven't been pushed yet — without it, two concurrent tasks where one deletes code can have the other silently re-introduce it via the fallback strategy. Enabled by default; only disable if it causes issues with your workflow.

Worktrunk integration

Disabled by default (opt-in). When enabled, Fusion shells out to worktrunk for worktree create, sync, prune, and remove operations and follows worktrunk's directory layout. {!worktrunkInstallVerified && form.worktrunk?.enabled !== true && ( Install the worktrunk binary below to enable this integration. )}
{worktrunkInstall.status === "installed" && ( worktrunk {worktrunkInstall.version ?? ""} installed at {worktrunkInstall.installPath ?? "~/.fusion/bin/worktrunk"} )} {(worktrunkInstall.status === "missing" || worktrunkInstall.status === "installing") && ( <> Enable worktrunk and request approval to install the pinned release. )} {worktrunkInstall.status === "pending-approval" && ( <> Awaiting approval — open Approvals to continue. )} {(worktrunkInstall.status === "denied" || worktrunkInstall.status === "failed") && ( <> {worktrunkInstall.error ?? "Worktrunk install failed."} )}
setForm((f) => ({ ...f, worktrunk: { enabled: f.worktrunk?.enabled === true, binaryPath: e.target.value, onFailure: f.worktrunk?.onFailure ?? "fail", }, })) } /> Optional. Leave blank to auto-resolve; Fusion will offer to install on first use.
fail stops on worktrunk errors for explicit operator recovery; fallback-native keeps progress moving by switching to Fusion's built-in worktree backend.
); case "commands": return ( <> {renderScopeBanner()}

Commands

setForm((f) => ({ ...f, testCommand: e.target.value || undefined })) } /> Command used to run tests — injected into generated task specs
setForm((f) => ({ ...f, buildCommand: e.target.value || undefined })) } /> Command used to build the project — injected into generated task specs
); case "merge": return ( <> {renderScopeBanner()}

Merge

More details When enabled, tasks that pass review are automatically merged into the main branch
More details When enabled, workflow revision feedback that explicitly names files outside the original task's declared File Scope is split into a dependent follow-up task instead of being appended to the current task's PROMPT.md.
{ const rawValue = e.target.value; if (rawValue === "") { setForm((f) => ({ ...f, verificationFixRetries: undefined } as SettingsFormState)); return; } const parsedValue = Number.parseInt(rawValue, 10); if (!Number.isFinite(parsedValue)) { setForm((f) => ({ ...f, verificationFixRetries: undefined } as SettingsFormState)); return; } const clampedValue = Math.max(0, Math.min(3, parsedValue)); setForm((f) => ({ ...f, verificationFixRetries: clampedValue } as SettingsFormState)); }} />
More details Controls auto-fix retry attempts after deterministic test/build verification failures — applies to both executor-time and in-merge verification (0-3).
More details Controls what happens after a task reaches In Review. Direct mode merges into the current branch locally. Pull request mode keeps the task in In Review while Fusion waits for GitHub reviews and required checks before merging the PR.
{form.mergeStrategy !== "pull-request" && (
More details Auto keeps today's squash behavior for branches with zero or one substantive commit, but switches multi-substantive branches to a history-preserving rebase-and-merge path. Individual tasks can override this in PROMPT.md with **Direct Merge Commit Strategy:** auto|always-squash|always-rebase.
)} {form.mergeStrategy === "pull-request" && (
More details When enabled, Fusion holds the PR in In Review until at least one approving GitHub review has been submitted. Useful on free private repos where GitHub's required-reviewer enforcement isn't available — without this, a fresh PR with no required checks is treated as immediately mergeable.
)}

GitHub Authentication

{(form.githubAuthMode ?? "gh-cli") === "token" && (
setForm((f) => ({ ...f, githubAuthToken: e.target.value || undefined })) } />
)}
More details When disabled, merge commit messages omit the task ID from the scope (e.g. feat: ... instead of feat(KB-001): ...)
More details When enabled, all commits made by Fusion include --author{" "} attribution identifying them as AI-generated
{form.commitAuthorEnabled !== false && ( <>
setForm((f) => ({ ...f, commitAuthorName: e.target.value || undefined, })) } /> Name used in commit author attribution
setForm((f) => ({ ...f, commitAuthorEmail: e.target.value || undefined, })) } /> Email used in commit author attribution
)}
More details When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.), generated files (dist/*, *.gen.ts), and trivial whitespace conflicts are resolved automatically without AI intervention. Complex code conflicts still require AI review.
More details When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.) are resolved using 'ours' strategy, generated files (dist/*, *.gen.ts) using 'theirs' strategy, and trivial whitespace conflicts are auto-resolved without spawning an AI agent. Complex code conflicts still require AI review.
More details Both Smart options start with a best-effort git fetch + fast-forward of local main from origin (so a freshly-pushed sibling commit doesn't get clobbered), then run an AI agent, then auto-resolve handles lock/generated/trivial files. They differ only in the final fallback: {" "} Smart, prefer main uses -X ours so main wins — protects just-merged sibling work and is the new default. {" "} Smart, prefer task uses -X theirs so the task branch wins — fast, but can resurrect code an earlier sibling task deleted (the FN-2887 class of regression). {" "} AI only retries the AI agent rather than auto-picking a side. {" "} Abort stops after the first AI attempt and waits for a human. {" "} Legacy "smart" and "prefer-main" values from older settings are migrated automatically.
When using smart-prefer-main, automatically prefer the branch side for files that main has recently modified to avoid silently discarding branch work.
Controls the post-merge audit gate. Warn (default) logs findings but auto-completes the merge. Block is the stricter opt-in mode that refuses to auto-complete merges with duplicate-subject or touched-file overlap risks. Off skips the audit entirely. Switching to Off is recommended only if you trust your branches don't silently drop edits.
More details When enabled, the merged result is automatically pushed to the configured git remote. This includes pulling the latest from the remote first (rebase) and resolving any conflicts with AI if needed.
{form.pushAfterMerge && (
setForm((f) => ({ ...f, pushRemote: e.target.value || undefined })) } />
More details Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".
)} ); case "agent-permissions": return ( <> {renderScopeBanner()}

Agent Permissions

Per-agent settings override project defaults. Each category controls a separate approval gate.
setForm((f) => ({ ...f, defaultAgentPermissionPolicy: { rules: toCompleteAgentPermissionRules(next?.rules) }, })) } />

Agent Provisioning Approvals

Configure project-level approval behavior for durable provisioning tools (fn_agent_create/fn_agent_delete).
setForm((f) => ({ ...f, agentProvisioning: next }))} /> ); case "memory": { // Use memory backend status from top-level hook call const { capabilities, status: backendStatus, loading: backendLoading, error: backendError, } = { capabilities: memoryCapabilities, status: memoryBackendStatus, loading: memoryBackendLoading, error: memoryBackendError, }; // Determine if editing is allowed const isMemoryEnabled = form.memoryEnabled !== false; const backendStatusResolved = !backendLoading && backendStatus !== null; const isBackendWritable = backendStatusResolved ? (capabilities?.writable ?? true) : true; const isEditingAllowed = isMemoryEnabled && isBackendWritable; const selectedMemoryFile = memoryFiles.find((file) => file.path === selectedMemoryPath); const memoryLayerNames: Record = { "long-term": "Long-term", daily: "Daily", dreams: "Dreams", }; return ( <> {renderScopeBanner()}

Memory

Memory lives in .fusion/memory/. Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed.
Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback.
{backendLoading ? (
Checking memory write access...
) : backendError ? (
Failed to load backend status: {backendError}
) : null} {backendStatusResolved && backendStatus.qmdAvailable === false && (
qmd is not installed. Search will use local files. Install indexed retrieval: {backendStatus.qmdInstallCommand || "bun install -g @tobilu/qmd"}
)}
Automatically compact memory when it exceeds the threshold on a schedule
{(form.memoryAutoSummarizeEnabled || false) && ( <>
setForm((f) => ({ ...f, memoryAutoSummarizeThresholdChars: parseInt(e.target.value, 10) || 50000, })) } min={1000} /> Memory will be compacted when it exceeds this character count
setForm((f) => ({ ...f, memoryAutoSummarizeSchedule: e.target.value })) } placeholder="0 3 * * *" /> Cron expression for auto-summarize schedule (default: daily at 3 AM)
)}
Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.
{isMemoryEnabled && form.memoryDreamsEnabled === true && ( <>
setForm((f) => ({ ...f, memoryDreamsSchedule: e.target.value })) } /> Cron expression for dream processing.
Manually trigger dream processing now.
)}
setMemoryTestQuery(e.target.value)} placeholder="Search memory with qmd" /> Runs the same qmd-backed memory_search path agents use.
{memoryTestResult && (
{memoryTestResult.results.length} result{memoryTestResult.results.length === 1 ? "" : "s"} {" "}for "{memoryTestResult.query}" qmd {memoryTestResult.qmdAvailable ? "available" : "missing"} · {memoryTestResult.usedFallback ? "local fallback used" : "qmd path used"} {memoryTestResult.results.length > 0 ? (
    {memoryTestResult.results.map((result, index) => (
  • {result.path}:{result.lineStart}

    {result.snippet}

  • ))}
) : ( No matching memory found. )}
)}
{!isMemoryEnabled && (
Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled.
)} {isMemoryEnabled && backendStatusResolved && !isBackendWritable && (
Memory is configured with a read-only backend. You can view the file, but saving is disabled.
)} {memoryLoading ? (
Loading memory…
) : (
{memoryDirty ? "Save or discard the current edits before switching files." : "Choose any project memory file to view or edit. Dreams is selected by default."}
{selectedMemoryFile && (
{memoryLayerNames[selectedMemoryFile.layer]} {selectedMemoryFile.path} {selectedMemoryFile.size.toLocaleString()} bytes · updated {new Date(selectedMemoryFile.updatedAt).toLocaleString()}
)}
{selectedMemoryFile?.layer === "long-term" && "Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams."} {selectedMemoryFile?.layer === "daily" && "Raw daily observations, open loops, and running context for dream processing."} {selectedMemoryFile?.layer === "dreams" && "Synthesized patterns and open loops promoted from daily memory."} {!selectedMemoryFile && "Edits the selected memory file."}
{ setMemoryContent(content); setMemoryDirty(true); }} readOnly={!isEditingAllowed} filePath={selectedMemoryPath} />
)} {!memoryLoading && (
{memoryDirty ? "Save or discard edits before compacting this file." : `Compacts ${selectedMemoryPath} and writes the result back to the same file.`}
)} {memoryDirty && isEditingAllowed && (
)} {memoryDirty && !isEditingAllowed && (
Cannot save: {isMemoryEnabled ? "Backend is read-only" : "Memory is disabled"}
)} ); } case "research-global": { const resolvedProvider = form.researchGlobalWebSearchProvider ?? form.researchGlobalDefaults?.searchProvider ?? "builtin"; const externalProvider = resolvedProvider === "searxng" || resolvedProvider === "brave" || resolvedProvider === "google" || resolvedProvider === "tavily"; const selectedCredentialProvider = resolvedProvider === "brave" || resolvedProvider === "tavily" ? resolvedProvider : null; const hasMissingResearchCredential = selectedCredentialProvider ? authProviders.some((provider) => provider.id === selectedCredentialProvider && !provider.authenticated) : false; const setSearchProvider = (provider: Settings["researchGlobalWebSearchProvider"]) => { setForm((current) => ({ ...current, researchGlobalWebSearchProvider: provider, researchGlobalDefaults: { ...(current.researchGlobalDefaults ?? {}), searchProvider: provider, }, })); }; return ( <> {renderScopeBanner()}

Research Defaults

Searches and fetches use the agent's native WebSearch/WebFetch tools. No API key required.
Advanced — external search providers
setForm((current) => ({ ...current, researchGlobalSearxngUrl: event.target.value || undefined, })) } placeholder="https://searx.example.com" />
setForm((current) => ({ ...current, researchGlobalGoogleSearchCx: event.target.value || undefined, })) } placeholder="custom-search-engine-id" />
Configure Brave, Tavily, and Google API keys in Authentication.
setForm((current) => ({ ...current, researchGlobalMaxConcurrentRuns: event.target.value === "" ? undefined : Number(event.target.value), })) } />
setForm((current) => ({ ...current, researchGlobalMaxSourcesPerRun: event.target.value === "" ? undefined : Number(event.target.value), researchGlobalDefaults: { ...(current.researchGlobalDefaults ?? {}), maxSourcesPerRun: event.target.value === "" ? undefined : Number(event.target.value), }, })) } />
setForm((current) => ({ ...current, researchGlobalDefaultTimeout: event.target.value === "" ? undefined : Number(event.target.value), })) } />
setForm((current) => ({ ...current, researchGlobalFetchTimeoutMs: event.target.value === "" ? undefined : Number(event.target.value), })) } />
setForm((current) => ({ ...current, researchGlobalMaxSynthesisRounds: event.target.value === "" ? undefined : Number(event.target.value), })) } />
{hasMissingResearchCredential && (
Missing credentials for the selected research provider.
)} ); } case "research-project": { const limits = form.researchSettings?.limits; const sources = form.researchSettings?.enabledSources; return ( <> {renderScopeBanner()}

Project Research Settings

Web search is always enabled. Configure the search provider under Research Defaults.
{[ ["pageFetch", "Page Fetch"], ["github", "GitHub"], ["localDocs", "Local Docs"], ["llmSynthesis", "LLM Synthesis"], ].map(([key, label]) => ( ))}
setForm((current) => ({ ...current, researchSettings: { ...(current.researchSettings ?? {}), limits: { ...(current.researchSettings?.limits ?? {}), maxConcurrentRuns: event.target.value === "" ? undefined : Number(event.target.value), }, }, })) } />
setForm((current) => ({ ...current, researchSettings: { ...(current.researchSettings ?? {}), limits: { ...(current.researchSettings?.limits ?? {}), maxSourcesPerRun: event.target.value === "" ? undefined : Number(event.target.value), }, }, })) } />
setForm((current) => ({ ...current, researchSettings: { ...(current.researchSettings ?? {}), limits: { ...(current.researchSettings?.limits ?? {}), maxDurationMs: event.target.value === "" ? undefined : Number(event.target.value), }, }, })) } />
setForm((current) => ({ ...current, researchSettings: { ...(current.researchSettings ?? {}), limits: { ...(current.researchSettings?.limits ?? {}), requestTimeoutMs: event.target.value === "" ? undefined : Number(event.target.value), }, }, })) } />
{researchLimitError && {researchLimitError}}
); } case "experimental": { const experimentalFeatures = form.experimentalFeatures ?? {}; // Merge known features (always shown) with custom features from settings, // while canonicalizing legacy aliases (e.g. devServer → devServerView) // so only one user-visible row is rendered per feature. const allFeatureKeys = Array.from( new Set([ ...Object.keys(KNOWN_EXPERIMENTAL_FEATURES), ...Object.keys(experimentalFeatures).map(getCanonicalExperimentalFeatureKey), ]) ).sort((a, b) => a.localeCompare(b)); const featureFlags = allFeatureKeys.map((key) => [key, isExperimentalFeatureEnabled(experimentalFeatures, key)] as const); return ( <> {renderScopeBanner()}

Experimental Features

Experimental features are early capabilities that are not yet fully stable. Enable them to test new functionality, but be aware they may change or be removed.
{featureFlags.map(([key, enabled]) => ( ))}
); } case "backups": return ( <> {renderScopeBanner()}

Database Backups

When enabled, the database is backed up automatically on a schedule
setForm((f) => ({ ...f, autoBackupSchedule: e.target.value })) } disabled={!form.autoBackupEnabled} /> Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min) {form.autoBackupSchedule && !/^[\s\d*,/-]+$/.test(form.autoBackupSchedule) && ( Invalid cron expression format )}
{ const val = e.target.value; setForm((f) => ({ ...f, autoBackupRetention: val === "" ? undefined : Number(val) })); }} disabled={!form.autoBackupEnabled} /> Number of backup files to keep (oldest are deleted first). Range: 1-100. {form.autoBackupRetention !== undefined && (form.autoBackupRetention < 1 || form.autoBackupRetention > 100) && ( Must be between 1 and 100 )}
setForm((f) => ({ ...f, autoBackupDir: e.target.value })) } disabled={!form.autoBackupEnabled} /> Directory for backup files, relative to project root {form.autoBackupDir && form.autoBackupDir.includes("..") && ( Path cannot contain parent directory traversal (..) )}

Memory Backups

When enabled, project and agent memory files are backed up automatically on a schedule.
setForm((f) => ({ ...f, memoryBackupSchedule: e.target.value }))} disabled={!form.memoryBackupEnabled} /> Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM). {form.memoryBackupSchedule && !/^[\s\d*,/-]+$/.test(form.memoryBackupSchedule) && ( Invalid cron expression format )}
{ const val = e.target.value; setForm((f) => ({ ...f, memoryBackupRetention: val === "" ? undefined : Number(val) })); }} disabled={!form.memoryBackupEnabled} /> Number of memory backups to keep (oldest are deleted first). Range: 1-100. {form.memoryBackupRetention !== undefined && (form.memoryBackupRetention < 1 || form.memoryBackupRetention > 100) && ( Must be between 1 and 100 )}
setForm((f) => ({ ...f, memoryBackupDir: e.target.value }))} disabled={!form.memoryBackupEnabled} /> Directory for memory backups, relative to project root. {form.memoryBackupDir && form.memoryBackupDir.includes("..") && ( Path cannot contain parent directory traversal (..) )}
{backupLoading ? (
Loading backup info…
) : backupInfo ? (
{backupInfo.count} backups
{backupInfo.totalSize > 1024 * 1024 ? `${(backupInfo.totalSize / (1024 * 1024)).toFixed(1)} MB` : `${(backupInfo.totalSize / 1024).toFixed(1)} KB`} total size
{backupInfo.backups.length > 0 && (
View {backupInfo.backups.length} backup(s)
    {backupInfo.backups.slice(0, 10).map((backup) => (
  • {backup.filename} {backup.size > 1024 * 1024 ? `${(backup.size / (1024 * 1024)).toFixed(1)} MB` : `${(backup.size / 1024).toFixed(1)} KB`}
  • ))} {backupInfo.backups.length > 10 && (
  • ...and {backupInfo.backups.length - 10} more
  • )}
)}
) : null}
); case "notifications": return ( <> {renderScopeBanner()}

Notifications

Sticky-only suppresses notifications for transient failures that the engine auto-recovers. Choose "All failures" for the legacy immediate-notification behavior.
{ const parsed = Number(e.target.value); setForm((f) => ({ ...f, failureNotificationDelayMs: Number.isFinite(parsed) && parsed >= 0 ? parsed : 0, })); }} /> How long a failure must persist before a push notification is sent. 0 = notify immediately.
ntfy
{form.ntfyEnabled && (
{ const val = e.target.value; setForm((f) => ({ ...f, ntfyTopic: val || undefined })); }} /> Your ntfy.sh topic name (1–64 alphanumeric/hyphen/underscore characters).{" "} Learn more about ntfy.sh {form.ntfyTopic && !/^[a-zA-Z0-9_-]{1,64}$/.test(form.ntfyTopic) && ( Topic must be 1–64 alphanumeric, hyphen, or underscore characters )}
Advanced
{ const value = e.target.value; setForm((f) => ({ ...f, ntfyBaseUrl: value || undefined })); }} /> Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://. { const value = e.target.value; setForm((f) => ({ ...f, ntfyAccessToken: value || undefined })); }} /> Leave blank to publish without authentication. When set, Fusion sends an Authorization Bearer header with ntfy requests.
{NOTIFICATION_EVENT_OPTIONS.map(({ event, label, description }) => { const checked = form.ntfyEvents?.includes(event) ?? true; return (
{description}
); })}
{ const val = e.target.value; setForm((f) => ({ ...f, ntfyDashboardHost: val || undefined })); }} /> Base URL for deep links in notifications. When set, clicking a notification opens the dashboard directly to the task. {form.ntfyDashboardHost && !/^https?:\/\/.+/.test(form.ntfyDashboardHost) && ( Must be a valid URL starting with http:// or https:// )}
{(testNotificationResult["ntfy"] || testNotificationResult["ntfy-message"] || testNotificationResult["ntfy-room"]) && (
{testNotificationResult["ntfy"] && ( General: {testNotificationResult["ntfy"].message} )} {testNotificationResult["ntfy-message"] && ( Message inbox: {testNotificationResult["ntfy-message"].message} )} {testNotificationResult["ntfy-room"] && ( Room reply: {testNotificationResult["ntfy-room"].message} )}
)}
)}
Webhook
{form.webhookEnabled && (
{ const val = e.target.value; setForm((f) => ({ ...f, webhookUrl: val || undefined })); }} />
{NOTIFICATION_EVENT_OPTIONS.map(({ event, label, description }) => { const currentEvents = form.webhookEvents ?? [...DEFAULT_NTFY_EVENTS]; const checked = currentEvents.includes(event); return (
{description}
); })}
{testNotificationResult["webhook"] && (
{testNotificationResult["webhook"].message}
)}
)}
); case "node-sync": return ( <> {renderScopeBanner()}

Node Sync

Automatically synchronize settings between this node and connected remote nodes
{form.settingsSyncEnabled && ( <>
Include API keys and OAuth tokens in sync operations
)} ); case "remote": { const remoteForm = form as Record; const activeProvider = (remoteForm.remoteActiveProvider as "tailscale" | "cloudflare" | null) ?? null; const tunnelState = (remoteStatus?.state as RemoteStatus["state"] | "error" | undefined) ?? "stopped"; const statusColor = tunnelState === "running" ? "running" : tunnelState === "starting" ? "starting" : tunnelState === "failed" || tunnelState === "error" ? "error" : "stopped"; return ( <> {renderScopeBanner()}

Remote Access

{tunnelState} {remoteStatus?.provider && · {remoteStatus.provider}} {remoteStatus?.url && {remoteStatus.url}} {remoteStatus?.lastError && {remoteStatus.lastError}}
{tunnelState === "stopped" && externalTunnel && (
{externalTunnel.url && {externalTunnel.url}} {tunnelShareLink?.qrSvg && (
Scan to open: External tunnel QR code
)}
)} {tunnelState === "running" && (remoteStatus?.url || tunnelShareLink) && (() => { let accessCode: string | null = null; let tailnetUrl: string | null = remoteStatus?.url ?? null; if (tunnelShareLink?.url) { try { const parsed = new URL(tunnelShareLink.url); accessCode = parsed.searchParams.get("rt"); if (!tailnetUrl) tailnetUrl = `${parsed.origin}/`; } catch { // fall through } } return (
{tailnetUrl && (
Tailnet URL: {tailnetUrl}
)} {accessCode && (
Remote access code: {accessCode}
)} {tunnelShareLink?.qrSvg && (
Scan to connect: Remote access QR code
)}
); })()}
{!activeProvider && Select a provider above to configure remote access.}
{activeProvider === "cloudflare" && remoteStatus?.cloudflaredAvailable === true && (
)} {activeProvider === "cloudflare" && remoteStatus?.cloudflaredAvailable === false && (
)} {activeProvider && (
{activeProvider === "tailscale" ? ( <> Tailscale Funnel will expose this dashboard on your tailnet's public {`https://..ts.net/`} URL — no hostname or port configuration needed. ) : ( <> {(remoteForm.remoteCloudflareQuickTunnel ?? true) ? "Using Quick Tunnel — automatically creates a random trycloudflare.com URL, no account needed." : "Named Tunnel mode enabled — configure tunnel name, token, and ingress URL below."}
{ const detailsOpen = event.currentTarget.open; setForm((f) => { const currentQuickTunnel = Boolean((f as Record).remoteCloudflareQuickTunnel ?? true); const nextQuickTunnel = !detailsOpen; if (currentQuickTunnel === nextQuickTunnel) { return f; } return { ...f, remoteCloudflareQuickTunnel: nextQuickTunnel } as SettingsFormState; }); }} > Advanced (Named Tunnel) {!(remoteForm.remoteCloudflareQuickTunnel ?? true) ? (
setForm((f) => ({ ...f, remoteCloudflareTunnelName: e.target.value } as SettingsFormState))} /> setForm((f) => ({ ...f, remoteCloudflareTunnelToken: e.target.value } as SettingsFormState))} /> setForm((f) => ({ ...f, remoteCloudflareIngressUrl: e.target.value } as SettingsFormState))} />
) : null}
)}
)}
{tunnelState === "running" || tunnelState === "starting" ? ( ) : ( <> {externalTunnel ? (
) : ( )} {activeProvider === "cloudflare" && remoteStatus?.cloudflaredAvailable === false ? ( cloudflared must be installed to start the tunnel ) : null} )}
Advanced Settings
setForm((f) => ({ ...f, remoteShortLivedTtlMs: Number(e.target.value || 900000) } as SettingsFormState))} /> {remoteShortLivedToken && Last short-lived token expires at {new Date(remoteShortLivedToken.expiresAt).toLocaleString()} ({remoteShortLivedToken.ttlMs}ms)}
Automatically restore tunnel on startup if it was running when last stopped.
URL and QR generation use the selected token type. {remoteAuthLinkTokenType === "short-lived" ? ` TTL: ${Number(remoteForm.remoteShortLivedTtlMs ?? 900000)}ms.` : ""} {remoteUrlPreview?.url && ( <> Authenticated URL:{remoteUrlPreview.url} Token type: {remoteUrlPreview.tokenType} {remoteUrlPreview.expiresAt ? ` · Expires at ${new Date(remoteUrlPreview.expiresAt).toLocaleString()}` : " · No expiry"} )} {remoteQrSvg && (

Scan this QR code on your phone

Remote access QR code
QR SVG markup
{remoteQrSvg}
)}
); } case "prompts": return ( <> {renderScopeBanner()}

Prompts

{ setForm((f) => ({ ...f, agentPrompts, })); }} promptOverrides={form.promptOverrides} onPromptOverridesChange={(overrides) => { setForm((f) => ({ ...f, promptOverrides: overrides, })); }} /> ); case "plugins": return ( <> {renderScopeBanner()}

Plugins

); case "authentication": { // CLI-backed providers (currently just claude-cli) render their own // compact card with Enable/Disable + Test actions — bypassing the // OAuth/API-key rendering below. Filter them out of the standard // sort and render alongside. const cliAuthProviders = authProviders.filter((p) => p.type === "cli"); const nonCliProviders = authProviders.filter((p) => p.type !== "cli"); // Sort providers: authenticated first, then unauthenticated. Within each bucket, sort alphabetically by name. const sortedProviders = [...nonCliProviders].sort((a, b) => { if (a.authenticated !== b.authenticated) { return a.authenticated ? -1 : 1; } return a.name.localeCompare(b.name); }); const authenticatedProviders = sortedProviders.filter(p => p.authenticated); const unauthenticatedProviders = sortedProviders.filter(p => !p.authenticated); // CLI-backed providers live in whichever bucket matches their current // auth state (Authenticated when signed in, Available otherwise). const claudeCliProvider = cliAuthProviders.find((p) => p.id === "claude-cli"); const cursorCliProvider = cliAuthProviders.find((p) => p.id === "cursor-cli"); const llamaCppProvider = cliAuthProviders.find((p) => p.id === "llama-cpp"); const claudeCliCard = claudeCliProvider ? ( { void loadAuthStatus(); }} /> ) : null; const cursorCliCard = cursorCliProvider ? ( { void loadAuthStatus(); }} /> ) : null; const llamaCppCard = llamaCppProvider ? ( { void loadAuthStatus(); }} /> ) : null; const showAuthenticatedGroup = authenticatedProviders.length > 0 || (claudeCliProvider?.authenticated ?? false) || (cursorCliProvider?.authenticated ?? false) || (llamaCppProvider?.authenticated ?? false); const showAvailableGroup = unauthenticatedProviders.length > 0 || (claudeCliProvider && !claudeCliProvider.authenticated) || (cursorCliProvider && !cursorCliProvider.authenticated) || (llamaCppProvider && !llamaCppProvider.authenticated); return ( <>

Authentication

{authLoading ? (
Loading authentication status…
) : authProviders.length === 0 ? (
No providers available
) : (
{ void loadAuthStatus(); } }} /> { void loadAuthStatus(); } }} /> {!showAuthenticatedGroup && (
Sign in to at least one provider to get started with AI models.
)} {showAuthenticatedGroup && (
Authenticated
{claudeCliProvider?.authenticated && claudeCliCard} {cursorCliProvider?.authenticated && cursorCliCard} {llamaCppProvider?.authenticated && llamaCppCard} {authenticatedProviders.map((provider) => (
{/* Stable icon wrapper contract for auth card tests: auth-provider-icon- */} {provider.name} ✓ Active {provider.authenticated && provider.keyHint && ( Key: {provider.keyHint} )}
{provider.type === "api_key" ? (
setApiKeyInputs((prev) => ({ ...prev, [provider.id]: e.target.value }))} disabled={authActionInProgress === provider.id} /> {provider.authenticated && !apiKeyInputs[provider.id] ? ( ) : ( )}
{authActionInProgress === provider.id && ( Saving… )} {apiKeyErrors[provider.id] && ( {apiKeyErrors[provider.id]} )}
) : (
{authActionInProgress === provider.id ? ( ) : provider.loginInProgress ? (
) : ( )}
)}
))}
)} {showAvailableGroup && (
Available
{claudeCliProvider && !claudeCliProvider.authenticated && claudeCliCard} {cursorCliProvider && !cursorCliProvider.authenticated && cursorCliCard} {llamaCppProvider && !llamaCppProvider.authenticated && llamaCppCard} {unauthenticatedProviders.map((provider) => (
{/* Stable icon wrapper contract for auth card tests: auth-provider-icon- */} {provider.name} ✗ Not connected
{provider.type === "api_key" ? (
setApiKeyInputs((prev) => ({ ...prev, [provider.id]: e.target.value }))} disabled={authActionInProgress === provider.id} />
{authActionInProgress === provider.id && ( Saving… )} {apiKeyErrors[provider.id] && ( {apiKeyErrors[provider.id]} )}
) : (
{authActionInProgress === provider.id ? ( ) : provider.loginInProgress ? (
) : ( )} {provider.id === "github-copilot" && deviceCodes[provider.id] && (provider.loginInProgress || authActionInProgress === provider.id) && (
Enter this code on GitHub
{deviceCodes[provider.id].userCode}
)} {loginInstructions[provider.id] && (provider.loginInProgress || authActionInProgress === provider.id) && ( )} {manualCodeConfigs[provider.id] && (provider.loginInProgress || authActionInProgress === provider.id) && ( setManualCodeInputs((prev) => ({ ...prev, [provider.id]: value }))} onSubmit={() => void handleSubmitManualCode(provider.id)} prompt={manualCodeConfigs[provider.id].prompt} placeholder={manualCodeConfigs[provider.id].placeholder} helpText={manualCodeConfigs[provider.id].helpText} disabled={manualCodeSubmitInProgress === provider.id} submitLabel={manualCodeSubmitInProgress === provider.id ? "Submitting…" : "Submit code"} data-testid={`auth-manual-code-${provider.id}`} /> )}
)}
))}
)}
)} Authentication changes take effect immediately — no need to save. {onReopenOnboarding && (
Re-run the setup wizard to review or update your AI provider and model configuration.
)} ); } case "hermes-runtime": return ( <>

Hermes Runtime

); case "openclaw-runtime": return ( <>

OpenClaw Runtime

); case "paperclip-runtime": return ( <>

Paperclip Runtime

); } }; return (

Settings

{appVersion && ( )} {updateCheckResult && ( {renderUpdateCheckResultContent()} )}
{loading ? (
Loading…
) : (
{showMobileSectionPicker && (
)}
{renderSectionFields()}
)}
{overlapPathPickerIndex !== null && (
event.stopPropagation()}>

Select ignored overlap path

Choose a file to ignore directly, or navigate into a folder and select the current directory.

Current directory: {overlapPathPickerCurrentPath === "." ? "(project root)" : overlapPathPickerCurrentPath}
)} {worktreesDirPickerOpen && (
event.stopPropagation()}>

Select worktrees directory

Navigate to the folder where Fusion should create task worktrees, then select the current directory.

Current directory: {worktreesDirPickerCurrentPath === "." ? "(project root)" : worktreesDirPickerCurrentPath}
)} {/* Import Confirmation Dialog */} {importDialogOpen && importPreview && (
e.target === e.currentTarget && setImportDialogOpen(false)} role="dialog" aria-modal="true">

Import Settings

Review the settings to be imported:

{importPreview.global && Object.keys(importPreview.global).length > 0 && (
Global Settings:
    {Object.entries(importPreview.global) .filter(([, v]) => v !== undefined) .map(([key]) => (
  • {key}
  • ))}
)} {importPreview.project && Object.keys(importPreview.project).length > 0 && (
Project Settings:
    {Object.entries(importPreview.project) .filter(([, v]) => v !== undefined) .map(([key]) => (
  • {key}
  • ))}
)}
If unchecked, existing settings will be replaced with imported values.
)}
); }