返回 DeepSeek-Reasonix
SettingsPanel.tsx
根目录 / desktop / frontend / src / components / SettingsPanel.tsx
1 import { ErrorMessage } from "./ErrorMessage";
2 import { StudioDiscoveryCard } from "./StudioIntroduction";
3 import { saveModelSettings, isModelSettingsResult } from "../lib/modelSettings";
4 import { ModelSettingHelp } from "./ModelSettingHelp";
5 import { desktopHost } from "../lib/desktopHost";
6 import { SettingsOptions } from "./SettingsOptions";
7 import { SettingsSelect } from "./SettingsSelect";
8 import { providerProtocolLabel, providerProtocolChoices } from "../lib/providerProtocol";
9 import { providerSupportsServerWebSearch } from "../lib/providerSearch";
10 export { providerSupportsServerWebSearch } from "../lib/providerSearch";
11 import { ManagementPageShell } from "./ManagementPageShell";
12 import { useProviderT as useT } from "../lib/providerSettingsLocale";
13 import type { ModelDetailsDraft } from "./ProviderModelDialog";
14 import { ConnectionTitle } from "./ConnectionTitle";
15 import { ProviderConnections } from "./ProviderConnections";
16 import { catalogForPreset } from "../lib/providerCatalog";
17 import { ProviderCatalogPicker, type CatalogChoice } from "./ProviderCatalogPicker";
18 import { Eye, EyeOff, Files } from "lucide-react";
19 import { lazy, memo, Suspense, startTransition, useCallback, useDeferredValue, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
20 import { ArrowRight, Check, CheckCircle2, ChevronDown, ChevronUp, CircleDollarSign, Clipboard, ExternalLink, KeyRound, Languages, ListChecks, Loader2, Monitor, MoreHorizontal, PanelBottom, Play, Power, QrCode, RefreshCw, Send, SlidersHorizontal, Trash2, Volume2 } from "lucide-react";
21 import { asArray } from "../lib/array";
22 import { ShellInterpreterFields } from "./SettingsShellSupport";
23 import { RuleList } from "./SettingsRuleList";
24 import { CopyButton } from "./CopyButton";
25 import { CHANNEL_ICONS } from "./channelIcons";
26 import { botAccessEntryCount, botAccessReady, botConnectionCredentialSummary, botConnectionLabel, botConnectionScopeLabel, botConnectionSecretEnv, botConnectionSecretPatch, botInstallTargetForConnection, botInstallTargetMatchesConnection, botTargetHint, botTargetLabel, diagnosticMessage, diagnosticReportDetail, firstConnectionRemote, formatInstallTimeLeft, formatInstallUserCode, qqBotAdded, type BotInstallTarget, type BotOfficialInstallTarget } from "./botConnectionSettings";
27 import { app, COMPACT_RATIO_MAX_PERCENT, COMPACT_RATIO_MIN_PERCENT, onRuntimeRebuilt, openExternal } from "../lib/bridge";
28 import { normalizeLangPref, useI18n, type DictKey, type LangPref } from "../lib/i18n";
29 import { createLatestRequestGate, mergedFetchedProviderModels, mergeProviderModelContextWindows, providerApiKeyEnvForSave, providerDefaultModel, providerIsConfigured, providerModelCandidates, providerModelContextWindowDrafts, providerRequiresKey } from "../lib/providerModels";
30 import { cachedFetchProviderModelCatalog, cachedFetchProviderModels, invalidateProviderCacheByAPIKeyEnv, shouldSkipAutoRefresh } from "../lib/providerModelCache";
31 import { providerBaseURLForSave, providerEndpointMismatchDetail, providerRequestURLForCatalogFormatChange, providerRequestURLFromConfig, trimmedBaseURL } from "../lib/providerEndpoint";
32 import { providerModelVisionCapability, providerVisionModelsForView } from "../lib/providerVisionCapability";
33 import { providerModelReasoningLevels } from "../lib/providerReasoningCapability";
34 import { useUpdater } from "../lib/useUpdater";
35 import {
36 applyTheme,
37 getTheme,
38 getThemeStyle,
39 normalizeThemePreference,
40 normalizeThemeStyleForTheme,
41 type Theme,
42 type ThemeStyle,
43 } from "../lib/theme";
44 import {
45 applyTerminalThemePreference,
46 createTerminalThemeSaveQueue,
47 getTerminalThemePreference,
48 normalizeTerminalThemePreference,
49 type TerminalThemePreference,
50 } from "../lib/terminalTheme";
51 import {
52 applyConversationWidth,
53 getCachedConversationWidth,
54 normalizeConversationWidth,
55 type ConversationWidth,
56 } from "../lib/conversationWidth";
57 import { applyTextSize, getTextSize, type TextSize } from "../lib/textSize";
58 import { snapZoom, zoomToPercent, saveRestartZoom, getRestartZoom, type ZoomLevel } from "../lib/dpiScale";
59 import {
60 applyFontFamily,
61 applyMonoFontFamily,
62 getFontFamily,
63 getMonoFontFamily,
64 getCustomFontName,
65 getCustomMonoFontName,
66 setCustomFontName,
67 setCustomMonoFontName,
68 type FontFamily,
69 type MonoFontFamily,
70 } from "../lib/fontFamily";
71 import { SessionExperienceSettings } from "./SessionExperienceSettings";
72 import { SettingsField, SettingsSection } from "./SettingsForm";
73 import { normalizeStatusBarItems, type StatusBarItemId } from "../lib/statusBarItems";
74 import { normalizeToolApprovalMode } from "../lib/types";
75 import {
76 comboFromKeyboardEvent,
77 detectShortcutPlatform,
78 formatShortcutCombo,
79 onShortcutsChanged,
80 resetCustomShortcuts,
81 resolvedShortcutCombo,
82 saveCustomShortcut,
83 shortcutAcceptsCombo,
84 shortcutConflict,
85 shortcutDefinitions,
86 type ShortcutAction,
87 } from "../lib/keyboardShortcuts";
88 import type { BotAccessView, BotAllowlistView, BotConnectionDiagnostic, BotConnectionView, BotInstallStartResult, BotRouteView, BotSettingsView, HookConfigView, HooksSettingsView, NetworkView, ProviderModelCapabilityView, ProviderModelCatalogUpdate, ProviderPresetView, ProviderView, SettingsTab, SettingsView } from "../lib/types";
89 import { AppearanceOverview } from "./AppearanceOverview";
90 import { applyConfiguredBaseAppearance, setBaseAppearance } from "../lib/themePack";
91 import { InlineConfirmButton } from "./InlineConfirmButton";
92 import { Tooltip } from "./Tooltip";
93 import { AnchoredPopover } from "./AnchoredPopover";
94 import { getGenerativePreset, setGenerativePreset, generativeMusic, type GenerativePreset } from "../lib/generative-music";
95 import { SoundSelect } from "./SoundSelect";
96 import { getSuccessPreference, setSuccessPreference, getAttentionPreference, setAttentionPreference, getNotificationVolume, setNotificationVolume as persistNotificationVolume, playSuccessChime, playAttentionChime, type SoundWavPref } from "../lib/sound";
97 import { NotificationVolumeSlider } from "./NotificationVolumeSlider";
98 import { ShortcutComboDisplay } from "./ShortcutComboDisplay";
99 import { SettingsNavigation, SETTINGS_NAV_TABS } from "./SettingsNavigation";
100 import { StatusBarItemsEditor } from "./StatusBarItemsEditor";
101 import { DesktopCloseBehaviorHint } from "./DesktopCloseBehaviorHint";
102 export type SettingsInitialFocus =
103 | { target: "bot-allowlist"; connectionId?: string; requestId?: number }
104 | { target: "model-access"; requestId?: number; onboarding?: boolean; providerName?: string; sourceTabId?: string }
105 | { target: "model-stats"; requestId: number };
106 type DesktopPlatform = "darwin" | "windows" | "linux";
107
108 const MCPServersSettingsPage = lazy(() => import("./CapabilitiesPanel").then((module) => ({ default: module.MCPServersSettingsPage })));
109 const RemoteHostsPage = lazy(() => import("./RemoteHostsPage").then((module) => ({ default: module.RemoteHostsPage })));
110 const SkillsSettingsPage = lazy(() => import("./CapabilitiesPanel").then((module) => ({ default: module.SkillsSettingsPage })));
111 const PluginsSettingsPage = lazy(() => import("./CapabilitiesPanel").then((module) => ({ default: module.PluginsSettingsPage })));
112 const MemorySettingsPage = lazy(() => import("./MemoryPanel").then((module) => ({ default: module.MemorySettingsPage })));
113 const SubagentsSettingsPage = lazy(() => import("./SubagentsPanel").then((module) => ({ default: module.SubagentsSettingsPage })));
114 const DiagnosticsSettingsPage = lazy(() => import("./DiagnosticsSettingsPage").then((module) => ({ default: module.DiagnosticsSettingsPage })));
115 const StorageSettingsPage = lazy(() => import("./StorageSettingsPage").then((module) => ({ default: module.StorageSettingsPage })));
116 const BrowserControlSettingsPage = lazy(() => import("./BrowserControlSettingsPage").then((module) => ({ default: module.BrowserControlSettingsPage })));
117 const UsageStatsPanel = lazy(() => import("./UsageStatsPanel").then((module) => ({ default: module.UsageStatsPanel })));
118 const QRCodeSVG = lazy(() => import("qrcode.react").then((module) => ({ default: module.QRCodeSVG })));
119
120 // SettingsPanel owns a full-window settings page while the workspace stays mounted.
121 export function SettingsPanel({
122 onClose,
123 onChanged,
124 initialTab,
125 onNavigate,
126 initialFocus,
127 agentRunning = false,
128 desktopPlatform,
129 onUseSubagent,
130 activeWorkspaceKey = "",
131 }: {
132 onClose: () => void;
133 onChanged: (settings?: SettingsView | null) => void;
134 initialTab?: SettingsTab;
135 onNavigate?: (tab: SettingsTab) => void;
136 workspaceRef?: { readonly current: HTMLDivElement | null };
137 initialFocus?: SettingsInitialFocus;
138 agentRunning?: boolean;
139 desktopPlatform: DesktopPlatform;
140 onUseSubagent: (command: string) => void;
141 activeWorkspaceKey?: string;
142 }) {
143 const t = useT();
144 const [s, setS] = useState<SettingsView | null>(null);
145 const [loadingSettings, setLoadingSettings] = useState(true);
146 const [settingsLoadFailed, setSettingsLoadFailed] = useState(false);
147 const [busy, setBusy] = useState(false);
148 const [err, setErr] = useState<string | null>(null);
149 const [warning, setWarning] = useState<string | null>(null);
150 const [modelApplication, setModelApplication] = useState<import("../lib/types").ModelSettingsResult | null>(null);
151 const modelApplicationSeq = useRef(0);
152 const settingsLoadSeq = useRef(0);
153 const settingsApplySeq = useRef(0);
154 const [theme, setThemeState] = useState<Theme>(getTheme());
155 const [themeStyle, setThemeStyleState] = useState<ThemeStyle>(() => getThemeStyle(getTheme()));
156 const [terminalTheme, setTerminalThemeState] = useState<TerminalThemePreference>(getTerminalThemePreference());
157 const [conversationWidth, setConversationWidth] = useState<ConversationWidth>(() => getCachedConversationWidth());
158 const [textSize, setTextSizeState] = useState<TextSize>(getTextSize());
159 const [zoomPct, setZoomPct] = useState<number>(zoomToPercent(getRestartZoom()));
160 const [fontFamily, setFontFamilyState] = useState<FontFamily>(getFontFamily());
161 const [monoFontFamily, setMonoFontFamilyState] = useState<MonoFontFamily>(getMonoFontFamily());
162 const [customFontName, setCustomFontNameState] = useState<string>(getCustomFontName());
163 const [customMonoFontName, setCustomMonoFontNameState] = useState<string>(getCustomMonoFontName());
164 const [tab, setTab] = useState<SettingsTab>(initialTab ?? "general");
165 const settingsContentRef = useRef<HTMLElement>(null);
166 const pendingSubagentCommandRef = useRef<string | null>(null);
167 const requestClose = useCallback(() => {
168 const command = pendingSubagentCommandRef.current;
169 pendingSubagentCommandRef.current = null;
170 onClose();
171 if (command) onUseSubagent(command);
172 }, [onClose, onUseSubagent]);
173 const zoomSaveSeq = useRef(0);
174 const terminalThemeSaveSeq = useRef(0);
175 const terminalThemeSavePending = useRef(false);
176 const terminalThemeSaveQueue = useRef<ReturnType<typeof createTerminalThemeSaveQueue> | null>(null);
177 if (!terminalThemeSaveQueue.current) {
178 terminalThemeSaveQueue.current = createTerminalThemeSaveQueue((next) => app.SetDesktopTerminalTheme(next));
179 }
180
181 const reload = useCallback(async () => {
182 const seq = ++settingsLoadSeq.current;
183 const applicationSeq = ++modelApplicationSeq.current;
184 setLoadingSettings(true);
185 setSettingsLoadFailed(false);
186 try {
187 const [view, application] = await Promise.all([
188 app.Settings(),
189 Promise.resolve().then(() => app.GetModelSettingsApplication()).catch(() => null),
190 ]);
191 const next = normalizeSettingsView(view);
192 if (seq !== settingsLoadSeq.current) return next;
193 setS(next);
194 if (application && applicationSeq === modelApplicationSeq.current) setModelApplication(application);
195 return next;
196 } catch {
197 if (seq !== settingsLoadSeq.current) return null;
198 setSettingsLoadFailed(true);
199 return null;
200 } finally {
201 if (seq === settingsLoadSeq.current) setLoadingSettings(false);
202 }
203 }, []);
204 useEffect(() => {
205 void reload();
206 }, [reload]);
207 const refreshModelApplication = useCallback(async () => {
208 const seq = ++modelApplicationSeq.current;
209 try {
210 const result = await app.GetModelSettingsApplication();
211 if (seq === modelApplicationSeq.current) setModelApplication(result);
212 } catch { /* Keep the last confirmed status until the next read. */ }
213 }, []);
214 useEffect(() => {
215 const refresh = () => { void refreshModelApplication(); };
216 const unsubscribe = onRuntimeRebuilt(refresh);
217 window.addEventListener("focus", refresh);
218 return () => {
219 unsubscribe();
220 window.removeEventListener("focus", refresh);
221 modelApplicationSeq.current += 1;
222 };
223 }, [refreshModelApplication]);
224 useEffect(() => {
225 if (modelApplication?.application !== "pending" && modelApplication?.application !== "failed") return;
226 const timer = window.setInterval(() => { void refreshModelApplication(); }, 2000);
227 return () => window.clearInterval(timer);
228 }, [modelApplication?.application, refreshModelApplication]);
229 useEffect(() => {
230 if (initialTab) setTab(initialTab);
231 }, [initialTab]);
232 useEffect(() => {
233 if (initialFocus?.target === "model-access") setTab("providers");
234 if (initialFocus?.target === "model-stats") setTab("model-stats");
235 }, [initialFocus?.target, initialFocus?.requestId]);
236 useEffect(() => {
237 const content = settingsContentRef.current;
238 if (!content) return;
239 content.scrollTop = 0;
240 content.scrollLeft = 0;
241 }, [tab]);
242 useEffect(() => {
243 if (!s) return;
244 const nextTheme = normalizeThemePreference(s.desktopTheme);
245 const nextStyle = normalizeThemeStyleForTheme(s.desktopThemeStyle, nextTheme);
246 setThemeState(nextTheme);
247 setThemeStyleState(nextStyle);
248 if (!terminalThemeSavePending.current) {
249 setTerminalThemeState(applyTerminalThemePreference(s.desktopTerminalTheme));
250 }
251 setConversationWidth(applyConversationWidth(s.conversationWidth));
252 }, [s?.conversationWidth, s?.desktopTheme, s?.desktopThemeStyle, s?.desktopTerminalTheme]);
253 useEffect(() => {
254 const host = desktopHost();
255 if (host.kind === "none" && desktopPlatform !== "windows") return;
256 let cancelled = false;
257 void (async () => {
258 try {
259 const persisted = host.kind === "electron"
260 ? await host.native.getAppZoom()
261 : await app.GetDesktopZoomFactor();
262 if (cancelled || typeof persisted !== "number" || !Number.isFinite(persisted)) return;
263 const snapped = snapZoom(persisted);
264 saveRestartZoom(snapped);
265 setZoomPct(zoomToPercent(snapped));
266 } catch {
267 // Older mocks or startup races can lack the binding; keep the local fallback.
268 }
269 })();
270 return () => {
271 cancelled = true;
272 };
273 }, [desktopPlatform]);
274
275 // apply runs a mutation, re-reads settings, and refreshes the topbar/model.
276 const pendingSettingsApplies = useRef(0);
277 const apply = useCallback(async (fn: () => Promise<unknown>) => {
278 const seq = ++settingsApplySeq.current;
279 pendingSettingsApplies.current += 1;
280 setBusy(true);
281 setErr(null);
282 setWarning(null);
283 try {
284 const result = await fn();
285 if (seq !== settingsApplySeq.current) return isModelSettingsResult(result) ? result.persisted : true;
286 if (isModelSettingsResult(result)) {
287 modelApplicationSeq.current += 1;
288 setModelApplication(result);
289 }
290 const next = await reload();
291 if (seq !== settingsApplySeq.current) return isModelSettingsResult(result) ? result.persisted : true;
292 onChanged(next);
293 window.dispatchEvent(new Event("reasonix:model-catalog-changed"));
294 if (isModelSettingsResult(result)) {
295 if (!result.persisted) throw new Error(result.issues.map(issue => issue.message).join("\n"));
296 }
297 if (typeof result === "string" && result.trim()) {
298 setWarning(result.trim());
299 }
300 return true;
301 } catch (e) {
302 if (seq !== settingsApplySeq.current) return false;
303 // Settings writes can be two-phase: persistence may succeed before a
304 // runtime refresh reports a real boot error. Re-read the authoritative
305 // state even on failure so the UI never offers an action that already
306 // committed (for example, a DeepSeek protocol upgrade).
307 try {
308 const next = await reload();
309 if (seq !== settingsApplySeq.current) return false;
310 onChanged(next);
311 window.dispatchEvent(new Event("reasonix:model-catalog-changed"));
312 } catch {
313 // Keep the original mutation error; it is the actionable failure.
314 }
315 if (seq !== settingsApplySeq.current) return false;
316 setErr(formatSettingsError(e, t));
317 return false;
318 } finally {
319 pendingSettingsApplies.current -= 1;
320 setBusy(pendingSettingsApplies.current > 0);
321 }
322 }, [reload, onChanged, t]);
323 const backgroundApply = useCallback(async (fn: () => Promise<void>) => {
324 const seq = ++settingsApplySeq.current;
325 setErr(null);
326 setWarning(null);
327 try {
328 await fn();
329 if (seq !== settingsApplySeq.current) return;
330 const next = await reload();
331 if (seq !== settingsApplySeq.current) return;
332 onChanged(next);
333 window.dispatchEvent(new Event("reasonix:model-catalog-changed"));
334 } catch (e) {
335 if (seq !== settingsApplySeq.current) return;
336 setErr(formatSettingsError(e, t));
337 try {
338 const current = await reload();
339 if (seq === settingsApplySeq.current) onChanged(current);
340 } catch { /* Keep the original save issue if readback is unavailable. */ }
341 }
342 }, [reload, onChanged, t]);
343 const setTerminalThemePreference = useCallback((next: TerminalThemePreference) => {
344 const seq = ++terminalThemeSaveSeq.current;
345 const previous = getTerminalThemePreference();
346 terminalThemeSavePending.current = true;
347 setErr(null);
348 setWarning(null);
349 applyTerminalThemePreference(next);
350 setTerminalThemeState(next);
351
352 void terminalThemeSaveQueue.current!(next)
353 .then(async () => {
354 if (seq !== terminalThemeSaveSeq.current) return;
355 const refreshed = await reload();
356 if (seq !== terminalThemeSaveSeq.current) return;
357 terminalThemeSavePending.current = false;
358 onChanged(refreshed);
359 })
360 .catch(async (error) => {
361 if (seq !== terminalThemeSaveSeq.current) return;
362 const refreshed = await reload();
363 if (seq !== terminalThemeSaveSeq.current) return;
364 const restored = normalizeTerminalThemePreference(refreshed?.desktopTerminalTheme ?? previous);
365 applyTerminalThemePreference(restored);
366 setTerminalThemeState(restored);
367 terminalThemeSavePending.current = false;
368 setErr(formatSettingsError(error, t));
369 onChanged(refreshed);
370 });
371 }, [onChanged, reload, t]);
372 const setRestartZoom = useCallback(async (zoom: ZoomLevel) => {
373 const snapped = snapZoom(zoom);
374 const seq = ++zoomSaveSeq.current;
375 setErr(null);
376 setWarning(null);
377 setZoomPct(zoomToPercent(snapped));
378 try {
379 const host = desktopHost();
380 if (host.kind === "electron") await host.native.setAppZoom(snapped);
381 else await app.SetDesktopZoomFactor(snapped);
382 if (seq === zoomSaveSeq.current) saveRestartZoom(snapped);
383 } catch (e) {
384 if (seq !== zoomSaveSeq.current) return;
385 setErr(formatSettingsError(e, t));
386 setZoomPct(zoomToPercent(getRestartZoom()));
387 }
388 }, [t]);
389
390 const selectTab = (next: SettingsTab) => { setTab(next); onNavigate?.(next); };
391
392 // These pages need SettingsView; capability pages load their own data.
393 const needsSettings = tab === "general" || tab === "models" || tab === "providers" || tab === "model-stats" || tab === "bots" || tab === "subagents" || tab === "network" || tab === "permissions" || tab === "sandbox" || tab === "appearance" || tab === "updates";
394 const lazySettingsPageFallback = <div className="empty">{t("settings.loading")}</div>;
395 const settingsNavigationItems = useMemo(() => SETTINGS_NAV_TABS.map((id) => ({
396 id,
397 label: settingsTabLabel(id, t),
398 meta: s ? settingsTabMeta(id, s, t) : "",
399 searchTerms: id === "general" ? [
400 "settings.language", "settings.currency",
401 "settings.closeBehavior",
402 "settings.defaultToolApprovalMode", "settings.sound", "settings.statusBarStyle", "settings.statusBarItems",
403 "settings.hardwareAcceleration", "GPU", "白屏", "闪烁", "渲染",
404 ].map((key) => t(key as DictKey)).join(" ") : "",
405 })), [s, t]);
406
407 return (
408 <ManagementPageShell title={t("settings.title")} className="settings-screen" onBack={requestClose} contentRef={settingsContentRef}
409 navigation={<SettingsNavigation items={settingsNavigationItems} activeTab={tab} onSelect={selectTab} />}>
410 <div className="settings-page-content">
411 {needsSettings && settingsLoadFailed && (
412 <div className="banner banner--error settings-load-error" role="alert">
413 <span>{t("settings.loadFailed")}</span>
414 <button className="btn btn--small" type="button" onClick={() => void reload()}>{t("common.retry")}</button>
415 </div>
416 )}
417 {needsSettings && err && <div className="banner banner--error"><ErrorMessage error={err} /></div>}
418 {needsSettings && warning && <div className="banner banner--warning"><ErrorMessage error={warning} /></div>}
419 {needsSettings && (tab === "models" || tab === "providers") && modelApplication && (modelApplication.application === "pending" || modelApplication.application === "failed") && (
420 <div className="banner banner--warning" role="status">
421 <span>{t(modelApplication.application === "pending" ? "settings.models.savedPending" : "settings.models.savedApplyFailed")}</span>
422 {modelApplication.issues.map((issue, index) => <span key={`${issue.code}:${index}`}><ErrorMessage error={issue} /></span>)}
423 {modelApplication.targets.filter(target => target.application === "failed").map(target => (
424 <button className="btn btn--small" key={target.tabId} type="button" disabled={busy} onClick={() => void apply(() => app.RetryModelSettingsApplication(target.tabId))}>{t("settings.models.applyRetry")}{target.title ? ` · ${target.title}` : ""}</button>
425 ))}
426 </div>
427 )}
428 {needsSettings && !s ? (
429 loadingSettings ? <div className="empty">{t("settings.loading")}</div> : null
430 ) : (
431 <>
432 {tab === "general" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><GeneralSection s={s} busy={busy} apply={apply} agentRunning={agentRunning} /></SettingsPageShell>}
433 {(tab === "models" || tab === "providers" || tab === "model-stats") && s && <SettingsPageShell key="model-pages" s={s} tab={tab} busy={busy} apply={apply}><ModelsSection onOpenProviders={() => selectTab("providers")} s={s} busy={busy} apply={apply} backgroundApply={backgroundApply} onboarding={initialFocus?.target === "model-access" && initialFocus.onboarding} focusProvider={initialFocus?.target === "model-access" ? initialFocus.providerName : undefined} focusRequestId={initialFocus?.target === "model-access" ? initialFocus.requestId : undefined} onOnboardingComplete={onClose} subtab={tab === "providers" ? "access" : tab === "model-stats" ? "stats" : "usage"} /></SettingsPageShell>}
434 {tab === "bots" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><BotsSection s={s} busy={busy} apply={apply} initialFocus={initialFocus} /></SettingsPageShell>}
435 {tab === "mcp" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><MCPServersSettingsPage /></Suspense></SettingsPageShell>}
436 {tab === "remote" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><RemoteHostsPage /></Suspense></SettingsPageShell>}
437 {tab === "skills" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><SkillsSettingsPage activeWorkspaceKey={activeWorkspaceKey} /></Suspense></SettingsPageShell>}
438 {tab === "subagents" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><Suspense fallback={lazySettingsPageFallback}><SubagentsSettingsPage s={s} onUseInChat={(command) => {
439 pendingSubagentCommandRef.current = command;
440 requestClose();
441 }} /></Suspense></SettingsPageShell>}
442 {tab === "plugins" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><PluginsSettingsPage /></Suspense></SettingsPageShell>}
443 {tab === "memory" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><MemorySettingsPage /></Suspense></SettingsPageShell>}
444 {tab === "hooks" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><HooksSection onChanged={onChanged} /></SettingsPageShell>}
445 {tab === "diagnostics" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><DiagnosticsSettingsPage onNavigate={selectTab} /></Suspense></SettingsPageShell>}
446 {tab === "shortcuts" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><ShortcutsSection /></SettingsPageShell>}
447 {tab === "permissions" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><PermissionsSection s={s} busy={busy} apply={apply} /></SettingsPageShell>}
448 {tab === "sandbox" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><SandboxSection s={s} busy={busy} apply={apply} windows={desktopPlatform === "windows"} /></SettingsPageShell>}
449 {tab === "network" && s && <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}><NetworkSection s={s} busy={busy} apply={apply} /></SettingsPageShell>}
450 {tab === "appearance" && s && (
451 <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}>
452 <AppearanceOverview
453 theme={theme}
454 themeStyle={themeStyle}
455 terminalTheme={terminalTheme}
456 conversationWidth={conversationWidth}
457 textSize={textSize}
458 showDisplayZoom={desktopHost().kind !== "none" || desktopPlatform === "windows"}
459 zoomPct={zoomPct}
460 fontFamily={fontFamily}
461 monoFontFamily={monoFontFamily}
462 customFontName={customFontName}
463 customMonoFontName={customMonoFontName}
464 onTheme={(nextTheme) => {
465 applyConfiguredBaseAppearance(nextTheme, themeStyle);
466 setThemeState(nextTheme);
467 void apply(() => app.SetDesktopAppearance(nextTheme, themeStyle));
468 }}
469 onConversationWidth={(width) => {
470 applyConversationWidth(width);
471 setConversationWidth(width);
472 void apply(() => app.SetDesktopConversationWidth(width));
473 }}
474 onThemeStyle={(style) => {
475 // AppearanceOverview already persists via ActivateBaseStyle /
476 // experience APIs. Parent only mirrors React + DOM state.
477 applyTheme(getTheme(), style, { persist: false });
478 setThemeStyleState(style);
479 setBaseAppearance(getTheme(), style);
480 }}
481 onTerminalTheme={setTerminalThemePreference}
482 onTextSize={(size) => {
483 applyTextSize(size);
484 setTextSizeState(size);
485 }}
486 onRestartZoom={setRestartZoom}
487 onFontFamily={(font) => {
488 applyFontFamily(font);
489 setFontFamilyState(font);
490 }}
491 onMonoFontFamily={(font) => {
492 applyMonoFontFamily(font);
493 setMonoFontFamilyState(font);
494 }}
495 onCustomFontNameChange={(name) => {
496 setCustomFontNameState(name);
497 setCustomFontName(name);
498 applyFontFamily("custom");
499 }}
500 onCustomMonoFontNameChange={(name) => {
501 setCustomMonoFontNameState(name);
502 setCustomMonoFontName(name);
503 applyMonoFontFamily("custom");
504 }}
505 />
506 </SettingsPageShell>
507 )}
508 {tab === "storage" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><StorageSettingsPage /></Suspense></SettingsPageShell>}
509 {tab === "browser" && <SettingsPageShell key={tab} s={s} tab={tab} busy={false} apply={apply}><Suspense fallback={lazySettingsPageFallback}><BrowserControlSettingsPage /></Suspense></SettingsPageShell>}
510 {tab === "updates" && s && (
511 <SettingsPageShell key={tab} s={s} tab={tab} busy={busy} apply={apply}>
512 <AboutSection
513 configPath={s.configPath}
514 shadowedByPath={s.shadowedByPath}
515 checkUpdates={s.checkUpdates}
516 updaterEnabled={s.updaterEnabled === true}
517 telemetry={s.telemetry !== false}
518 metrics={s.metrics !== false}
519 settingsBusy={busy}
520 applySettings={apply}
521 />
522 </SettingsPageShell>
523 )}
524 </>
525 )}
526 </div>
527 </ManagementPageShell>
528 );
529 }
530
531 function SettingsPageShell({ s: _s, tab, children }: { s: SettingsView | null; tab: SettingsTab; busy: boolean; apply: (fn: () => Promise<unknown>) => Promise<boolean>; children: ReactNode }) {
532 const t = useT();
533 return (
534 <div aria-label={settingsTabPageTitle(tab, t)} className={`settings-page settings-page--${settingsPageKind(tab)} settings-page--${tab}`} data-layout={settingsPageLayout(tab)}>
535 {children}
536 </div>
537 );
538 }
539
540 export function settingsPageLayout(tab: SettingsTab): "form" | "list" | "detail" | "tool" {
541 if (tab === "providers" || tab === "bots") return "detail";
542 if (["model-stats", "diagnostics", "hooks", "updates"].includes(tab)) return "tool";
543 if (["mcp", "remote", "skills", "subagents", "plugins", "memory", "shortcuts"].includes(tab)) return "list";
544 return "form";
545 }
546
547 function settingsPageKind(tab: SettingsTab): "form" | "manager" {
548 switch (tab) {
549 case "providers":
550 case "model-stats":
551 case "bots":
552 case "hooks":
553 case "diagnostics":
554 case "mcp":
555 case "remote":
556 case "skills":
557 case "subagents":
558 case "plugins":
559 case "memory":
560 case "appearance":
561 return "manager";
562 default:
563 return "form";
564 }
565 }
566
567
568 function settingsTabPageTitle(id: SettingsTab, t: ReturnType<typeof useT>): string {
569 switch (id) {
570 case "mcp": return t("settings.tab.mcp");
571 case "skills": return t("settings.tab.skills");
572 case "plugins": return t("settings.tab.plugins");
573 case "memory": return t("settings.tab.memory");
574 case "diagnostics": return t("settings.tab.diagnostics");
575 case "shortcuts": return t("settings.tab.shortcuts");
576 default: return settingsTabLabel(id, t);
577 }
578 }
579
580 type SectionProps = {
581 s: SettingsView;
582 busy: boolean;
583 apply: (fn: () => Promise<unknown>) => Promise<boolean>;
584 };
585
586 type ModelsSectionProps = SectionProps & {
587 onOpenProviders?: () => void;
588 onboarding?: boolean;
589 focusProvider?: string;
590 focusRequestId?: number;
591 onOnboardingComplete?: () => void;
592 backgroundApply: (fn: () => Promise<void>) => Promise<void>;
593 subtab: "usage" | "access" | "stats";
594 };
595
596 function settingsTabLabel(id: SettingsTab, t: ReturnType<typeof useT>): string {
597 switch (id) {
598 case "model-stats": return t("settings.modelTab.stats");
599 case "general":
600 return t("settings.tab.general");
601 case "models":
602 return t("settings.models.preferences");
603 case "providers":
604 return t("settings.models.services");
605 case "bots":
606 return t("settings.tab.bots");
607 case "mcp":
608 return t("settings.tab.mcp");
609 case "remote":
610 return t("settings.tab.remote");
611 case "skills":
612 return t("settings.tab.skills");
613 case "subagents":
614 return t("settings.tab.subagents");
615 case "plugins":
616 return t("settings.tab.plugins");
617 case "memory":
618 return t("settings.tab.memory");
619 case "hooks":
620 return t("settings.tab.hooks");
621 case "diagnostics":
622 return t("settings.tab.diagnostics");
623 case "shortcuts":
624 return t("settings.tab.shortcuts");
625 case "network":
626 return t("settings.tab.network");
627 case "permissions":
628 return t("settings.tab.permissions");
629 case "sandbox":
630 return t("settings.tab.sandbox");
631 case "appearance": return t("settings.tab.appearance");
632 case "storage": return t("settings.tab.storage");
633 case "browser": return t("settings.tab.browser");
634 case "updates":
635 return t("settings.tab.updates");
636 }
637 }
638
639 function settingsTabMeta(id: SettingsTab, s: SettingsView, t: ReturnType<typeof useT>): string {
640 switch (id) {
641 case "model-stats": return "";
642 case "models":
643 return settingsModelMeta(s, t);
644 case "general":
645 return s.sessionExperience === "deep" ? t("settings.sessionExperience.deep") : t("settings.sessionExperience.standard");
646 case "providers":
647 return t("settings.providerCount", { n: s.providers.length });
648 case "bots":
649 return botSettingsMeta(s.bot, t);
650 case "mcp":
651 return t("caps.connectorsTab");
652 case "remote":
653 return t("remote.tabHint");
654 case "skills":
655 return t("settings.tabSub.skills");
656 case "subagents":
657 return t("subagents.tabHint");
658 case "plugins":
659 return t("settings.tabSub.plugins");
660 case "memory":
661 return t("settings.tabSub.memory");
662 case "hooks":
663 return t("settings.tabSub.hooks");
664 case "diagnostics":
665 return t("settings.tabSub.diagnostics");
666 case "shortcuts":
667 return t("settings.tabSub.shortcuts");
668 case "network":
669 return proxyModeLabel(normalizeProxyMode(s.network.proxyMode), t);
670 case "permissions":
671 return "";
672 case "sandbox":
673 return "";
674 case "appearance": return t("settings.appearanceMeta");
675 case "storage": return t("settings.storageMeta");
676 case "browser": return t("settings.browserMeta");
677 case "updates":
678 return t("settings.updatesMeta");
679 }
680 }
681
682 function settingsModelMeta(s: SettingsView, t: ReturnType<typeof useT>): string {
683 const ref = toRef(s.defaultModel, s);
684 if (!ref) return t("common.none");
685 if (!ref.includes("/")) return ref;
686 const [provider, ...modelParts] = ref.split("/");
687 const model = modelParts.join("/") || ref;
688 const providerView = s.providers.find((p) => p.name === provider);
689 return `${modelProviderLabel(provider, providerView, t)} · ${model}`;
690 }
691
692 function botSettingsMeta(bot: BotSettingsView, t: ReturnType<typeof useT>): string {
693 const normalized = normalizeBotSettings(bot);
694 const connections = normalized.connections.length + (qqBotAdded(normalized.qq) ? 1 : 0);
695 if (connections === 0) return t("settings.botNoConnections");
696 if (!normalized.enabled) return t("settings.botDisabledWithConnections", { n: connections });
697 return t("settings.botConnectionCount", { n: connections });
698 }
699
700 export function ShortcutsSection() {
701 const t = useT();
702 const [platform] = useState(() => detectShortcutPlatform());
703 const [revision, setRevision] = useState(0);
704 const [recording, setRecording] = useState<ShortcutAction | null>(null);
705 const [conflict, setConflict] = useState<{ action: ShortcutAction; conflictAction: ShortcutAction } | null>(null);
706 const [unsupportedAction, setUnsupportedAction] = useState<ShortcutAction | null>(null);
707
708 useEffect(() => onShortcutsChanged(() => setRevision((value) => value + 1)), []);
709
710 const definitions = shortcutDefinitions();
711 const commitShortcut = (action: ShortcutAction, event: ReactKeyboardEvent<HTMLButtonElement>) => {
712 if (event.key === "Escape") {
713 event.preventDefault();
714 event.stopPropagation();
715 setConflict(null);
716 setUnsupportedAction(null);
717 setRecording(null);
718 return;
719 }
720 const combo = comboFromKeyboardEvent(event.nativeEvent);
721 if (!combo) return;
722 if (!shortcutAcceptsCombo(action, combo)) {
723 // Let the browser move focus before onBlur cancels recording. Updating
724 // recording state synchronously here can keep focus on the re-rendered
725 // button in WebKit.
726 if (event.key === "Tab") {
727 const recorder = event.currentTarget;
728 queueMicrotask(() => {
729 // Native Tab normally moves focus first. If this WebView does not,
730 // release focus so the recorder cannot become a keyboard trap.
731 if (document.activeElement === recorder) recorder.blur();
732 });
733 return;
734 }
735 event.preventDefault();
736 event.stopPropagation();
737 setConflict(null);
738 setUnsupportedAction(action);
739 return;
740 }
741 event.preventDefault();
742 event.stopPropagation();
743 const conflictDefinition = shortcutConflict(action, combo, platform);
744 if (conflictDefinition) {
745 setUnsupportedAction(null);
746 setConflict({ action, conflictAction: conflictDefinition.action });
747 return;
748 }
749 saveCustomShortcut(action, combo);
750 setConflict(null);
751 setUnsupportedAction(null);
752 setRecording(null);
753 setRevision((value) => value + 1);
754 };
755
756 return (
757 <SettingsSection
758 title={t("settings.shortcutsTitle")}
759 description={t("settings.shortcutsHint")}
760 actions={
761 <button
762 className="chip chip--icon"
763 type="button"
764 title={t("settings.shortcutsResetAll")}
765 aria-label={t("settings.shortcutsResetAll")}
766 onClick={() => {
767 resetCustomShortcuts();
768 setConflict(null);
769 setUnsupportedAction(null);
770 setRecording(null);
771 setRevision((value) => value + 1);
772 }}
773 >
774 <RefreshCw size={14} />
775 </button>
776 }
777 >
778 <div className="shortcuts-settings" data-revision={revision}>
779 {conflict && (
780 <div className="shortcuts-settings__conflict" role="alert">
781 {t("settings.shortcutsConflict", {
782 action: t(definitions.find((definition) => definition.action === conflict.action)?.labelKey ?? "settings.tab.shortcuts"),
783 conflict: t(definitions.find((definition) => definition.action === conflict.conflictAction)?.labelKey ?? "settings.tab.shortcuts"),
784 })}
785 </div>
786 )}
787 {unsupportedAction && (
788 <div className="shortcuts-settings__conflict" role="alert">
789 {t("settings.shortcutsEnterOnly", {
790 action: t(definitions.find((definition) => definition.action === unsupportedAction)?.labelKey ?? "settings.tab.shortcuts"),
791 })}
792 </div>
793 )}
794 {definitions.map((definition) => {
795 const resolved = resolvedShortcutCombo(definition.action, platform);
796 const defaultCombo = definition.defaults[platform];
797 const display = formatShortcutCombo(resolved, platform);
798 const isCustom = formatShortcutCombo(resolved, platform) !== formatShortcutCombo(defaultCombo, platform);
799 const isRecording = recording === definition.action;
800 return (
801 <div className="shortcuts-settings__row" key={definition.action}>
802 <div className="shortcuts-settings__copy">
803 <div className="shortcuts-settings__label">{t(definition.labelKey)}</div>
804 <div className="shortcuts-settings__desc">{t(definition.descriptionKey)}</div>
805 </div>
806 <div className="shortcuts-settings__control">
807 <button
808 className={`shortcuts-settings__key${isRecording ? " shortcuts-settings__key--recording" : ""}${definition.configurable === false ? " shortcuts-settings__key--locked" : ""}`}
809 type="button"
810 data-shortcut-action={definition.action}
811 disabled={definition.configurable === false}
812 aria-label={isRecording ? t("settings.shortcutsRecording") : display}
813 aria-pressed={isRecording}
814 onClick={(event) => {
815 setRecording(definition.action);
816 setConflict(null);
817 setUnsupportedAction(null);
818 // WebKit (the desktop WKWebView) does not focus buttons on
819 // click, and the recorder listens for keys on the button —
820 // without this the recorder never receives any keydown.
821 event.currentTarget.focus();
822 }}
823 onBlur={() => {
824 if (!isRecording) return;
825 setConflict(null);
826 setUnsupportedAction(null);
827 setRecording(null);
828 }}
829 onKeyDown={(event) => isRecording && commitShortcut(definition.action, event)}
830 >
831 {isRecording ? t("settings.shortcutsRecording") : <ShortcutComboDisplay combo={resolved} platform={platform} />}
832 </button>
833 <button
834 className="chip"
835 type="button"
836 disabled={!isCustom}
837 onClick={() => {
838 saveCustomShortcut(definition.action, null);
839 setConflict(null);
840 setUnsupportedAction(null);
841 setRecording(null);
842 setRevision((value) => value + 1);
843 }}
844 >
845 {t("settings.shortcutsReset")}
846 </button>
847 </div>
848 </div>
849 );
850 })}
851 </div>
852 </SettingsSection>
853 );
854 }
855
856 // allRefs flattens providers into "provider/model" refs for the model selectors.
857 export function allRefs(s: SettingsView): string[] {
858 const out: string[] = [];
859 for (const p of s.providers) {
860 if (!p.added || !providerIsConfigured(p)) continue;
861 for (const m of p.models) out.push(`${p.name}/${m}`);
862 }
863 return out;
864 }
865
866 // toRef normalises a stored model id (a provider name, a bare model, or a ref) to
867 // a "provider/model" ref so a <select> of refs can show it selected.
868 export function toRef(model: string, s: SettingsView): string {
869 if (!model) return "";
870 if (model.includes("/")) return model;
871 const byName = s.providers.find((p) => p.name === model);
872 if (byName) return `${byName.name}/${byName.default || byName.models[0] || ""}`;
873 const byModel = s.providers.find((p) => p.models.includes(model));
874 if (byModel) return `${byModel.name}/${model}`;
875 return model;
876 }
877
878 const PROXY_MODES = ["auto", "custom", "off"] as const;
879
880 // EFFORT_PRESETS is the canonical union of /effort levels the kernel recognises.
881 // The settings UI uses it for subagent defaults; provider-specific levels are
882 // inferred by the backend or edited in TOML for rare gateways.
883 export const EFFORT_PRESETS: readonly string[] = ["low", "medium", "high", "xhigh", "max"];
884 const COMPACT_RATIO_PRESETS = [
885 [0.7, "settings.compactRatioPreset.70", "settings.compactRatioPresetEffect.70"],
886 [0.8, "settings.compactRatioPreset.80", "settings.compactRatioPresetEffect.80"],
887 [0.85, "settings.compactRatioPreset.85", "settings.compactRatioPresetEffect.85"],
888 ] as const;
889 const REASONING_PROTOCOLS: readonly string[] = ["", "deepseek", "glm", "kimi-k3", "openai", "none"];
890 const THINKING_MODES: readonly string[] = ["", "enabled", "disabled", "adaptive"];
891 const PROXY_TYPES = ["http", "https", "socks5", "socks5h"] as const;
892 const LANGUAGE_PREFS: LangPref[] = ["", "zh", "en"];
893 const TOOL_APPROVAL_MODES = ["read-only", "workspace-write", "danger-full-access"] as const;
894 const BOT_TOOL_APPROVAL_MODES = ["", "read-only", "workspace-write", "danger-full-access"] as const;
895 const BOT_QUEUE_MODES = ["steer", "followup", "collect", "interrupt"] as const;
896 const BOT_QUEUE_DROPS = ["summarize", "old", "new"] as const;
897 const BOT_ROUTE_CHAT_TYPES = ["", "dm", "group", "guild", "direct", "thread"] as const;
898
899 type ProxyMode = (typeof PROXY_MODES)[number];
900
901 function normalizeProxyMode(mode: string): ProxyMode {
902 switch (mode) {
903 case "custom":
904 return "custom";
905 case "off":
906 return "off";
907 default:
908 return "auto";
909 }
910 }
911
912 function normalizeNetworkView(network: NetworkView): NetworkView {
913 return { ...network, proxyMode: normalizeProxyMode(network.proxyMode) };
914 }
915
916 function normalizeReasoningProtocol(protocol: string | undefined): string {
917 return REASONING_PROTOCOLS.includes(protocol ?? "") ? protocol ?? "" : "";
918 }
919
920 function normalizeThinkingMode(thinking: string | undefined): string {
921 const v = String(thinking ?? "").trim().toLowerCase();
922 return THINKING_MODES.includes(v) ? v : "";
923 }
924
925 export function providerEditorEffectiveKind(isNewCustomProvider: boolean, kind: string, kinds: string[]): string {
926 void isNewCustomProvider;
927 const selected = kind.trim();
928 return selected || kinds[0] || "openai";
929 }
930
931 function formatProviderHeaders(headers: Record<string, string> | null | undefined): string {
932 const entries = Object.entries(headers ?? {})
933 .map(([key, value]) => [key.trim(), String(value ?? "").trim()] as const)
934 .filter(([key, value]) => key && value)
935 .sort(([a], [b]) => a.localeCompare(b));
936 return entries.map(([key, value]) => `${key}: ${value}`).join("\n");
937 }
938
939 function parseProviderHeaders(raw: string): Record<string, string> {
940 const out: Record<string, string> = {};
941 for (const line of raw.split(/\r?\n/)) {
942 const trimmed = line.trim();
943 if (!trimmed || trimmed.startsWith("#")) continue;
944 const colon = trimmed.indexOf(":");
945 const eq = trimmed.indexOf("=");
946 const cut = colon >= 0 && (eq < 0 || colon < eq) ? colon : eq;
947 if (cut <= 0) continue;
948 const key = trimmed.slice(0, cut).trim();
949 const value = trimmed.slice(cut + 1).trim();
950 if (key && value) out[key] = value;
951 }
952 return out;
953 }
954
955 function sortedJSONValue(value: unknown): unknown {
956 if (Array.isArray(value)) return value.map(sortedJSONValue);
957 if (value && typeof value === "object") {
958 const out: Record<string, unknown> = {};
959 for (const key of Object.keys(value as Record<string, unknown>).sort((a, b) => a.localeCompare(b))) {
960 out[key] = sortedJSONValue((value as Record<string, unknown>)[key]);
961 }
962 return out;
963 }
964 return value;
965 }
966
967 function formatSettingsError(error: unknown, t: ReturnType<typeof useT>): string {
968 const msg = String((error as Error)?.message ?? error ?? "").trim();
969 const unknownModel = /^unknown model (.+)$/i.exec(msg);
970 if (unknownModel) return t("settings.errorUnknownModel", { model: unknownModel[1] });
971 const providerNotAdded = /^model (.+) is not available because provider (.+) is not added$/i.exec(msg);
972 if (providerNotAdded) return t("settings.errorModelProviderMissing", { model: providerNotAdded[1], provider: providerNotAdded[2] });
973 const providerNoKey = /^model (.+) is not available because provider (.+) has no key$/i.exec(msg);
974 if (providerNoKey) return t("settings.errorModelProviderNoKey", { model: providerNoKey[1], provider: providerNoKey[2] });
975 if (/^background session is still open; reopen or close it before upgrading the DeepSeek provider protocol$/i.test(msg)) {
976 return t("settings.errorProviderDetached");
977 }
978 const removeAccessBusy = /^finish or cancel active work using (.+) before removing the provider access$/i.exec(msg);
979 if (removeAccessBusy) return t("settings.errorRemoveAccessBusy", { provider: removeAccessBusy[1] });
980 const removeAccessDetached = /^background session is still using (.+); reopen or close it before removing the provider access$/i.exec(msg);
981 if (removeAccessDetached) return t("settings.errorProviderDetached");
982 const removeAccessNoFallback = /^remove provider access: (.+) is in use and no other configured provider exists$/i.exec(msg);
983 if (removeAccessNoFallback) return t("settings.errorRemoveProviderNoFallback", { provider: removeAccessNoFallback[1] });
984 const deleteProviderNoFallback = /^remove provider: (.+) is in use and no other configured provider exists$/i.exec(msg);
985 if (deleteProviderNoFallback) return t("settings.errorRemoveProviderNoFallback", { provider: deleteProviderNoFallback[1] });
986 const deleteProviderBusy = /^finish or cancel active work using (.+) before deleting the provider$/i.exec(msg);
987 if (deleteProviderBusy) return t("settings.errorDeleteProviderBusy", { provider: deleteProviderBusy[1] });
988 const deleteProviderDetached = /^background session is still using (.+); reopen or close it before deleting the provider$/i.exec(msg);
989 if (deleteProviderDetached) return t("settings.errorProviderDetached");
990 const saveBeforeRemoveAccess = /^save current session before removing provider access: (.+)$/is.exec(msg);
991 if (saveBeforeRemoveAccess) return t("settings.errorSaveBeforeRemoveAccess", { err: saveBeforeRemoveAccess[1] });
992 const saveBeforeDeleteProvider = /^save current session before deleting provider: (.+)$/is.exec(msg);
993 if (saveBeforeDeleteProvider) return t("settings.errorSaveBeforeDeleteProvider", { err: saveBeforeDeleteProvider[1] });
994 const removeProviderUsed = /^remove provider: (.+) is used by open tabs and no other configured provider exists$/i.exec(msg);
995 if (removeProviderUsed) return t("settings.errorRemoveProviderNoFallback", { provider: removeProviderUsed[1] });
996 return msg || t("settings.errorUnknown");
997 }
998
999 function validateProviderExtraBodyValue(value: unknown, path = "extra_body", t?: ReturnType<typeof useT>): void {
1000 if (value === null) {
1001 throw new Error(t ? t("settings.providerExtraBodyNull", { path }) : `${path} cannot contain null`);
1002 }
1003 if (Array.isArray(value)) {
1004 value.forEach((item, index) => validateProviderExtraBodyValue(item, `${path}[${index}]`, t));
1005 return;
1006 }
1007 if (typeof value === "object") {
1008 for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
1009 validateProviderExtraBodyValue(child, `${path}.${key}`, t);
1010 }
1011 }
1012 }
1013
1014 export function formatProviderExtraBody(extraBody: Record<string, unknown> | null | undefined): string {
1015 const cleaned: Record<string, unknown> = {};
1016 for (const [rawKey, value] of Object.entries(extraBody ?? {})) {
1017 const key = rawKey.trim();
1018 if (!key || value === undefined) continue;
1019 cleaned[key] = value;
1020 }
1021 if (Object.keys(cleaned).length === 0) return "";
1022 return JSON.stringify(sortedJSONValue(cleaned), null, 2);
1023 }
1024
1025 export function parseProviderExtraBody(raw: string, t?: ReturnType<typeof useT>): Record<string, unknown> {
1026 const trimmed = raw.trim();
1027 if (!trimmed) return {};
1028 const parsed = JSON.parse(trimmed) as unknown;
1029 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1030 throw new Error(t ? t("settings.providerExtraBodyObjectRequired") : "extra body must be a JSON object");
1031 }
1032 validateProviderExtraBodyValue(parsed, "extra_body", t);
1033 const out: Record<string, unknown> = {};
1034 for (const [rawKey, value] of Object.entries(parsed as Record<string, unknown>)) {
1035 const key = rawKey.trim();
1036 if (key) out[key] = value;
1037 }
1038 return out;
1039 }
1040
1041 export function providerExtraBodyParseError(error: unknown, t: ReturnType<typeof useT>): string {
1042 if (error instanceof SyntaxError) return t("settings.providerExtraBodyError");
1043 const message = String((error as Error)?.message ?? error ?? "").trim();
1044 return message || t("settings.providerExtraBodyError");
1045 }
1046
1047 function providerModelFetchFallbackMessage(error: unknown, t: ReturnType<typeof useT>): string {
1048 const message = String((error as Error)?.message ?? error);
1049 if (/\bstatus\s+(401|403)\b/i.test(message)) {
1050 return t("settings.fetchModelsManualFallbackAuth");
1051 }
1052 if (/\bstatus\s+(404|405)\b/i.test(message)) {
1053 return t("settings.fetchModelsManualFallbackUnsupported");
1054 }
1055 if (/\b(status\s+5\d\d|request failed|network|timeout|timed out|connection|deadline|fetch failed)\b/i.test(message)) {
1056 return t("settings.fetchModelsManualFallbackNetwork");
1057 }
1058 if (/\b(decode response|invalid character|unexpected end|unexpected format)\b/i.test(message)) {
1059 return t("settings.fetchModelsManualFallbackDecode");
1060 }
1061 return t("settings.fetchModelsManualFallbackGeneric", { err: message });
1062 }
1063
1064 function normalizeReasoningLanguage(lang: string | undefined): string {
1065 const v = String(lang ?? "").trim().toLowerCase();
1066 return v === "zh" || v === "en" ? v : "auto";
1067 }
1068
1069 function normalizeBotQueueMode(mode: unknown): string {
1070 const raw = String(mode ?? "").trim().toLowerCase();
1071 return BOT_QUEUE_MODES.includes(raw as any) ? raw : "steer";
1072 }
1073
1074 function normalizeBotQueueDrop(mode: unknown): string {
1075 const raw = String(mode ?? "").trim().toLowerCase();
1076 return BOT_QUEUE_DROPS.includes(raw as any) ? raw : "summarize";
1077 }
1078
1079 function normalizeBotRouteChatType(value: unknown): string {
1080 const raw = String(value ?? "").trim().toLowerCase();
1081 return BOT_ROUTE_CHAT_TYPES.includes(raw as any) ? raw : "";
1082 }
1083
1084 function normalizeBotRoute(raw: any): BotRouteView {
1085 return {
1086 connectionId: String(raw?.connectionId ?? "").trim(),
1087 platform: String(raw?.platform ?? "").trim().toLowerCase(),
1088 chatType: normalizeBotRouteChatType(raw?.chatType),
1089 chatId: String(raw?.chatId ?? "").trim(),
1090 userId: String(raw?.userId ?? "").trim(),
1091 threadId: String(raw?.threadId ?? "").trim(),
1092 model: String(raw?.model ?? "").trim(),
1093 toolApprovalMode: normalizeBotToolApprovalMode(raw?.toolApprovalMode),
1094 workspaceRoot: String(raw?.workspaceRoot ?? "").trim(),
1095 };
1096 }
1097
1098 function emptyBotRoute(): BotRouteView {
1099 return {
1100 connectionId: "",
1101 platform: "",
1102 chatType: "",
1103 chatId: "",
1104 userId: "",
1105 threadId: "",
1106 model: "",
1107 toolApprovalMode: "",
1108 workspaceRoot: "",
1109 };
1110 }
1111
1112 function botRouteHasValue(route: BotRouteView): boolean {
1113 return Boolean(
1114 route.connectionId ||
1115 route.platform ||
1116 route.chatType ||
1117 route.chatId ||
1118 route.userId ||
1119 route.threadId ||
1120 route.model ||
1121 route.toolApprovalMode ||
1122 route.workspaceRoot
1123 );
1124 }
1125
1126 function defaultBotSettings(): BotSettingsView {
1127 return {
1128 enabled: false,
1129 model: "",
1130 toolApprovalMode: "workspace-write",
1131 maxSteps: 0,
1132 debounceMs: 1500,
1133 queueMode: "steer",
1134 queueCap: 20,
1135 queueDrop: "summarize",
1136 ignoreSelfMessages: true,
1137 selfUserIds: {
1138 qq: [],
1139 feishu: [],
1140 weixin: [],
1141 dingtalk: [],
1142 },
1143 control: {
1144 enabled: false,
1145 addr: "127.0.0.1:37913",
1146 tokenEnv: "REASONIX_BOT_CONTROL_TOKEN",
1147 },
1148 pairing: {
1149 enabled: true,
1150 requestTtlMinutes: 60,
1151 maxPendingPerPlatform: 3,
1152 },
1153 routes: [],
1154 allowlist: {
1155 enabled: true,
1156 allowAll: false,
1157 qqUsers: [],
1158 feishuUsers: [],
1159 weixinUsers: [],
1160 qqApprovers: [],
1161 feishuApprovers: [],
1162 weixinApprovers: [],
1163 qqAdmins: [],
1164 feishuAdmins: [],
1165 weixinAdmins: [],
1166 qqGroups: [],
1167 feishuGroups: [],
1168 weixinGroups: [],
1169 dingtalkUsers: [],
1170 dingtalkApprovers: [],
1171 dingtalkAdmins: [],
1172 dingtalkGroups: [],
1173 },
1174 qq: { enabled: false, appId: "", appSecretEnv: "QQ_BOT_APP_SECRET", secretSet: false, sandbox: false, model: "", toolApprovalMode: "workspace-write", workspaceRoot: "", access: defaultBotAccess() },
1175 feishu: {
1176 enabled: false,
1177 domain: "feishu",
1178 appId: "",
1179 appSecretEnv: "FEISHU_BOT_APP_SECRET",
1180 secretSet: false,
1181 verificationToken: "",
1182 mode: "webhook",
1183 webhookPort: 8080,
1184 requireMention: true,
1185 },
1186 weixin: {
1187 enabled: false,
1188 accountId: "default",
1189 tokenEnv: "WEIXIN_BOT_TOKEN",
1190 tokenSet: false,
1191 apiBase: "https://ilinkai.weixin.qq.com",
1192 },
1193 dingtalk: {
1194 enabled: false,
1195 clientId: "",
1196 clientSecretEnv: "DINGTALK_CLIENT_SECRET",
1197 secretSet: false,
1198 botName: "",
1199 requireMention: true,
1200 model: "",
1201 toolApprovalMode: "",
1202 workspaceRoot: "",
1203 access: defaultBotAccess(),
1204 },
1205 connections: [],
1206 };
1207 }
1208
1209 function defaultBotAccess(): BotAccessView {
1210 return {
1211 enabled: true,
1212 allowAll: false,
1213 pairingEnabled: true,
1214 users: [],
1215 groups: [],
1216 approvers: [],
1217 admins: [],
1218 };
1219 }
1220
1221 function normalizeBotAccess(raw: any, fallback: BotAccessView = defaultBotAccess()): BotAccessView {
1222 const access = raw ?? fallback;
1223 return {
1224 enabled: access.enabled !== false,
1225 allowAll: Boolean(access.allowAll),
1226 pairingEnabled: access.pairingEnabled !== false,
1227 users: asArray(access.users),
1228 groups: asArray(access.groups),
1229 approvers: asArray(access.approvers),
1230 admins: asArray(access.admins),
1231 };
1232 }
1233
1234 function normalizeBotSettings(bot: BotSettingsView | null | undefined): BotSettingsView {
1235 const fallback = defaultBotSettings();
1236 const allowlist = bot?.allowlist ?? fallback.allowlist;
1237 const selfUserIds = bot?.selfUserIds ?? fallback.selfUserIds;
1238 const control = bot?.control ?? fallback.control;
1239 const pairing = bot?.pairing ?? fallback.pairing;
1240 const mode = bot?.feishu?.mode === "websocket" ? "websocket" : "webhook";
1241 return {
1242 ...fallback,
1243 ...bot,
1244 toolApprovalMode: normalizeBotToolApprovalMode(bot?.toolApprovalMode),
1245 maxSteps: Math.max(0, Number(bot?.maxSteps ?? fallback.maxSteps) || 0),
1246 debounceMs: Number(bot?.debounceMs) || fallback.debounceMs,
1247 queueMode: normalizeBotQueueMode(bot?.queueMode),
1248 queueCap: Math.max(0, Math.floor(Number(bot?.queueCap ?? fallback.queueCap) || 0)),
1249 queueDrop: normalizeBotQueueDrop(bot?.queueDrop),
1250 ignoreSelfMessages: bot?.ignoreSelfMessages !== false,
1251 selfUserIds: {
1252 qq: asArray(selfUserIds.qq),
1253 feishu: asArray(selfUserIds.feishu),
1254 weixin: asArray(selfUserIds.weixin),
1255 dingtalk: asArray(selfUserIds.dingtalk),
1256 },
1257 control: {
1258 enabled: Boolean(control.enabled),
1259 addr: String(control.addr ?? fallback.control.addr),
1260 tokenEnv: String(control.tokenEnv ?? fallback.control.tokenEnv),
1261 },
1262 pairing: {
1263 enabled: pairing.enabled !== false,
1264 requestTtlMinutes: Math.max(0, Math.floor(Number(pairing.requestTtlMinutes ?? fallback.pairing.requestTtlMinutes) || 0)),
1265 maxPendingPerPlatform: Math.max(0, Math.floor(Number(pairing.maxPendingPerPlatform ?? fallback.pairing.maxPendingPerPlatform) || 0)),
1266 },
1267 routes: asArray(bot?.routes).map(normalizeBotRoute).filter(botRouteHasValue),
1268 allowlist: {
1269 ...fallback.allowlist,
1270 ...allowlist,
1271 qqUsers: asArray(allowlist.qqUsers),
1272 feishuUsers: asArray(allowlist.feishuUsers),
1273 weixinUsers: asArray(allowlist.weixinUsers),
1274 qqApprovers: asArray(allowlist.qqApprovers),
1275 feishuApprovers: asArray(allowlist.feishuApprovers),
1276 weixinApprovers: asArray(allowlist.weixinApprovers),
1277 qqAdmins: asArray(allowlist.qqAdmins),
1278 feishuAdmins: asArray(allowlist.feishuAdmins),
1279 weixinAdmins: asArray(allowlist.weixinAdmins),
1280 qqGroups: asArray(allowlist.qqGroups),
1281 feishuGroups: asArray(allowlist.feishuGroups),
1282 weixinGroups: asArray(allowlist.weixinGroups),
1283 dingtalkUsers: asArray(allowlist.dingtalkUsers),
1284 dingtalkApprovers: asArray(allowlist.dingtalkApprovers),
1285 dingtalkAdmins: asArray(allowlist.dingtalkAdmins),
1286 dingtalkGroups: asArray(allowlist.dingtalkGroups),
1287 },
1288 qq: {
1289 ...fallback.qq,
1290 ...bot?.qq,
1291 model: String(bot?.qq?.model ?? fallback.qq.model).trim(),
1292 toolApprovalMode: normalizeBotToolApprovalMode(bot?.qq?.toolApprovalMode),
1293 workspaceRoot: String(bot?.qq?.workspaceRoot ?? fallback.qq.workspaceRoot).trim(),
1294 access: normalizeBotAccess(bot?.qq?.access, fallback.qq.access),
1295 },
1296 feishu: { ...fallback.feishu, ...bot?.feishu, domain: bot?.feishu?.domain === "lark" ? "lark" : "feishu", mode },
1297 weixin: { ...fallback.weixin, ...bot?.weixin },
1298 dingtalk: {
1299 ...fallback.dingtalk,
1300 ...bot?.dingtalk,
1301 toolApprovalMode: normalizeBotToolApprovalMode(bot?.dingtalk?.toolApprovalMode),
1302 access: normalizeBotAccess(bot?.dingtalk?.access, fallback.dingtalk.access),
1303 },
1304 connections: asArray(bot?.connections).map(normalizeBotConnection),
1305 };
1306 }
1307
1308 function normalizeBotConnection(raw: any) {
1309 const credential = raw?.credential ?? {};
1310 const workspaceRoot = String(raw?.workspaceRoot ?? "").trim();
1311 return {
1312 id: String(raw?.id ?? "").trim(),
1313 provider: String(raw?.provider ?? "").trim(),
1314 domain: String(raw?.domain ?? "").trim(),
1315 label: String(raw?.label ?? "").trim(),
1316 enabled: raw?.enabled !== false,
1317 status: String(raw?.status ?? "disconnected").trim(),
1318 model: String(raw?.model ?? "").trim(),
1319 toolApprovalMode: normalizeBotToolApprovalMode(raw?.toolApprovalMode, true),
1320 workspaceRoot,
1321 access: normalizeBotAccess(raw?.access),
1322 credential: {
1323 appId: String(credential.appId ?? "").trim(),
1324 appSecretEnv: String(credential.appSecretEnv ?? "").trim(),
1325 accountId: String(credential.accountId ?? "").trim(),
1326 tokenEnv: String(credential.tokenEnv ?? "").trim(),
1327 secretSet: Boolean(credential.secretSet),
1328 },
1329 sessionMappings: asArray(raw?.sessionMappings).map((item: any) => ({
1330 remoteId: String(item?.remoteId ?? "").trim(),
1331 sessionId: String(item?.sessionId ?? "").trim(),
1332 sessionSource: String(item?.sessionSource ?? "").trim(),
1333 chatType: String(item?.chatType ?? "").trim(),
1334 userId: String(item?.userId ?? "").trim(),
1335 threadId: String(item?.threadId ?? "").trim(),
1336 scope: normalizeBotMappingScope(item?.scope, item?.workspaceRoot ?? workspaceRoot),
1337 workspaceRoot: normalizeBotMappingScope(item?.scope, item?.workspaceRoot ?? workspaceRoot) === "project"
1338 ? String(item?.workspaceRoot ?? workspaceRoot).trim()
1339 : "",
1340 updatedAt: String(item?.updatedAt ?? "").trim(),
1341 })),
1342 lastError: String(raw?.lastError ?? "").trim(),
1343 createdAt: String(raw?.createdAt ?? "").trim(),
1344 updatedAt: String(raw?.updatedAt ?? "").trim(),
1345 };
1346 }
1347
1348 function normalizeBotToolApprovalMode(mode: unknown, allowEmpty = false): "read-only" | "workspace-write" | "danger-full-access" | "" {
1349 const raw = String(mode ?? "").trim().toLowerCase();
1350 if (raw === "") return allowEmpty ? "" : "workspace-write";
1351 if (raw === "read-only" || raw === "ask") return "read-only";
1352 if (raw === "workspace-write" || raw === "auto" || raw === "yolo") return "workspace-write";
1353 if (raw === "danger-full-access" || raw === "full" || raw === "full-access" || raw === "bypass") return "danger-full-access";
1354 // A non-empty unknown value is an incompatible permission contract. Keep it
1355 // fail-closed even for per-connection settings that otherwise allow inherit.
1356 return "read-only";
1357 }
1358
1359 function normalizeBotMappingScope(scope: unknown, workspaceRoot: unknown): "global" | "project" {
1360 if (String(scope ?? "").trim() === "project") return "project";
1361 return String(workspaceRoot ?? "").trim() ? "project" : "global";
1362 }
1363
1364 function normalizeStringMap(value: unknown): Record<string, string> {
1365 if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1366 const out: Record<string, string> = {};
1367 for (const [rawKey, rawValue] of Object.entries(value as Record<string, unknown>)) {
1368 const key = rawKey.trim();
1369 const val = String(rawValue ?? "").trim();
1370 if (key && val) out[key] = val;
1371 }
1372 return out;
1373 }
1374
1375 function normalizeExtraBodyMap(value: unknown): Record<string, unknown> {
1376 if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1377 const out: Record<string, unknown> = {};
1378 for (const [rawKey, rawValue] of Object.entries(value as Record<string, unknown>)) {
1379 const key = rawKey.trim();
1380 if (key && rawValue !== undefined) out[key] = rawValue;
1381 }
1382 return out;
1383 }
1384
1385 export function normalizeProviderView(p: ProviderView): ProviderView {
1386 const visionModels = asArray(p.visionModels);
1387 const modelCapabilities = asArray(p.modelCapabilities).flatMap((item) => {
1388 if (!item || typeof item !== "object") return [];
1389 const raw = item as Partial<ProviderModelCapabilityView>;
1390 const model = String(raw.model ?? "").trim();
1391 if (!model) return [];
1392 return [{
1393 automaticState: raw.automaticState,
1394 automaticSource: raw.automaticSource,
1395 imageInputEnableAllowed: raw.imageInputEnableAllowed,
1396 imageInputBlockReason: raw.imageInputBlockReason,
1397 model,
1398 inputModalities: asArray(raw.inputModalities).map(String),
1399 state: String(raw.state ?? "unknown"),
1400 source: String(raw.source ?? "unknown"),
1401 }];
1402 });
1403 const requiresKey = providerRequiresKey(p);
1404 return {
1405 ...p,
1406 name: String(p.name ?? ""),
1407 baseUrl: String(p.baseUrl ?? ""),
1408 builtIn: Boolean(p.builtIn),
1409 added: Boolean(p.added),
1410 chatUrl: p.chatUrl ?? "",
1411 requestUrl: p.requestUrl ?? "",
1412 models: asArray(p.models),
1413 visionModels,
1414 modelCapabilities,
1415 visionModelsConfigured: Boolean(p.visionModelsConfigured ?? visionModels.length > 0),
1416 visionCapability: p.visionCapability === "unsupported" || p.visionCapability === "configurable"
1417 ? p.visionCapability
1418 : undefined,
1419 modelsUrl: p.modelsUrl ?? "",
1420 headers: normalizeStringMap(p.headers),
1421 extraBody: normalizeExtraBodyMap(p.extraBody),
1422 authHeader: Boolean(p.authHeader),
1423 noProxy: Boolean(p.noProxy),
1424 reasoningProtocol: normalizeReasoningProtocol(p.reasoningProtocol),
1425 thinking: normalizeThinkingMode(p.thinking),
1426 webSearch: Boolean(p.webSearch),
1427 serverWebSearchCapability: typeof p.serverWebSearchCapability === "boolean"
1428 ? p.serverWebSearchCapability
1429 : undefined,
1430 supportedEfforts: asArray(p.supportedEfforts),
1431 modelOverrides: asArray(p.modelOverrides),
1432 recommendedUpgradeAvailable: Boolean(p.recommendedUpgradeAvailable),
1433 requiresKey,
1434 configured: providerIsConfigured({ ...p, requiresKey }),
1435 keySource: p.keySource ?? "",
1436 keySourcePath: p.keySourcePath ?? "",
1437 modelCatalogFingerprint: p.modelCatalogFingerprint ?? "",
1438 };
1439 }
1440
1441 type ProviderPresetStatus = NonNullable<ProviderPresetView["status"]> | "partial";
1442
1443 function normalizeProviderPresetStatus(status: ProviderPresetView["status"] | undefined, added: boolean): ProviderPresetStatus {
1444 if (status === "installed" || status === "installed_modified" || status === "partial" || status === "name_conflict" || status === "similar_existing") return status;
1445 return added ? "installed" : "available";
1446 }
1447
1448 function normalizeProviderPresetView(p: ProviderPresetView): ProviderPresetView {
1449 const requiresKey = Boolean(p.requiresKey ?? p.keyEnv);
1450 const configured = Boolean(p.configured ?? (!requiresKey || p.keySet));
1451 const status = normalizeProviderPresetStatus(p.status, Boolean(p.added));
1452 return {
1453 ...p,
1454 id: String(p.id ?? "").trim(),
1455 label: String(p.label ?? "").trim(),
1456 description: String(p.description ?? "").trim(),
1457 keyEnv: String(p.keyEnv ?? "").trim(),
1458 providerNames: asArray(p.providerNames),
1459 models: asArray(p.models),
1460 added: Boolean(p.added || status === "installed" || status === "installed_modified" || status === "partial" || status === "name_conflict"),
1461 status,
1462 statusProviderNames: asArray(p.statusProviderNames),
1463 missingProviderNames: asArray(p.missingProviderNames),
1464 keySet: Boolean(p.keySet),
1465 requiresKey,
1466 configured,
1467 keySource: p.keySource ?? "",
1468 keySourcePath: p.keySourcePath ?? "",
1469 };
1470 }
1471
1472 function normalizeSettingsView(view: SettingsView | null | undefined): SettingsView | null {
1473 if (!view) return null;
1474 const permissions = view.permissions ?? { mode: "ask", allow: [], ask: [], deny: [] };
1475 const sandbox = view.sandbox ?? { bash: "enforce", network: false, workspaceRoot: "", allowWrite: [], effectiveWorkspaceRoot: "", effectiveWriteRoots: [], shell: "auto", effectiveShell: "" };
1476 const network = view.network ?? {
1477 proxyMode: "auto",
1478 proxyUrl: "",
1479 noProxy: "",
1480 proxy: { type: "socks5", server: "", port: 0, username: "", password: "" },
1481 };
1482 const agent = view.agent ?? { temperature: 0, maxSteps: 0, plannerMaxSteps: 0, maxSubagentDepth: 2, maxSubagentConcurrency: 6, maxParallelWriters: 3, systemPrompt: "", reasoningLanguage: "auto", compactRatio: 0.80 };
1483 agent.plannerMaxSteps = Number.isFinite(agent.plannerMaxSteps) ? Math.max(0, Math.trunc(agent.plannerMaxSteps)) : 0;
1484 agent.maxSteps = Number.isFinite(agent.maxSteps) ? Math.max(0, Math.trunc(agent.maxSteps)) : 0;
1485 agent.maxSubagentDepth = Number.isFinite(agent.maxSubagentDepth) && agent.maxSubagentDepth <= 1 ? 1 : 2;
1486 agent.reasoningLanguage = normalizeReasoningLanguage(agent.reasoningLanguage);
1487 agent.compactRatio = Number.isFinite(agent.compactRatio) && Number(agent.compactRatio) > 0 ? Number(agent.compactRatio) : 0.80;
1488 agent.effectiveCompactRatio = Number.isFinite(agent.effectiveCompactRatio) && Number(agent.effectiveCompactRatio) > 0
1489 ? Number(agent.effectiveCompactRatio)
1490 : agent.compactRatio;
1491 agent.compactRatioOverridden = Boolean(agent.compactRatioOverridden);
1492 return {
1493 ...view,
1494 webSearchModel: view.webSearchModel || "auto",
1495 webSearchModels: asArray(view.webSearchModels).filter((ref): ref is string => typeof ref === "string"),
1496 providers: asArray(view.providers).map(normalizeProviderView),
1497 officialProviders: asArray(view.officialProviders).map(normalizeProviderView),
1498 providerPresets: asArray(view.providerPresets).map(normalizeProviderPresetView).filter((p) => p.id),
1499 providerKinds: asArray(view.providerKinds),
1500 permissions: {
1501 ...permissions,
1502 allow: asArray(permissions.allow),
1503 ask: asArray(permissions.ask),
1504 deny: asArray(permissions.deny),
1505 },
1506 sandbox: {
1507 ...sandbox,
1508 allowWrite: asArray(sandbox.allowWrite),
1509 effectiveWorkspaceRoot: String(sandbox.effectiveWorkspaceRoot ?? ""),
1510 effectiveWriteRoots: asArray(sandbox.effectiveWriteRoots),
1511 effectiveShell: String(sandbox.effectiveShell ?? sandbox.shell ?? ""),
1512 },
1513 network: {
1514 ...network,
1515 proxy: network.proxy ?? { type: "socks5", server: "", port: 0, username: "", password: "" },
1516 },
1517 agent,
1518 bot: normalizeBotSettings(view.bot),
1519 autoPlan: "off",
1520 defaultToolApprovalMode: normalizeToolApprovalMode(view.defaultToolApprovalMode),
1521 autoApproveTools: Boolean(view.autoApproveTools ?? view.bypass),
1522 bypass: Boolean(view.autoApproveTools ?? view.bypass),
1523 desktopLanguage: normalizeLangPref(view.desktopLanguage),
1524 desktopCurrency: normalizeDesktopCurrency(view.desktopCurrency),
1525 desktopTheme: normalizeThemePreference(view.desktopTheme),
1526 desktopThemeStyle: normalizeThemeStyleForTheme(view.desktopThemeStyle, normalizeThemePreference(view.desktopTheme)),
1527 desktopTerminalTheme: normalizeTerminalThemePreference(view.desktopTerminalTheme),
1528 closeBehavior: normalizeCloseBehavior(view.closeBehavior),
1529 sessionExperience: view.sessionExperience === "deep" ? "deep" : "standard",
1530 displayMode: "standard",
1531 statusBarStyle: normalizeStatusBarStyle(view.statusBarStyle),
1532 statusBarItems: normalizeStatusBarItems(view.statusBarItems),
1533 conversationWidth: normalizeConversationWidth(view.conversationWidth),
1534 checkUpdates: view.checkUpdates !== false,
1535 updaterEnabled: view.updaterEnabled === true,
1536 updateChannel: "stable",
1537 };
1538 }
1539
1540 type DesktopCurrency = "" | "CNY" | "USD";
1541
1542 function normalizeDesktopCurrency(currency: string | undefined): DesktopCurrency {
1543 return currency === "CNY" || currency === "USD" ? currency : "";
1544 }
1545
1546 type CloseBehavior = "background" | "quit";
1547
1548 function normalizeCloseBehavior(mode: string | undefined): CloseBehavior {
1549 return mode === "quit" ? "quit" : "background";
1550 }
1551
1552 type StatusBarStyle = "icon" | "text";
1553 function normalizeStatusBarStyle(style: string | undefined): StatusBarStyle {
1554 return style === "text" ? "text" : "icon";
1555 }
1556
1557 function statusBarItemLabel(id: StatusBarItemId, t: ReturnType<typeof useT>): string {
1558 switch (id) {
1559 case "workspace":
1560 return t("settings.statusBarItem.workspace");
1561 case "cache":
1562 return t("status.cacheLabel");
1563 case "cache_avg":
1564 return t("status.cacheAvgLabel");
1565 case "session_tokens":
1566 return t("status.sessionTokensLabel");
1567 case "turn_tokens":
1568 return t("status.turnTokensLabel");
1569 case "turn_tps":
1570 return t("status.tpsLabel");
1571 case "turn_output_tokens":
1572 return t("status.outputTokensLabel");
1573 case "turn_cache_tokens":
1574 return t("status.cacheTokensLabel");
1575 case "turn_cost":
1576 return t("status.turnCostLabel");
1577 case "session_turns":
1578 return t("status.sessionTurnsLabel");
1579 case "context":
1580 return t("status.ctxLabel");
1581 case "compact":
1582 return t("status.compactLabel");
1583 case "cost":
1584 return t("status.costLabel");
1585 case "balance":
1586 return t("status.balanceLabel");
1587 }
1588 }
1589
1590 function closeBehaviorLabel(mode: CloseBehavior, t: ReturnType<typeof useT>): string {
1591 return mode === "quit" ? t("settings.closeBehavior.quit") : t("settings.closeBehavior.background");
1592 }
1593
1594 function providerKindLabel(kind: string, _t: ReturnType<typeof useT>): string {
1595 return providerProtocolLabel(kind);
1596 }
1597
1598 function providerKindHint(kind: string, t: ReturnType<typeof useT>): string {
1599 if (kind === "responses" || kind === "dashscope-responses") return providerProtocolLabel(kind);
1600 return kind === "responses" ? t("settings.catalog.responsesHint") : kind === "anthropic" ? t("settings.providerProtocolAnthropicHint") : t("settings.providerProtocolOpenAIHint");
1601 }
1602
1603 function reasoningProtocolLabel(protocol: string, t: ReturnType<typeof useT>): string {
1604 switch (protocol) {
1605 case "deepseek":
1606 return t("settings.reasoningProtocol.deepseek");
1607 case "glm": return t("settings.reasoningProtocol.glm");
1608 case "kimi-k3": return t("settings.reasoningProtocol.kimiK3");
1609 case "openai":
1610 return t("settings.reasoningProtocol.openai");
1611 case "none":
1612 return t("settings.reasoningProtocol.none");
1613 default:
1614 return t("settings.reasoningProtocol.auto");
1615 }
1616 }
1617
1618 function thinkingModeLabel(mode: string, t: ReturnType<typeof useT>): string {
1619 switch (mode) {
1620 case "enabled":
1621 return t("settings.thinkingMode.enabled");
1622 case "disabled":
1623 return t("settings.thinkingMode.disabled");
1624 case "adaptive":
1625 return t("settings.thinkingMode.adaptive");
1626 default:
1627 return t("settings.thinkingMode.auto");
1628 }
1629 }
1630 function GeneralSection({ s, busy, apply, agentRunning }: SectionProps & { agentRunning: boolean }) {
1631 const { setPref } = useI18n();
1632 const t = useT();
1633 const closeBehavior = normalizeCloseBehavior(s.closeBehavior);
1634 const soundPanelId = useId();
1635 const languagePref = normalizeLangPref(s.desktopLanguage);
1636 const desktopCurrency = normalizeDesktopCurrency(s.desktopCurrency);
1637 const [genMusicPreset, setGenMusicPreset] = useState<GenerativePreset>(getGenerativePreset());
1638 const [soundPref, setSoundPref] = useState<SoundWavPref>(getSuccessPreference());
1639 const [attentionPref, setAttentionPref] = useState<SoundWavPref>(getAttentionPreference());
1640 const [notificationVolume, setNotificationVolume] = useState(getNotificationVolume);
1641 const [soundExpanded, setSoundExpanded] = useState(false);
1642 const [graphics, setGraphics] = useState<import("../lib/desktopHost").GraphicsSettingsState | null>(null);
1643 const [graphicsBusy, setGraphicsBusy] = useState(false);
1644 const [graphicsError, setGraphicsError] = useState<string | null>(null);
1645 useEffect(() => {
1646 let active = true;
1647 const host = desktopHost();
1648 if (host.kind === "electron") void host.native.graphics.get().then((value) => { if (active) setGraphics(value); }).catch(() => undefined);
1649 return () => { active = false; };
1650 }, []);
1651 const updateGraphics = (enabled: boolean) => {
1652 const host = desktopHost();
1653 if (host.kind !== "electron" || graphicsBusy) return;
1654 setGraphicsBusy(true); setGraphicsError(null);
1655 void host.native.graphics.setHardwareAcceleration(enabled).then((value) => { setGraphics(value); }).catch((error: unknown) => { setGraphicsError(error instanceof Error ? error.message : String(error)); }).finally(() => setGraphicsBusy(false));
1656 };
1657 const statusBarStyle = normalizeStatusBarStyle(s.statusBarStyle);
1658 const statusBarItems = normalizeStatusBarItems(s.statusBarItems);
1659 const soundStatus = summarizeSoundStatus(genMusicPreset, soundPref, attentionPref, notificationVolume);
1660 const applyStatusBarItems = (items: StatusBarItemId[]) => {
1661 const contentScrollTop = document.querySelector<HTMLElement>(".settings-center__content")?.scrollTop ?? 0;
1662 const navScrollTop = document.querySelector<HTMLElement>(".settings-center__nav")?.scrollTop ?? 0;
1663 const active = document.activeElement;
1664 if (active instanceof HTMLElement && active.closest(".status-bar-items-editor")) active.blur();
1665 void apply(() => app.SetStatusBarItems(items)).finally(() => {
1666 window.scrollTo(0, 0);
1667 requestAnimationFrame(() => {
1668 window.scrollTo(0, 0);
1669 const content = document.querySelector<HTMLElement>(".settings-center__content");
1670 const nav = document.querySelector<HTMLElement>(".settings-center__nav");
1671 if (content) content.scrollTop = Math.min(contentScrollTop, Math.max(0, content.scrollHeight - content.clientHeight));
1672 if (nav) nav.scrollTop = navScrollTop;
1673 });
1674 });
1675 };
1676 const setLanguage = (next: LangPref) => {
1677 setPref(next);
1678 void apply(() => app.SetDesktopLanguage(next));
1679 };
1680 return (
1681 <>
1682 <SettingsSection title={t("settings.general.sectionAppearance")} description={t("settings.general.sectionAppearanceHint")}>
1683 <SettingsField label={t("settings.language")} hint={t("settings.languageHint")} icon={<Languages size={18} />}>
1684 <SettingsOptions layout="field" className="set-seg">
1685 {LANGUAGE_PREFS.map((pref) => (
1686 <button
1687 key={pref || "auto"}
1688 className={`set-seg__btn${languagePref === pref ? " set-seg__btn--on" : ""}`}
1689 disabled={busy}
1690 onClick={() => setLanguage(pref)}
1691 >
1692 {pref === "" ? t("settings.langAuto") : pref === "zh" ? "中文" : "English"}
1693 </button>
1694 ))}
1695 </SettingsOptions>
1696 </SettingsField>
1697 <SettingsField label={t("settings.currency")} hint={t("settings.currencyHint")} icon={<CircleDollarSign size={18} />}>
1698 <SettingsOptions layout="field" className="set-seg">
1699 {(["", "CNY", "USD"] as DesktopCurrency[]).map((currency) => (
1700 <button
1701 key={currency || "auto"}
1702 className={`set-seg__btn${desktopCurrency === currency ? " set-seg__btn--on" : ""}`}
1703 disabled={busy || agentRunning}
1704 onClick={() => void apply(() => app.SetDesktopCurrency(currency))}
1705 >
1706 {currency === "" ? t("settings.currencyAuto") : currency}
1707 </button>
1708 ))}
1709 </SettingsOptions>
1710 </SettingsField>
1711 </SettingsSection>
1712
1713 <SessionExperienceSettings snapshot={s} busy={busy} apply={apply} />
1714
1715 <SettingsSection title={t("settings.general.sectionSystem")} description={t("settings.general.sectionSystemHint")}>
1716 {graphics && <SettingsField label={<span className="settings-graphics-label"><span>{t("settings.hardwareAcceleration")}</span>{graphics.restartRequired && graphics.override === "none" && <span className="settings-graphics-status">{t("settings.hardwareAccelerationRestartShort")}</span>}{graphics.override !== "none" && <span className="settings-graphics-status settings-graphics-status--warning">{t("settings.hardwareAccelerationOverride")}</span>}{graphicsError && <span className="settings-graphics-status settings-graphics-status--error" role="alert"><ErrorMessage error={graphicsError} /></span>}</span>} hint={t("settings.hardwareAccelerationHint")} icon={<Monitor size={18} />}>
1717 <div className="settings-graphics-control">
1718 <ToggleSegment value={graphics.hardwareAcceleration} disabled={graphicsBusy || !graphics.writable || graphics.override !== "none"} onChange={updateGraphics} />
1719 </div>
1720 </SettingsField>}
1721 <SettingsField label={t("settings.closeBehavior")} hint={<DesktopCloseBehaviorHint backgroundSelected={closeBehavior === "background"} hint={t("settings.closeBehaviorHint")} unavailableHint={t("settings.closeBehaviorUnavailable")} />} icon={<Power size={18} />}>
1722 <SettingsOptions layout="field" className="set-seg">
1723 {(["background", "quit"] as const).map((mode) => (
1724 <button
1725 key={mode}
1726 className={`set-seg__btn${closeBehavior === mode ? " set-seg__btn--on" : ""}`}
1727 disabled={busy}
1728 onClick={() => void apply(() => app.SetCloseBehavior(mode))}
1729 >
1730 {closeBehaviorLabel(mode, t)}
1731 </button>
1732 ))}
1733 </SettingsOptions>
1734 </SettingsField>
1735 <SettingsField label={t("settings.sound")} hint={t("settings.soundHint")} icon={<Volume2 size={18} />} stacked>
1736 <div className={`settings-sound-editor${soundExpanded ? " settings-sound-editor--expanded" : ""}`}>
1737 <div className="settings-sound-editor__summary">
1738 <span className={`settings-sound-editor__status settings-sound-editor__status--${soundStatus}`}>
1739 {t(`settings.soundStatus.${soundStatus}`)}
1740 </span>
1741 <Tooltip label={t(soundExpanded ? "settings.soundCollapse" : "settings.soundExpand")}>
1742 <button
1743 type="button"
1744 className="settings-sound-editor__toggle"
1745 aria-expanded={soundExpanded}
1746 aria-controls={soundPanelId}
1747 aria-label={t(soundExpanded ? "settings.soundCollapse" : "settings.soundExpand")}
1748 onClick={() => setSoundExpanded((open) => !open)}
1749 >
1750 {soundExpanded ? <ChevronUp size={15} aria-hidden="true" /> : <ChevronDown size={15} aria-hidden="true" />}
1751 </button>
1752 </Tooltip>
1753 </div>
1754 {soundExpanded && (
1755 <div className="settings-sound-editor__list" id={soundPanelId}>
1756 <div className="settings-sound-row">
1757 <span className="settings-sound-row__label">{t("settings.generativeMusic")}</span>
1758 <GenMusicSelect
1759 value={genMusicPreset}
1760 onChange={(next) => {
1761 setGenMusicPreset(next);
1762 setGenerativePreset(next);
1763 if (next === "off") {
1764 generativeMusic.stop();
1765 } else {
1766 if (generativeMusic.isRunning) {
1767 generativeMusic.setPreset(next);
1768 } else if (agentRunning) {
1769 generativeMusic.start(next);
1770 }
1771 generativeMusic.playPreview(next);
1772 }
1773 }}
1774 onPreview={() => { if (genMusicPreset !== "off") generativeMusic.playPreview(genMusicPreset); }}
1775 previewDisabled={genMusicPreset === "off"}
1776 />
1777 </div>
1778 <div className="settings-sound-row">
1779 <span className="settings-sound-row__label">{t("settings.notificationVolume")}</span>
1780 <NotificationVolumeSlider
1781 value={notificationVolume}
1782 onChange={(next) => setNotificationVolume(persistNotificationVolume(next))}
1783 />
1784 </div>
1785 <div className="settings-sound-row">
1786 <span className="settings-sound-row__label">{t("settings.notificationSoundSuccess")}</span>
1787 <SoundSelect
1788 value={soundPref}
1789 onChange={(next) => {
1790 setSoundPref(next);
1791 setSuccessPreference(next);
1792 playSuccessChime();
1793 }}
1794 onPreview={playSuccessChime}
1795 previewDisabled={soundPref === "off"}
1796 />
1797 </div>
1798 <div className="settings-sound-row">
1799 <span className="settings-sound-row__label">{t("settings.notificationSoundAttention")}</span>
1800 <SoundSelect
1801 value={attentionPref}
1802 onChange={(next) => {
1803 setAttentionPref(next);
1804 setAttentionPreference(next);
1805 playAttentionChime();
1806 }}
1807 onPreview={playAttentionChime}
1808 previewDisabled={attentionPref === "off"}
1809 />
1810 </div>
1811 </div>
1812 )}
1813 </div>
1814 </SettingsField>
1815 <SettingsField label={t("settings.statusBarStyle")} hint={t("settings.statusBarStyleHint")} icon={<PanelBottom size={18} />}>
1816 <SettingsOptions layout="field" className="set-seg">
1817 {(["icon", "text"] as const).map((style) => (
1818 <button
1819 key={style}
1820 className={`set-seg__btn${statusBarStyle === style ? " set-seg__btn--on" : ""}`}
1821 disabled={busy}
1822 onClick={() => void apply(() => app.SetStatusBarStyle(style))}
1823 >
1824 {t(`settings.statusBarStyle.${style}`)}
1825 </button>
1826 ))}
1827 </SettingsOptions>
1828 </SettingsField>
1829 <SettingsField label={t("settings.statusBarItems")} hint={t("settings.statusBarItemsHint")} icon={<ListChecks size={18} />} className="status-bar-items-setting" stacked>
1830 <StatusBarItemsEditor
1831 items={statusBarItems}
1832 busy={busy}
1833 onChange={applyStatusBarItems}
1834 itemLabel={(id) => statusBarItemLabel(id, t)}
1835 />
1836 </SettingsField>
1837 </SettingsSection>
1838 </>
1839 );
1840 }
1841
1842 const GENRE_OPTIONS: { value: GenerativePreset; labelKey: DictKey }[] = [
1843 { value: "off", labelKey: "settings.generativeMusic.off" },
1844 { value: "ethereal", labelKey: "settings.generativeMusic.presets.ethereal" },
1845 { value: "classic", labelKey: "settings.generativeMusic.presets.classic" },
1846 { value: "digital", labelKey: "settings.generativeMusic.presets.digital" },
1847 { value: "retro", labelKey: "settings.generativeMusic.presets.retro" },
1848 ];
1849
1850 function summarizeSoundStatus(
1851 music: GenerativePreset,
1852 success: SoundWavPref,
1853 attention: SoundWavPref,
1854 notificationVolume: number,
1855 ): "allOff" | "enabled" | "custom" {
1856 const notificationsAudible = notificationVolume > 0;
1857 const enabledCount = [
1858 music !== "off",
1859 notificationsAudible && success !== "off",
1860 notificationsAudible && attention !== "off",
1861 ].filter(Boolean).length;
1862 if (enabledCount === 0) return "allOff";
1863 if (enabledCount === 1) return "enabled";
1864 return "custom";
1865 }
1866
1867 function GenMusicSelect({
1868 value,
1869 onChange,
1870 onPreview,
1871 previewDisabled,
1872 }: {
1873 value: GenerativePreset;
1874 onChange: (v: GenerativePreset) => void;
1875 onPreview: () => void;
1876 previewDisabled?: boolean;
1877 }) {
1878 const t = useT();
1879 return (
1880 <div className="sound-select">
1881 <SettingsSelect value={value} onValueChange={next => onChange(next as GenerativePreset)}
1882 aria-label={t("settings.generativeMusic")}
1883 options={GENRE_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))} />
1884 {!previewDisabled && (
1885 <button className="chip chip--icon" type="button" title={t("settings.generativeMusicPreview")} aria-label={t("settings.generativeMusicPreview")} onClick={onPreview}>
1886 <Play size={13} aria-hidden="true" />
1887 </button>
1888 )}
1889
1890 </div>
1891 );
1892 }
1893
1894 function NetworkSection({ s, busy, apply }: SectionProps) {
1895 const t = useT();
1896 const savedNetwork = normalizeNetworkView(s.network);
1897 const [draft, setDraft] = useState<NetworkView>(savedNetwork);
1898 useEffect(() => setDraft(normalizeNetworkView(s.network)), [s.network]);
1899 const dirty = JSON.stringify(draft) !== JSON.stringify(savedNetwork);
1900 const setProxy = (next: Partial<NetworkView["proxy"]>) => {
1901 setDraft({ ...draft, proxy: { ...draft.proxy, ...next } });
1902 };
1903
1904 return (
1905 <SettingsSection
1906 title={t("settings.tab.network")}
1907
1908 >
1909 <SettingsField label={t("settings.proxyMode")}>
1910 <SettingsOptions layout="field" className="set-seg">
1911 {PROXY_MODES.map((mode) => (
1912 <button
1913 key={mode}
1914 className={`set-seg__btn${draft.proxyMode === mode ? " set-seg__btn--on" : ""}`}
1915 disabled={busy}
1916 onClick={() => setDraft({ ...draft, proxyMode: mode })}
1917 >
1918 {proxyModeLabel(mode, t)}
1919 </button>
1920 ))}
1921 </SettingsOptions>
1922 </SettingsField>
1923
1924 {draft.proxyMode === "custom" && (
1925 <>
1926 <SettingsField label={t("settings.proxyType")}>
1927 <SettingsOptions layout="field" className="set-seg">
1928 {PROXY_TYPES.map((typ) => (
1929 <button
1930 key={typ}
1931 className={`set-seg__btn${draft.proxy.type === typ ? " set-seg__btn--on" : ""}`}
1932 disabled={busy}
1933 onClick={() => setProxy({ type: typ })}
1934 >
1935 {typ.toUpperCase()}
1936 </button>
1937 ))}
1938 </SettingsOptions>
1939 </SettingsField>
1940 <SettingsField label={t("settings.proxyServer")}>
1941 <div className="settings-inline-controls">
1942 <input
1943 className="mem-input set-grow"
1944 placeholder="127.0.0.1"
1945 value={draft.proxy.server}
1946 disabled={busy || !!draft.proxyUrl.trim()}
1947 onChange={(e) => setProxy({ server: e.target.value })}
1948 />
1949 <label className="set-label">{t("settings.proxyPort")}</label>
1950 <input
1951 className="mem-input set-narrow"
1952 placeholder="7890"
1953 value={draft.proxy.port ? String(draft.proxy.port) : ""}
1954 disabled={busy || !!draft.proxyUrl.trim()}
1955 inputMode="numeric"
1956 onChange={(e) => setProxy({ port: Number(e.target.value) || 0 })}
1957 />
1958 </div>
1959 </SettingsField>
1960 <SettingsField label={t("settings.proxyUsername")}>
1961 <div className="settings-inline-controls">
1962 <input
1963 className="mem-input set-grow"
1964 value={draft.proxy.username}
1965 disabled={busy || !!draft.proxyUrl.trim()}
1966 onChange={(e) => setProxy({ username: e.target.value })}
1967 />
1968 <label className="set-label">{t("settings.proxyPassword")}</label>
1969 <input
1970 className="mem-input set-grow"
1971 type="password"
1972 value={draft.proxy.password}
1973 disabled={busy || !!draft.proxyUrl.trim()}
1974 onChange={(e) => setProxy({ password: e.target.value })}
1975 />
1976 </div>
1977 </SettingsField>
1978 <SettingsField label={t("settings.proxyUrl")} hint={t("settings.proxyUrlHint")}>
1979 <input
1980 className="mem-input set-grow"
1981 placeholder="socks5://127.0.0.1:7890"
1982 value={draft.proxyUrl}
1983 disabled={busy}
1984 onChange={(e) => setDraft({ ...draft, proxyUrl: e.target.value })}
1985 />
1986 </SettingsField>
1987 <SettingsField label={t("settings.noProxy")}>
1988 <input
1989 className="mem-input set-grow"
1990 placeholder="localhost,127.0.0.1,.local"
1991 value={draft.noProxy}
1992 disabled={busy}
1993 onChange={(e) => setDraft({ ...draft, noProxy: e.target.value })}
1994 />
1995 </SettingsField>
1996 </>
1997 )}
1998 <div className="settings-save-bar">
1999 <span role="status">{t(dirty ? "settings.models.unsaved" : "settings.models.saved")}</span>
2000 <button className="btn btn--small" disabled={busy || !dirty} onClick={() => setDraft(savedNetwork)}>{t("common.cancel")}</button>
2001 <button className="btn btn--primary btn--small" disabled={busy || !dirty} onClick={() => void apply(() => app.SetNetwork(draft))}>{t("settings.saveNetwork")}</button>
2002 </div>
2003 </SettingsSection>
2004 );
2005 }
2006
2007 const BOT_ALLOWLIST_TEXT_KEYS = [
2008 "qqUsers",
2009 "feishuUsers",
2010 "weixinUsers",
2011 "qqApprovers",
2012 "feishuApprovers",
2013 "weixinApprovers",
2014 "qqAdmins",
2015 "feishuAdmins",
2016 "weixinAdmins",
2017 "qqGroups",
2018 "feishuGroups",
2019 "weixinGroups",
2020 "dingtalkUsers",
2021 "dingtalkApprovers",
2022 "dingtalkAdmins",
2023 "dingtalkGroups",
2024 ] as const;
2025 type BotAllowlistTextKey = typeof BOT_ALLOWLIST_TEXT_KEYS[number];
2026 type BotSelfUserTextKey = keyof BotSettingsView["selfUserIds"];
2027 type BotInstallState = {
2028 target: BotInstallTarget | "";
2029 result: BotInstallStartResult | null;
2030 status: "idle" | "starting" | "showing" | "connected" | "error";
2031 timeLeft: number;
2032 message: string;
2033 };
2034 const BOT_INSTALL_TARGETS: BotInstallTarget[] = ["qq", "feishu", "lark", "weixin", "dingtalk"];
2035 const BOT_INSTALL_DEFAULT_TIMEOUT_SECONDS = 300;
2036 const BOT_INSTALL_MIN_POLL_SECONDS = 3;
2037 const DEFAULT_QQ_SECRET_ENV = "QQ_BOT_APP_SECRET";
2038 const QQ_CONNECTION_ID = "__qq_bot__";
2039 const DINGTALK_CONNECTION_ID = "__dingtalk_bot__";
2040 const BOT_PLATFORM_KEYS = ["qq", "feishu", "weixin", "dingtalk"] as const;
2041 type BotPlatformKey = typeof BOT_PLATFORM_KEYS[number];
2042 const BOT_ALLOWLIST_ROLES = ["Users", "Groups", "Approvers", "Admins"] as const;
2043 type BotAllowlistRole = typeof BOT_ALLOWLIST_ROLES[number];
2044 type BotAccessListField = "users" | "groups" | "approvers" | "admins";
2045
2046 function botAllowlistKey(platform: BotPlatformKey, role: BotAllowlistRole): BotAllowlistTextKey {
2047 return `${platform}${role}`;
2048 }
2049
2050 function botConnectionPlatform(connection: BotConnectionView): BotPlatformKey {
2051 if (connection.provider === "weixin") return "weixin";
2052 if (connection.provider === "qq") return "qq";
2053 if (connection.provider === "dingtalk") return "dingtalk";
2054 return "feishu";
2055 }
2056
2057 function botPlatformLabel(platform: BotPlatformKey, t: ReturnType<typeof useT>): string {
2058 if (platform === "qq") return "QQ";
2059 if (platform === "weixin") return t("settings.botWeixin");
2060 if (platform === "dingtalk") return t("settings.botDingtalk");
2061 return t("settings.botPlatformFeishuLark");
2062 }
2063
2064 type BotConnectionListItem =
2065 | { kind: "qq" }
2066 | { kind: "connection"; connection: BotConnectionView };
2067
2068 type BotsSectionProps = SectionProps & { initialFocus?: SettingsInitialFocus };
2069
2070 function BotsSection({ s, busy, apply, initialFocus }: BotsSectionProps) {
2071 const t = useT();
2072 const savedBot = normalizeBotSettings(s.bot);
2073 const [draft, setDraft] = useState<BotSettingsView>(savedBot);
2074 const [allowlistText, setAllowlistText] = useState<Record<BotAllowlistTextKey, string>>(() => botAllowlistTextValues(savedBot.allowlist));
2075 const [selfUserText, setSelfUserText] = useState<Record<BotSelfUserTextKey, string>>(() => botSelfUserTextValues(savedBot.selfUserIds));
2076 const [showAllPlatforms, setShowAllPlatforms] = useState(false);
2077 const [installTarget, setInstallTarget] = useState<BotInstallTarget>("qq");
2078 const [install, setInstall] = useState<BotInstallState>({ target: "qq", result: null, status: "idle", timeLeft: 0, message: "" });
2079 const [diagnostics, setDiagnostics] = useState<Record<string, BotConnectionDiagnostic | string>>({});
2080 const [testTargets, setTestTargets] = useState<Record<string, string>>({});
2081 const [connectionSecrets, setConnectionSecrets] = useState<Record<string, string>>({});
2082 const [accessText, setAccessText] = useState<Record<string, string>>({});
2083 const [qqSecretValue, setQQSecretValue] = useState("");
2084 const [dingtalkSecretValue, setDingtalkSecretValue] = useState("");
2085 const [dingtalkTesting, setDingtalkTesting] = useState(false);
2086 const [runtimePlatforms, setRuntimePlatforms] = useState<Record<string, string>>({});
2087 const [expandedConnectionId, setExpandedConnectionId] = useState("");
2088 const [advancedMode, setAdvancedMode] = useState(false);
2089 const installRef = useRef(install);
2090 const installPollTimerRef = useRef<number | null>(null);
2091 const installCountdownTimerRef = useRef<number | null>(null);
2092 const installRequestInFlightRef = useRef(false);
2093 const installAttemptRef = useRef(0);
2094 const stepConnectRef = useRef<HTMLElement | null>(null);
2095 const initialFocusHandledRef = useRef("");
2096 const refs = allRefs(s);
2097
2098 useEffect(() => {
2099 const nextBot = normalizeBotSettings(s.bot);
2100 setDraft(nextBot);
2101 setAllowlistText(botAllowlistTextValues(nextBot.allowlist));
2102 setSelfUserText(botSelfUserTextValues(nextBot.selfUserIds));
2103 setConnectionSecrets({});
2104 setAccessText({});
2105 setQQSecretValue("");
2106 setTestTargets({});
2107 }, [s.bot]);
2108 // 轮询 bot runtime 的真实平台连接状态,用于 channel 在线徽章(如钉钉黄/绿点)。
2109 useEffect(() => {
2110 let cancelled = false;
2111 const refresh = () => {
2112 if (typeof app.BotRuntimeStatus !== "function") return;
2113 void app.BotRuntimeStatus()
2114 .then((status) => {
2115 if (!cancelled) setRuntimePlatforms(status.platforms ?? {});
2116 })
2117 .catch(() => {});
2118 };
2119 refresh();
2120 const id = window.setInterval(refresh, 5000);
2121 return () => {
2122 cancelled = true;
2123 window.clearInterval(id);
2124 };
2125 }, []);
2126 const focusAccessStep = () => {
2127 if (!expandedConnectionId && connectionItems.length > 0) {
2128 const first = connectionItems[0];
2129 if (first.kind === "qq") {
2130 setInstallTarget("qq");
2131 setExpandedConnectionId(QQ_CONNECTION_ID);
2132 } else {
2133 const nextTarget = botInstallTargetForConnection(first.connection);
2134 setInstallTarget(nextTarget);
2135 setExpandedConnectionId(first.connection.id);
2136 }
2137 }
2138 window.setTimeout(() => stepConnectRef.current?.scrollIntoView({ block: "start", behavior: "smooth" }), 60);
2139 };
2140 useEffect(() => {
2141 if (initialFocus?.target !== "bot-allowlist") return;
2142 const focusKey = `${initialFocus.target}:${initialFocus.connectionId ?? ""}`;
2143 if (initialFocusHandledRef.current === focusKey) return;
2144 initialFocusHandledRef.current = focusKey;
2145 focusAccessStep();
2146 }, [initialFocus]);
2147 useEffect(() => {
2148 installRef.current = install;
2149 }, [install]);
2150 useEffect(() => {
2151 installAttemptRef.current += 1;
2152 installRequestInFlightRef.current = false;
2153 clearInstallTimers();
2154 setInstall({ target: installTarget, result: null, status: "idle", timeLeft: 0, message: "" });
2155 }, [installTarget]);
2156 useEffect(() => () => {
2157 installAttemptRef.current += 1;
2158 clearInstallTimers();
2159 }, []);
2160
2161 const setConnections = (mapper: (connections: BotConnectionView[]) => BotConnectionView[]) =>
2162 setDraft((prev) => ({ ...prev, connections: mapper(prev.connections) }));
2163 const persistBotDraft = async (nextDraft: BotSettingsView) => {
2164 const nextBot = botDraftWithDerivedGatewayState(nextDraft);
2165 setDraft(nextBot);
2166 await apply(async () => {
2167 await app.SetBotSettings(nextBot);
2168 });
2169 };
2170 const persistConnections = (mapper: (connections: BotConnectionView[]) => BotConnectionView[]) =>
2171 persistBotDraft({ ...draft, connections: mapper(draft.connections) });
2172 const updateConnection = (id: string, patch: Partial<BotConnectionView>) =>
2173 setConnections((items) => items.map((item) => item.id === id ? { ...item, ...patch } : item));
2174 const persistConnection = (id: string, patch: Partial<BotConnectionView>) =>
2175 persistConnections((items) => items.map((item) => item.id === id ? { ...item, ...patch } : item));
2176 const persistConnectionToolApprovalMode = (id: string, mode: string) => {
2177 const normalizedMode = normalizeBotToolApprovalMode(mode, true);
2178 setConnections((items) => items.map((item) => item.id === id ? { ...item, toolApprovalMode: normalizedMode } : item));
2179 void apply(() => app.SetBotConnectionToolApprovalMode(id, normalizedMode));
2180 };
2181 const updateConnectionCredential = (id: string, patch: Partial<BotConnectionView["credential"]>) =>
2182 setConnections((items) => items.map((item) => item.id === id ? { ...item, credential: { ...item.credential, ...patch } } : item));
2183 const persistConnectionCredential = (id: string, patch: Partial<BotConnectionView["credential"]>) =>
2184 persistConnections((items) => items.map((item) => item.id === id ? { ...item, credential: { ...item.credential, ...patch } } : item));
2185 const updateAllowlist = (patch: Partial<BotAllowlistView>) =>
2186 setDraft((prev) => ({ ...prev, allowlist: { ...prev.allowlist, ...patch } }));
2187 const persistAllowlist = (patch: Partial<BotAllowlistView>) =>
2188 persistBotDraft({ ...draft, allowlist: { ...draft.allowlist, ...patch } });
2189 const persistAllowlistText = (key: BotAllowlistTextKey, value: string) => {
2190 const entries = parseBotListInput(value);
2191 setAllowlistText((prev) => ({ ...prev, [key]: entries.join("\n") }));
2192 void persistAllowlist({ [key]: entries } as Partial<BotAllowlistView>);
2193 };
2194 const updateBotSettings = (patch: Partial<BotSettingsView>) =>
2195 setDraft((prev) => ({ ...prev, ...patch }));
2196 const persistBotSettings = (patch: Partial<BotSettingsView>) =>
2197 persistBotDraft({ ...draft, ...patch });
2198 const updateSelfUserText = (key: BotSelfUserTextKey, value: string) =>
2199 setSelfUserText((prev) => ({ ...prev, [key]: value }));
2200 const persistSelfUserText = (key: BotSelfUserTextKey, value: string) => {
2201 const entries = parseBotListInput(value);
2202 const nextSelfUserIds = { ...draft.selfUserIds, [key]: entries };
2203 setSelfUserText((prev) => ({ ...prev, [key]: entries.join("\n") }));
2204 void persistBotSettings({ selfUserIds: nextSelfUserIds });
2205 };
2206 const updateRoute = (index: number, patch: Partial<BotRouteView>) =>
2207 setDraft((prev) => ({
2208 ...prev,
2209 routes: prev.routes.map((route, routeIndex) => routeIndex === index ? normalizeBotRoute({ ...route, ...patch }) : route),
2210 }));
2211 const persistRoute = (index: number, patch: Partial<BotRouteView>) =>
2212 persistBotDraft({
2213 ...draft,
2214 routes: draft.routes.map((route, routeIndex) => routeIndex === index ? normalizeBotRoute({ ...route, ...patch }) : route),
2215 });
2216 const addRoute = () =>
2217 setDraft((prev) => ({ ...prev, routes: [...prev.routes, emptyBotRoute()] }));
2218 const removeRoute = (index: number) =>
2219 void persistBotDraft({ ...draft, routes: draft.routes.filter((_, routeIndex) => routeIndex !== index) });
2220 const updateQQ = (patch: Partial<BotSettingsView["qq"]>) =>
2221 setDraft((prev) => ({ ...prev, qq: { ...prev.qq, ...patch } }));
2222 const persistQQ = (patch: Partial<BotSettingsView["qq"]>) =>
2223 persistBotDraft({ ...draft, qq: { ...draft.qq, ...patch } });
2224 const updateQQAccess = (patch: Partial<BotAccessView>) =>
2225 updateQQ({ access: normalizeBotAccess({ ...draft.qq.access, ...patch }) });
2226 const persistQQAccess = (patch: Partial<BotAccessView>) =>
2227 persistQQ({ access: normalizeBotAccess({ ...draft.qq.access, ...patch }) });
2228 const updateDingtalk = (patch: Partial<BotSettingsView["dingtalk"]>) =>
2229 setDraft((prev) => ({ ...prev, dingtalk: { ...prev.dingtalk, ...patch } }));
2230 const persistDingtalk = (patch: Partial<BotSettingsView["dingtalk"]>) =>
2231 persistBotDraft({ ...draft, dingtalk: { ...draft.dingtalk, ...patch } });
2232 const updateDingtalkAccess = (patch: Partial<BotAccessView>) =>
2233 updateDingtalk({ access: normalizeBotAccess({ ...draft.dingtalk.access, ...patch }) });
2234 const persistDingtalkAccess = (patch: Partial<BotAccessView>) =>
2235 persistDingtalk({ access: normalizeBotAccess({ ...draft.dingtalk.access, ...patch }) });
2236 const updateConnectionAccess = (id: string, patch: Partial<BotAccessView>) =>
2237 setConnections((items) => items.map((item) => item.id === id ? { ...item, access: normalizeBotAccess({ ...item.access, ...patch }) } : item));
2238 const persistConnectionAccess = (connection: BotConnectionView, patch: Partial<BotAccessView>) =>
2239 persistConnection(connection.id, { access: normalizeBotAccess({ ...connection.access, ...patch }) });
2240 const accessTextKey = (id: string, field: BotAccessListField) => `${id}:${field}`;
2241 const accessListText = (id: string, access: BotAccessView, field: BotAccessListField) =>
2242 accessText[accessTextKey(id, field)] ?? access[field].join("\n");
2243 const setAccessListText = (id: string, field: BotAccessListField, value: string) =>
2244 setAccessText((prev) => ({ ...prev, [accessTextKey(id, field)]: value }));
2245 const persistAccessListText = (
2246 id: string,
2247 access: BotAccessView,
2248 field: BotAccessListField,
2249 value: string,
2250 persistAccess: (patch: Partial<BotAccessView>) => void,
2251 ) => {
2252 const entries = parseBotListInput(value);
2253 setAccessText((prev) => ({ ...prev, [accessTextKey(id, field)]: entries.join("\n") }));
2254 persistAccess({ ...access, [field]: entries } as Partial<BotAccessView>);
2255 };
2256 const removeConnection = async (connection: BotConnectionView) => {
2257 const nextDraft = botDraftWithDerivedGatewayState({
2258 ...draft,
2259 connections: draft.connections.filter((item) => item.id !== connection.id),
2260 });
2261 await apply(async () => {
2262 await app.SetBotSettings(nextDraft);
2263 });
2264 };
2265 const installQrURL = install.result?.url ?? "";
2266 const installQrIsImage = installQrURL.startsWith("data:image/");
2267 const isQQInstallTarget = installTarget === "qq";
2268 const isDingtalkInstallTarget = installTarget === "dingtalk";
2269 const selectedInstallLabel = botTargetLabel(installTarget, t);
2270 const installUserCode = install.result?.userCode && installTarget !== "weixin" ? formatInstallUserCode(install.result.userCode) : "";
2271 const qqSecretEnv = draft.qq.appSecretEnv.trim() || DEFAULT_QQ_SECRET_ENV;
2272 const qqConfigured = draft.qq.enabled && draft.qq.appId.trim() && qqSecretEnv && draft.qq.secretSet;
2273 const qqCanEnableAccess = botAccessReady(draft.qq.access);
2274 const qqCanSaveAndEnable = Boolean(draft.qq.appId.trim() && qqSecretEnv && (draft.qq.secretSet || qqSecretValue.trim()) && qqCanEnableAccess);
2275 const qqAdded = qqBotAdded(draft.qq);
2276 const nativeRuntimeAvailable = desktopHost().kind !== "none";
2277 const browserPreviewBotConfigured = !nativeRuntimeAvailable && (qqAdded || draft.connections.length > 0);
2278 const qqOnline = qqConfigured && nativeRuntimeAvailable;
2279 const dingtalkSecretEnv = draft.dingtalk.clientSecretEnv.trim() || "DINGTALK_CLIENT_SECRET";
2280 const dingtalkConfigured = Boolean(draft.dingtalk.enabled && draft.dingtalk.clientId.trim() && dingtalkSecretEnv && draft.dingtalk.secretSet);
2281 // 保存按钮仅在用户输入了新的密钥后才可点;已保存过密钥但没有新输入时置灰。
2282 const dingtalkCanSaveAndEnable = Boolean(draft.dingtalk.clientId.trim() && dingtalkSecretEnv && dingtalkSecretValue.trim());
2283 const dingtalkOnline = runtimePlatforms["dingtalk"] === "running" || runtimePlatforms["dingtalk"] === "degraded";
2284 const connectionItems: BotConnectionListItem[] = [
2285 ...(qqAdded ? [{ kind: "qq" as const }] : []),
2286 ...draft.connections.map((connection) => ({ kind: "connection" as const, connection })),
2287 ];
2288 const selectedInstallConnection = isQQInstallTarget || isDingtalkInstallTarget ? undefined : draft.connections.find((connection) => botInstallTargetMatchesConnection(installTarget, connection));
2289 const selectedChannelConfigured = isQQInstallTarget ? qqAdded : isDingtalkInstallTarget ? dingtalkConfigured : Boolean(selectedInstallConnection);
2290 const routeConnectionOptions = [
2291 ...(qqAdded ? [{ id: "qq", label: "QQ" }] : []),
2292 ...draft.connections.map((connection) => ({
2293 id: connection.id || [connection.provider, connection.domain].filter(Boolean).join("-"),
2294 label: connection.label || botConnectionLabel(connection, t),
2295 })).filter((item) => item.id),
2296 ];
2297
2298 const saveBot = () => app.SetBotSettings(botDraftWithDerivedGatewayState(draft));
2299 function clearInstallTimers() {
2300 if (installPollTimerRef.current !== null) {
2301 window.clearTimeout(installPollTimerRef.current);
2302 installPollTimerRef.current = null;
2303 }
2304 if (installCountdownTimerRef.current !== null) {
2305 window.clearInterval(installCountdownTimerRef.current);
2306 installCountdownTimerRef.current = null;
2307 }
2308 }
2309 function beginInstallCountdown(attempt: number) {
2310 if (installCountdownTimerRef.current !== null) {
2311 window.clearInterval(installCountdownTimerRef.current);
2312 }
2313 installCountdownTimerRef.current = window.setInterval(() => {
2314 setInstall((prev) => {
2315 if (installAttemptRef.current !== attempt || prev.status !== "showing") return prev;
2316 return { ...prev, timeLeft: Math.max(0, prev.timeLeft - 1) };
2317 });
2318 }, 1000);
2319 }
2320 function scheduleInstallPoll(attempt: number, interval: number) {
2321 if (installPollTimerRef.current !== null) {
2322 window.clearTimeout(installPollTimerRef.current);
2323 }
2324 installPollTimerRef.current = window.setTimeout(() => void pollInstall(attempt), Math.max(interval || BOT_INSTALL_MIN_POLL_SECONDS, BOT_INSTALL_MIN_POLL_SECONDS) * 1000);
2325 }
2326 const startInstall = async (target: BotOfficialInstallTarget) => {
2327 if (installRequestInFlightRef.current) return;
2328 const existing = draft.connections.find((connection) => botInstallTargetMatchesConnection(target, connection));
2329 if (existing) {
2330 installAttemptRef.current += 1;
2331 clearInstallTimers();
2332 setInstall({ target, result: null, status: "connected", timeLeft: 0, message: t("settings.botInstallAlreadyConnected", { provider: botTargetLabel(target, t) }) });
2333 return;
2334 }
2335 clearInstallTimers();
2336 const attempt = installAttemptRef.current + 1;
2337 installAttemptRef.current = attempt;
2338 installRequestInFlightRef.current = true;
2339 setInstall({ target, result: null, status: "starting", timeLeft: 0, message: t("settings.botInstallStarting") });
2340 const provider = target === "weixin" ? "weixin" : "feishu";
2341 const domain = target === "lark" ? "lark" : target === "weixin" ? "weixin" : "feishu";
2342 try {
2343 const result = await app.StartBotConnectionInstall(provider, domain);
2344 if (installAttemptRef.current !== attempt) return;
2345 if (!result.ok) {
2346 setInstall({ target, result, status: "error", timeLeft: 0, message: result.message || t("settings.botInstallFailed") });
2347 return;
2348 }
2349 const timeLeft = result.expireIn > 0 ? result.expireIn : BOT_INSTALL_DEFAULT_TIMEOUT_SECONDS;
2350 setInstall({ target, result, status: "showing", timeLeft, message: result.message || t("settings.botInstallScanHint") });
2351 beginInstallCountdown(attempt);
2352 scheduleInstallPoll(attempt, result.interval);
2353 } catch (err) {
2354 if (installAttemptRef.current === attempt) {
2355 setInstall({ target, result: null, status: "error", timeLeft: 0, message: err instanceof Error ? err.message : t("settings.botInstallFailed") });
2356 }
2357 } finally {
2358 if (installAttemptRef.current === attempt) {
2359 installRequestInFlightRef.current = false;
2360 }
2361 }
2362 };
2363 const pollInstall = async (attempt = installAttemptRef.current) => {
2364 const current = installRef.current;
2365 if (installAttemptRef.current !== attempt || current.status !== "showing" || !current.result?.installId || !current.target) return;
2366 const poll = await app.PollBotConnectionInstall(current.result.installId);
2367 if (installAttemptRef.current !== attempt) return;
2368 if (poll.done) {
2369 clearInstallTimers();
2370 setDraft((prev) => ({
2371 ...prev,
2372 enabled: true,
2373 connections: [...prev.connections.filter((c) => c.id !== poll.connection.id), poll.connection],
2374 }));
2375 setInstall((prev) => ({ ...prev, status: "connected", timeLeft: 0, message: poll.message || t("settings.botInstallConnected") }));
2376 return;
2377 }
2378 if (poll.error) {
2379 clearInstallTimers();
2380 setInstall((prev) => ({ ...prev, status: "error", timeLeft: 0, message: poll.error }));
2381 return;
2382 }
2383 setInstall((prev) => ({ ...prev, message: poll.message || t("settings.botInstallWaiting") }));
2384 scheduleInstallPoll(attempt, current.result.interval);
2385 };
2386 useEffect(() => {
2387 if (install.status !== "showing" || install.timeLeft > 0) return;
2388 installAttemptRef.current += 1;
2389 clearInstallTimers();
2390 setInstall((prev) => prev.status === "showing" ? { ...prev, status: "error", message: t("settings.botInstallExpired") } : prev);
2391 }, [install.status, install.timeLeft]);
2392 const diagnoseConnection = async (id: string) => {
2393 const diag = await app.DiagnoseBotConnection(id);
2394 setDiagnostics((prev) => ({ ...prev, [id]: diag }));
2395 return diag;
2396 };
2397 const testConnection = async (connection: BotConnectionView) => {
2398 const target = (testTargets[connection.id] ?? firstConnectionRemote(connection)).trim();
2399 const diag = await app.TestBotConnection(connection.id, target);
2400 setDiagnostics((prev) => ({ ...prev, [connection.id]: diag }));
2401 if (diag.messageId && target) {
2402 const updatedAt = new Date().toISOString();
2403 await persistConnections((items) => items.map((item) => {
2404 if (item.id !== connection.id) return item;
2405 const scope = connection.workspaceRoot ? "project" : "global";
2406 const matchesTestMapping = (mapping: BotConnectionView["sessionMappings"][number]) =>
2407 mapping.remoteId === target &&
2408 !mapping.chatType.trim() &&
2409 !mapping.userId.trim() &&
2410 !mapping.threadId.trim();
2411 const sessionMappings = [
2412 ...item.sessionMappings.filter((mapping) => !matchesTestMapping(mapping)),
2413 { remoteId: target, sessionId: "", sessionSource: "", chatType: "", userId: "", threadId: "", scope, workspaceRoot: scope === "project" ? connection.workspaceRoot : "", updatedAt },
2414 ];
2415 return { ...item, sessionMappings, updatedAt };
2416 }));
2417 }
2418 };
2419 const testDingtalkBot = async () => {
2420 setDingtalkTesting(true);
2421 try {
2422 const diag = await app.TestDingtalkBot();
2423 setDiagnostics((prev) => ({ ...prev, dingtalk: diag }));
2424 } finally {
2425 setDingtalkTesting(false);
2426 }
2427 };
2428 const ensureReportableDiagnostic = async (connection: BotConnectionView) => {
2429 return diagnoseConnection(connection.id);
2430 };
2431 const copyConnectionDiagnostic = async (connection: BotConnectionView) => {
2432 const diag = await ensureReportableDiagnostic(connection);
2433 if (!diag.reportDetail) return;
2434 try {
2435 await navigator.clipboard.writeText(diag.reportDetail);
2436 setDiagnostics((prev) => ({ ...prev, [connection.id]: { ...diag, message: t("settings.botDiagnosticCopied") } }));
2437 } catch (err) {
2438 setDiagnostics((prev) => ({
2439 ...prev,
2440 [connection.id]: { ...diag, status: "error", message: err instanceof Error ? err.message : t("settings.botDiagnosticCopyFailed") },
2441 }));
2442 }
2443 };
2444 const reportConnectionDiagnostic = async (connection: BotConnectionView) => {
2445 const diag = await ensureReportableDiagnostic(connection);
2446 if (!diag.reportDetail) return;
2447 try {
2448 await app.ReportCrash(diag.reportKind || "bot", diag.reportDetail);
2449 setDiagnostics((prev) => ({ ...prev, [connection.id]: { ...diag, status: "ok", message: t("settings.botDiagnosticReportSent") } }));
2450 } catch (err) {
2451 setDiagnostics((prev) => ({
2452 ...prev,
2453 [connection.id]: { ...diag, status: "error", message: err instanceof Error ? err.message : t("settings.botDiagnosticReportFailed") },
2454 }));
2455 }
2456 };
2457 const saveConnectionSecret = async (connection: BotConnectionView) => {
2458 const env = botConnectionSecretEnv(connection).trim();
2459 const value = (connectionSecrets[connection.id] ?? "").trim();
2460 if (!env || !value) return;
2461 await apply(async () => {
2462 await saveBot();
2463 await app.SetBotSecret(env, value);
2464 });
2465 setConnectionSecrets((prev) => ({ ...prev, [connection.id]: "" }));
2466 };
2467 const clearConnectionSecret = async (connection: BotConnectionView) => {
2468 const env = botConnectionSecretEnv(connection).trim();
2469 if (!env) return;
2470 await apply(async () => {
2471 await saveBot();
2472 await app.ClearBotSecret(env);
2473 });
2474 };
2475 const clearQQSecret = async () => {
2476 const env = draft.qq.appSecretEnv.trim() || DEFAULT_QQ_SECRET_ENV;
2477 if (!env) return;
2478 await apply(async () => {
2479 await saveBot();
2480 await app.ClearBotSecret(env);
2481 });
2482 setQQSecretValue("");
2483 };
2484 const clearDingtalkSecret = async () => {
2485 const env = draft.dingtalk.clientSecretEnv.trim() || "DINGTALK_CLIENT_SECRET";
2486 if (!env) return;
2487 await apply(async () => {
2488 await saveBot();
2489 await app.ClearBotSecret(env);
2490 });
2491 setDingtalkSecretValue("");
2492 };
2493 const focusQQAccessSettings = () => {
2494 setDiagnostics((prev) => ({ ...prev, [QQ_CONNECTION_ID]: t("settings.botQQAccessRequired") }));
2495 setExpandedConnectionId(QQ_CONNECTION_ID);
2496 window.setTimeout(() => stepConnectRef.current?.scrollIntoView({ block: "start", behavior: "smooth" }), 60);
2497 };
2498 const saveQQAndEnable = async () => {
2499 if (!qqCanEnableAccess) {
2500 focusQQAccessSettings();
2501 return;
2502 }
2503 const env = draft.qq.appSecretEnv.trim() || DEFAULT_QQ_SECRET_ENV;
2504 const secret = qqSecretValue.trim();
2505 const nextDraft = botDraftWithDerivedGatewayState({
2506 ...draft,
2507 qq: {
2508 ...draft.qq,
2509 enabled: true,
2510 appId: draft.qq.appId.trim(),
2511 appSecretEnv: env,
2512 secretSet: draft.qq.secretSet || Boolean(secret),
2513 },
2514 });
2515 await apply(async () => {
2516 await app.SetBotSettings(nextDraft);
2517 if (secret) await app.SetBotSecret(env, secret);
2518 });
2519 setDraft(nextDraft);
2520 setQQSecretValue("");
2521 };
2522 const saveDingtalkAndEnable = async () => {
2523 const env = draft.dingtalk.clientSecretEnv.trim() || "DINGTALK_CLIENT_SECRET";
2524 const secret = dingtalkSecretValue.trim();
2525 const nextDraft = botDraftWithDerivedGatewayState({
2526 ...draft,
2527 dingtalk: {
2528 ...draft.dingtalk,
2529 enabled: true,
2530 clientId: draft.dingtalk.clientId.trim(),
2531 clientSecretEnv: env,
2532 secretSet: draft.dingtalk.secretSet || Boolean(secret),
2533 },
2534 });
2535 await apply(async () => {
2536 await app.SetBotSettings(nextDraft);
2537 if (secret) await app.SetBotSecret(env, secret);
2538 });
2539 setDraft(nextDraft);
2540 setDingtalkSecretValue("");
2541 };
2542 const removeDingtalkBot = async () => {
2543 const env = draft.dingtalk.clientSecretEnv.trim() || "DINGTALK_CLIENT_SECRET";
2544 const nextDraft = botDraftWithDerivedGatewayState({
2545 ...draft,
2546 dingtalk: { enabled: false, clientId: "", clientSecretEnv: "DINGTALK_CLIENT_SECRET", secretSet: false, botName: "", requireMention: true, model: "", toolApprovalMode: "", workspaceRoot: "", access: defaultBotAccess() },
2547 });
2548 await apply(async () => {
2549 await app.SetBotSettings(nextDraft);
2550 if (draft.dingtalk.secretSet) await app.ClearBotSecret(env);
2551 });
2552 setDraft(nextDraft);
2553 };
2554 const removeQQBot = async () => {
2555 const env = draft.qq.appSecretEnv.trim() || DEFAULT_QQ_SECRET_ENV;
2556 const nextDraft = botDraftWithDerivedGatewayState({
2557 ...draft,
2558 qq: { enabled: false, appId: "", appSecretEnv: DEFAULT_QQ_SECRET_ENV, secretSet: false, sandbox: false, model: "", toolApprovalMode: "workspace-write", workspaceRoot: "", access: defaultBotAccess() },
2559 });
2560 await apply(async () => {
2561 await app.SetBotSettings(nextDraft);
2562 if (draft.qq.secretSet) await app.ClearBotSecret(env);
2563 });
2564 setDraft(nextDraft);
2565 setQQSecretValue("");
2566 setExpandedConnectionId("");
2567 };
2568 const selectedQQ = isQQInstallTarget && qqAdded;
2569 const selectedConnection = isQQInstallTarget || isDingtalkInstallTarget ? null : selectedInstallConnection ?? null;
2570 const selectedDingtalk = isDingtalkInstallTarget && dingtalkConfigured;
2571 const selectedDiagnostic = selectedConnection ? diagnostics[selectedConnection.id] : undefined;
2572 const selectedDiagnosticDetail = diagnosticReportDetail(selectedDiagnostic);
2573 const selectedConnectionRemote = selectedConnection ? firstConnectionRemote(selectedConnection) : "";
2574 const selectedConnectionToolApprovalMode = selectedConnection ? normalizeBotToolApprovalMode(selectedConnection.toolApprovalMode) : "workspace-write";
2575 const simpleAccessMode = draft.allowlist.allowAll ? "everyone" : "trusted";
2576 const connectedPlatforms = new Set<BotPlatformKey>();
2577 if (qqAdded) connectedPlatforms.add("qq");
2578 for (const connection of draft.connections) connectedPlatforms.add(botConnectionPlatform(connection));
2579 const platformHasAllowlistText = (platform: BotPlatformKey) =>
2580 BOT_ALLOWLIST_ROLES.some((role) => allowlistText[botAllowlistKey(platform, role)].trim());
2581 const visibleAccessPlatforms = BOT_PLATFORM_KEYS.filter((platform) =>
2582 showAllPlatforms || connectedPlatforms.size === 0 || connectedPlatforms.has(platform) || platformHasAllowlistText(platform));
2583 const platformFilterAvailable = connectedPlatforms.size > 0 &&
2584 BOT_PLATFORM_KEYS.some((platform) => !connectedPlatforms.has(platform) && !platformHasAllowlistText(platform));
2585 const botChannelConnectionForTarget = (target: BotInstallTarget) =>
2586 target === "qq" || target === "dingtalk" ? null : draft.connections.find((connection) => botInstallTargetMatchesConnection(target, connection));
2587 const botChannelIsConfigured = (target: BotInstallTarget) =>
2588 target === "qq" ? qqAdded : target === "dingtalk" ? dingtalkConfigured : Boolean(botChannelConnectionForTarget(target));
2589 const openBotChannel = (target: BotInstallTarget) => {
2590 setInstallTarget(target);
2591 const connection = botChannelConnectionForTarget(target);
2592 setExpandedConnectionId(target === "qq" && qqAdded ? QQ_CONNECTION_ID : connection?.id || "");
2593 };
2594 const setSimpleAccessMode = (mode: "trusted" | "everyone") => {
2595 const patch = mode === "everyone"
2596 ? { enabled: false, allowAll: true }
2597 : { enabled: true, allowAll: false };
2598 updateAllowlist(patch);
2599 void persistAllowlist(patch);
2600 };
2601 const renderBotAccessSection = (
2602 id: string,
2603 access: BotAccessView,
2604 updateAccess: (patch: Partial<BotAccessView>) => void,
2605 persistAccess: (patch: Partial<BotAccessView>) => void,
2606 ) => {
2607 const mode = access.allowAll ? "everyone" : "trusted";
2608 const setMode = (nextMode: "trusted" | "everyone") => {
2609 const patch = nextMode === "everyone"
2610 ? { enabled: false, allowAll: true }
2611 : { enabled: true, allowAll: false };
2612 updateAccess(patch);
2613 persistAccess(patch);
2614 };
2615 return (
2616 <section className="bot-detail-section bot-detail-section--access">
2617 <div>
2618 <div className="bot-detail-section__head">{t("settings.botAccessControl")}</div>
2619 <p>{access.allowAll ? t("settings.botSimpleAccessEveryoneSummary") : t("settings.botSimpleAccessTrustedSummary", { count: botAccessEntryCount(access) })}</p>
2620 </div>
2621 <div className="bot-choice-grid bot-choice-grid--access">
2622 <button
2623 type="button"
2624 className={`bot-choice-card${mode === "trusted" ? " bot-choice-card--active" : ""}`}
2625 disabled={busy}
2626 onClick={() => setMode("trusted")}
2627 >
2628 <strong>{t("settings.botAccessTrusted")}</strong>
2629 <span>{t("settings.botAccessTrustedHint")}</span>
2630 </button>
2631 <button
2632 type="button"
2633 className={`bot-choice-card${mode === "everyone" ? " bot-choice-card--active" : ""}`}
2634 disabled={busy}
2635 onClick={() => setMode("everyone")}
2636 >
2637 <strong>{t("settings.botAccessEveryone")}</strong>
2638 <span>{t("settings.botAccessEveryoneHint")}</span>
2639 </button>
2640 </div>
2641 <div className="bot-pairing-row">
2642 <div>
2643 <strong>{t("settings.botAccessPairing")}</strong>
2644 <span>{t("settings.botAccessPairingHint")}</span>
2645 </div>
2646 <ToggleSegment
2647 value={access.pairingEnabled}
2648 disabled={busy}
2649 onChange={(pairingEnabled) => {
2650 updateAccess({ pairingEnabled });
2651 persistAccess({ pairingEnabled });
2652 }}
2653 />
2654 </div>
2655 {access.allowAll ? (
2656 <div className="bot-access-panel__warning">{t("settings.botAllowAllWarn")}</div>
2657 ) : (
2658 <div className="bot-access-platforms bot-access-platforms--single">
2659 <div className="bot-access-platform">
2660 <BotListInput
2661 label={t("settings.botListUsers")}
2662 value={accessListText(id, access, "users")}
2663 disabled={busy}
2664 placeholder={t("settings.botListPlaceholder")}
2665 onChange={(value) => setAccessListText(id, "users", value)}
2666 onBlur={(value) => persistAccessListText(id, access, "users", value, persistAccess)}
2667 />
2668 <BotListInput
2669 label={t("settings.botListGroups")}
2670 value={accessListText(id, access, "groups")}
2671 disabled={busy}
2672 placeholder={t("settings.botListPlaceholder")}
2673 onChange={(value) => setAccessListText(id, "groups", value)}
2674 onBlur={(value) => persistAccessListText(id, access, "groups", value, persistAccess)}
2675 />
2676 </div>
2677 </div>
2678 )}
2679 <details className="bot-access-panel bot-simple-roles">
2680 <summary className="bot-access-panel__summary">
2681 <span>
2682 <strong>{t("settings.botRoleAccess")}</strong>
2683 <small>{t("settings.botRoleAccessHint")}</small>
2684 </span>
2685 <ChevronDown className="bot-access-panel__chevron" size={16} aria-hidden="true" />
2686 </summary>
2687 <div className="bot-access-panel__body">
2688 <div className="bot-access-platforms bot-access-platforms--single">
2689 <div className="bot-access-platform">
2690 <BotListInput
2691 label={t("settings.botListApprovers")}
2692 value={accessListText(id, access, "approvers")}
2693 disabled={busy || access.allowAll}
2694 placeholder={t("settings.botListPlaceholder")}
2695 onChange={(value) => setAccessListText(id, "approvers", value)}
2696 onBlur={(value) => persistAccessListText(id, access, "approvers", value, persistAccess)}
2697 />
2698 <BotListInput
2699 label={t("settings.botListAdmins")}
2700 value={accessListText(id, access, "admins")}
2701 disabled={busy || access.allowAll}
2702 placeholder={t("settings.botListPlaceholder")}
2703 onChange={(value) => setAccessListText(id, "admins", value)}
2704 onBlur={(value) => persistAccessListText(id, access, "admins", value, persistAccess)}
2705 />
2706 </div>
2707 </div>
2708 </div>
2709 </details>
2710 </section>
2711 );
2712 };
2713 const qqDetailCard = (
2714 <article className="bot-detail-card" aria-labelledby="bot-detail-title">
2715 <div className="bot-detail-card__head">
2716 <div className="bot-detail-card__identity">
2717 <div className="bot-detail-card__title" id="bot-detail-title">
2718 QQ Bot
2719 <span className="badge badge--neutral">QQ</span>
2720 <span className={`badge ${qqOnline ? "badge--project" : qqConfigured ? "badge--feedback" : "badge--feedback"}`}>
2721 {qqOnline ? t("settings.botConnectionConnected") : qqConfigured ? t("settings.botConnectionConfigured") : t("settings.botConnectionDisconnected")}
2722 </span>
2723 </div>
2724 <div className="bot-detail-card__desc">{t("settings.botAutoSaveHint")}</div>
2725 </div>
2726 </div>
2727
2728 <section className="bot-detail-section">
2729 <div className="bot-detail-section__head">{t("settings.botConnectionSummary")}</div>
2730 <div className="bot-detail-summary">
2731 <div>
2732 <span>{t("settings.botConnectionColumnChannel")}</span>
2733 <strong>QQ</strong>
2734 </div>
2735 <div>
2736 <span>{t("settings.botConnectionColumnRemote")}</span>
2737 <code title={draft.qq.appId.trim() || undefined}>{draft.qq.appId.trim() || "—"}</code>
2738 </div>
2739 <div>
2740 <span>{t("settings.botConnectionColumnScope")}</span>
2741 <strong>{t("settings.botScopeGlobal")}</strong>
2742 </div>
2743 <div>
2744 <span>{t("settings.botConnectionColumnStatus")}</span>
2745 <strong>{qqOnline ? t("settings.botConnectionConnected") : qqConfigured ? t("settings.botConnectionConfigured") : t("settings.botConnectionDisconnected")}</strong>
2746 </div>
2747 </div>
2748 </section>
2749
2750 <section className="bot-detail-section bot-detail-section--runtime-primary">
2751 <SettingsField label={t("settings.botEnableBot")} hint={t("settings.botGatewayEnabled")}>
2752 <ToggleSegment
2753 value={draft.qq.enabled}
2754 disabled={busy}
2755 onChange={(enabled) => {
2756 if (enabled && !qqCanEnableAccess) {
2757 focusQQAccessSettings();
2758 return;
2759 }
2760 updateQQ({ enabled });
2761 void persistQQ({ enabled });
2762 }}
2763 />
2764 </SettingsField>
2765 <SettingsField label={t("settings.botToolApprovalMode")} hint={t("settings.botToolApprovalModeHint")}>
2766 <SettingsOptions className="provider-add-segmented" role="group" aria-label={t("settings.botToolApprovalMode")}>
2767 {TOOL_APPROVAL_MODES.map((mode) => (
2768 <button
2769 key={mode}
2770 type="button"
2771 className={normalizeBotToolApprovalMode(draft.qq.toolApprovalMode) === mode ? "provider-add-segmented__item provider-add-segmented__item--active" : "provider-add-segmented__item"}
2772 disabled={busy}
2773 onClick={() => void persistQQ({ toolApprovalMode: mode })}
2774 >
2775 {t(`settings.botToolApprovalMode.${mode}` as DictKey)}
2776 </button>
2777 ))}
2778 </SettingsOptions>
2779 </SettingsField>
2780 <SettingsField label={t("settings.botChannelModel")} hint={t("settings.botChannelModelHint")}>
2781 <ModelPicker
2782 s={s}
2783 refs={refs}
2784 value={toRef(draft.qq.model, s)}
2785 disabled={busy}
2786 emptyOptionLabel={t("settings.botChannelModelAuto")}
2787 emptyOptionHint={settingsModelMeta(s, t)}
2788 onPick={(model) => void persistQQ({ model })}
2789 />
2790 </SettingsField>
2791 </section>
2792
2793 {renderBotAccessSection(QQ_CONNECTION_ID, draft.qq.access, updateQQAccess, (patch) => void persistQQAccess(patch))}
2794
2795 <section className="bot-detail-section">
2796 <div className="bot-detail-section__head">{t("settings.botRuntimeSettings")}</div>
2797 <SettingsField label={t("settings.botSandbox")} hint={t("settings.botInstallQQHint")}>
2798 <ToggleSegment
2799 value={draft.qq.sandbox}
2800 disabled={busy}
2801 onLabel={t("settings.toggleOn")}
2802 offLabel={t("settings.toggleOff")}
2803 onChange={(sandbox) => {
2804 updateQQ({ sandbox });
2805 void persistQQ({ sandbox });
2806 }}
2807 />
2808 </SettingsField>
2809 <SettingsField label={t("settings.botWorkspaceRoot")} hint={t("settings.botWorkspaceRootHint")}>
2810 <input
2811 className="mem-input"
2812 value={draft.qq.workspaceRoot}
2813 disabled={busy}
2814 placeholder={t("settings.botWorkspaceRootPlaceholder")}
2815 spellCheck={false}
2816 onChange={(event) => updateQQ({ workspaceRoot: event.target.value })}
2817 onBlur={(event) => void persistQQ({ workspaceRoot: event.currentTarget.value })}
2818 />
2819 </SettingsField>
2820 </section>
2821
2822 <section className="bot-detail-section">
2823 <div className="bot-detail-section__head">{t("settings.botCredential")}</div>
2824 <div className="bot-credential-stack">
2825 <div className="bot-credential-line">
2826 <span>{draft.qq.appId.trim() ? t("settings.botCredentialApp", { value: draft.qq.appId.trim() }) : t("settings.botCredentialConfigured")}</span>
2827 <strong>{draft.qq.secretSet ? t("settings.botSecretSet") : t("settings.botSecretMissing")}</strong>
2828 </div>
2829 <div className="bot-secret-row bot-secret-row--qq">
2830 <input
2831 className="mem-input"
2832 value={draft.qq.appId}
2833 disabled={busy}
2834 placeholder={t("settings.botAppId")}
2835 spellCheck={false}
2836 aria-label={t("settings.botAppId")}
2837 onChange={(event) => updateQQ({ appId: event.target.value })}
2838 onBlur={(event) => void persistQQ({ appId: event.currentTarget.value })}
2839 />
2840 <input
2841 className="mem-input"
2842 value={draft.qq.appSecretEnv || DEFAULT_QQ_SECRET_ENV}
2843 disabled={busy}
2844 placeholder={DEFAULT_QQ_SECRET_ENV}
2845 spellCheck={false}
2846 aria-label={t("settings.botSecretEnv")}
2847 onChange={(event) => updateQQ({ appSecretEnv: event.target.value })}
2848 onBlur={(event) => void persistQQ({ appSecretEnv: event.currentTarget.value || DEFAULT_QQ_SECRET_ENV })}
2849 />
2850 <input
2851 className="mem-input"
2852 type="password"
2853 value={qqSecretValue}
2854 disabled={busy}
2855 placeholder={draft.qq.secretSet ? t("settings.botSecretReplace") : t("settings.botSecretPaste")}
2856 aria-label={t("settings.botSecretValue")}
2857 onChange={(event) => setQQSecretValue(event.target.value)}
2858 />
2859 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !qqCanSaveAndEnable} onClick={() => void saveQQAndEnable()}>
2860 {draft.qq.secretSet ? t("settings.saveKey") : t("settings.botSaveAndEnable")}
2861 </button>
2862 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !draft.qq.secretSet} onClick={() => void clearQQSecret()}>
2863 {t("settings.clearKey")}
2864 </button>
2865 </div>
2866 {!qqCanEnableAccess ? <div className="bot-connect-panel__hint bot-connect-panel__hint--warning">{t("settings.botQQAccessRequired")}</div> : null}
2867 </div>
2868 </section>
2869
2870 <section className="bot-detail-section bot-detail-section--danger">
2871 <div>
2872 <div className="bot-detail-section__head">{t("settings.botDangerZone")}</div>
2873 <p>{t("settings.deleteBotHint")}</p>
2874 </div>
2875 <InlineConfirmButton
2876 label={t("settings.deleteBot")}
2877 confirmLabel={t("settings.confirmDeleteBot")}
2878 cancelLabel={t("common.cancel")}
2879 disabled={busy}
2880 danger
2881 onConfirm={() => void removeQQBot()}
2882 />
2883 </section>
2884 </article>
2885 );
2886
2887 const dingtalkDetailCard = (
2888 <article className="bot-detail-card" aria-labelledby="bot-detail-title">
2889 <div className="bot-detail-card__head">
2890 <div className="bot-detail-card__identity">
2891 <div className="bot-detail-card__title" id="bot-detail-title">
2892 DingTalk Bot
2893 <span className="badge badge--neutral">DingTalk</span>
2894 <span className={`badge ${dingtalkOnline ? "badge--project" : dingtalkConfigured ? "badge--feedback" : "badge--feedback"}`}>
2895 {dingtalkOnline ? t("settings.botConnectionConnected") : dingtalkConfigured ? t("settings.botConnectionConfigured") : t("settings.botConnectionDisconnected")}
2896 </span>
2897 </div>
2898 <div className="bot-detail-card__desc">{t("settings.botAutoSaveHint")}</div>
2899 </div>
2900 <div className="bot-detail-card__actions">
2901 <button type="button" className="btn btn--small" disabled={busy || !dingtalkConfigured || dingtalkTesting} onClick={() => void testDingtalkBot()}>
2902 {dingtalkTesting ? t("settings.botTesting") : t("settings.botTest")}
2903 </button>
2904 </div>
2905 </div>
2906
2907 <section className="bot-detail-section">
2908 <div className="bot-detail-section__head">{t("settings.botConnectionSummary")}</div>
2909 <div className="bot-detail-summary">
2910 <div>
2911 <span>{t("settings.botConnectionColumnChannel")}</span>
2912 <strong>DingTalk</strong>
2913 </div>
2914 <div>
2915 <span>{t("settings.botDingtalkClientId")}</span>
2916 <code title={draft.dingtalk.clientId.trim() || undefined}>{draft.dingtalk.clientId.trim() || "—"}</code>
2917 </div>
2918 <div>
2919 <span>{t("settings.botConnectionColumnScope")}</span>
2920 <strong>{t("settings.botScopeGlobal")}</strong>
2921 </div>
2922 <div>
2923 <span>{t("settings.botConnectionColumnStatus")}</span>
2924 <strong>{dingtalkOnline ? t("settings.botConnectionConnected") : dingtalkConfigured ? t("settings.botConnectionConfigured") : t("settings.botConnectionDisconnected")}</strong>
2925 </div>
2926 </div>
2927 </section>
2928
2929 <section className="bot-detail-section bot-detail-section--runtime-primary">
2930 <SettingsField label={t("settings.botEnableBot")} hint={t("settings.botGatewayEnabled")}>
2931 <ToggleSegment
2932 value={draft.dingtalk.enabled}
2933 disabled={busy}
2934 onChange={(enabled) => {
2935 updateDingtalk({ enabled });
2936 void persistDingtalk({ enabled });
2937 }}
2938 />
2939 </SettingsField>
2940 <SettingsField label={t("settings.botToolApprovalMode")} hint={t("settings.botToolApprovalModeHint")}>
2941 <SettingsOptions className="provider-add-segmented" role="group" aria-label={t("settings.botToolApprovalMode")}>
2942 {TOOL_APPROVAL_MODES.map((mode) => (
2943 <button
2944 key={mode}
2945 type="button"
2946 className={normalizeBotToolApprovalMode(draft.dingtalk.toolApprovalMode, true) === mode ? "provider-add-segmented__item provider-add-segmented__item--active" : "provider-add-segmented__item"}
2947 disabled={busy}
2948 onClick={() => {
2949 updateDingtalk({ toolApprovalMode: mode });
2950 // 热更新运行中 gateway,不重启 bot runtime(避免面板跳变)。
2951 void app.SetBotDingtalkToolApprovalMode(mode).catch((e) => {
2952 console.warn("set dingtalk approval mode failed", e);
2953 });
2954 }}
2955 >
2956 {t(`settings.botToolApprovalMode.${mode}` as DictKey)}
2957 </button>
2958 ))}
2959 </SettingsOptions>
2960 </SettingsField>
2961 <SettingsField label={t("settings.botChannelModel")} hint={t("settings.botChannelModelHint")}>
2962 <ModelPicker
2963 s={s}
2964 refs={refs}
2965 value={toRef(draft.dingtalk.model, s)}
2966 disabled={busy}
2967 emptyOptionLabel={t("settings.botChannelModelAuto")}
2968 emptyOptionHint={settingsModelMeta(s, t)}
2969 onPick={(model) => {
2970 updateDingtalk({ model });
2971 void persistDingtalk({ model });
2972 }}
2973 />
2974 </SettingsField>
2975 </section>
2976
2977 {renderBotAccessSection(DINGTALK_CONNECTION_ID, draft.dingtalk.access, updateDingtalkAccess, (patch) => void persistDingtalkAccess(patch))}
2978
2979 <section className="bot-detail-section">
2980 <div className="bot-detail-section__head">{t("settings.botRuntimeSettings")}</div>
2981 <SettingsField label={t("settings.botWorkspaceRoot")} hint={t("settings.botWorkspaceRootHint")}>
2982 <input
2983 className="mem-input"
2984 value={draft.dingtalk.workspaceRoot}
2985 disabled={busy}
2986 placeholder={t("settings.botWorkspaceRootPlaceholder")}
2987 spellCheck={false}
2988 onChange={(event) => updateDingtalk({ workspaceRoot: event.target.value })}
2989 onBlur={(event) => void persistDingtalk({ workspaceRoot: event.currentTarget.value })}
2990 />
2991 </SettingsField>
2992 <SettingsField label={t("settings.botDingtalkBotName")} hint={t("settings.botDingtalkBotNameHint")}>
2993 <input
2994 className="mem-input"
2995 value={draft.dingtalk.botName}
2996 disabled={busy}
2997 placeholder={t("settings.botDingtalkBotName")}
2998 spellCheck={false}
2999 onChange={(event) => updateDingtalk({ botName: event.target.value })}
3000 onBlur={(event) => void persistDingtalk({ botName: event.currentTarget.value })}
3001 />
3002 </SettingsField>
3003 <SettingsField label={t("settings.botDingtalkRequireMention")} hint={t("settings.botDingtalkRequireMentionHint")}>
3004 <ToggleSegment
3005 value={draft.dingtalk.requireMention}
3006 disabled={busy}
3007 onLabel={t("settings.toggleOn")}
3008 offLabel={t("settings.toggleOff")}
3009 onChange={(requireMention) => {
3010 updateDingtalk({ requireMention });
3011 void persistDingtalk({ requireMention });
3012 }}
3013 />
3014 </SettingsField>
3015 </section>
3016
3017 <section className="bot-detail-section">
3018 <div className="bot-detail-section__head">{t("settings.botCredential")}</div>
3019 <div className="bot-credential-stack">
3020 <div className="bot-credential-line">
3021 <span>{draft.dingtalk.clientId.trim() ? t("settings.botCredentialClientId", { value: draft.dingtalk.clientId.trim() }) : t("settings.botCredentialConfigured")}</span>
3022 <strong>{draft.dingtalk.secretSet ? t("settings.botSecretSet") : t("settings.botSecretMissing")}</strong>
3023 </div>
3024 <div className="bot-secret-row bot-secret-row--dingtalk">
3025 <input
3026 className="mem-input"
3027 value={draft.dingtalk.clientId}
3028 disabled={busy}
3029 placeholder={t("settings.botDingtalkClientId")}
3030 spellCheck={false}
3031 aria-label={t("settings.botDingtalkClientId")}
3032 onChange={(event) => updateDingtalk({ clientId: event.target.value })}
3033 onBlur={(event) => void persistDingtalk({ clientId: event.currentTarget.value })}
3034 />
3035 <input
3036 className="mem-input"
3037 value={draft.dingtalk.clientSecretEnv || "DINGTALK_CLIENT_SECRET"}
3038 disabled={busy}
3039 placeholder="DINGTALK_CLIENT_SECRET"
3040 spellCheck={false}
3041 aria-label={t("settings.botSecretEnv")}
3042 onChange={(event) => updateDingtalk({ clientSecretEnv: event.target.value })}
3043 onBlur={(event) => void persistDingtalk({ clientSecretEnv: event.currentTarget.value || "DINGTALK_CLIENT_SECRET" })}
3044 />
3045 <input
3046 className="mem-input"
3047 type="password"
3048 value={dingtalkSecretValue}
3049 disabled={busy}
3050 placeholder={draft.dingtalk.secretSet ? t("settings.botSecretReplace") : t("settings.botSecretPaste")}
3051 aria-label={t("settings.botDingtalkClientSecret")}
3052 onChange={(event) => setDingtalkSecretValue(event.target.value)}
3053 />
3054 <div className="bot-secret-row__actions">
3055 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !dingtalkCanSaveAndEnable} onClick={() => void saveDingtalkAndEnable()}>
3056 {draft.dingtalk.secretSet ? t("settings.saveKey") : t("settings.botSaveAndEnable")}
3057 </button>
3058 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !draft.dingtalk.secretSet} onClick={() => void clearDingtalkSecret()}>
3059 {t("settings.clearKey")}
3060 </button>
3061 </div>
3062 </div>
3063 </div>
3064 </section>
3065
3066 {diagnosticMessage(diagnostics.dingtalk) ? (
3067 <div className="bot-detail-notice">
3068 <span>{diagnosticMessage(diagnostics.dingtalk)}</span>
3069 </div>
3070 ) : null}
3071
3072 <section className="bot-detail-section bot-detail-section--danger">
3073 <div>
3074 <div className="bot-detail-section__head">{t("settings.botDangerZone")}</div>
3075 <p>{t("settings.deleteBotHint")}</p>
3076 </div>
3077 <InlineConfirmButton
3078 label={t("settings.deleteBot")}
3079 confirmLabel={t("settings.confirmDeleteBot")}
3080 cancelLabel={t("common.cancel")}
3081 disabled={busy}
3082 danger
3083 onConfirm={() => void removeDingtalkBot()}
3084 />
3085 </section>
3086 </article>
3087 );
3088
3089 const connectionDetailCard = selectedConnection ? (
3090 <article className="bot-detail-card" aria-labelledby="bot-detail-title">
3091 <div className="bot-detail-card__head">
3092 <div className="bot-detail-card__identity">
3093 <div className="bot-detail-card__title" id="bot-detail-title">
3094 {selectedConnection.label || botConnectionLabel(selectedConnection, t)}
3095 <span className="badge badge--neutral">{botConnectionLabel(selectedConnection, t)}</span>
3096 <span className={`badge ${selectedConnection.status === "connected" ? "badge--project" : "badge--feedback"}`}>
3097 {selectedConnection.status === "connected" ? t("settings.botConnectionConnected") : selectedConnection.status || t("settings.botConnectionDisconnected")}
3098 </span>
3099 </div>
3100 <div className="bot-detail-card__desc">{t("settings.botAutoSaveHint")}</div>
3101 </div>
3102 <div className="bot-detail-card__actions">
3103 <button type="button" className="btn btn--small" disabled={busy} onClick={() => void diagnoseConnection(selectedConnection.id)}>
3104 {t("settings.botDiagnose")}
3105 </button>
3106 {(selectedConnection.provider === "feishu" || selectedConnection.provider === "weixin") ? (
3107 <button type="button" className="btn btn--small" disabled={busy || !selectedConnectionRemote} onClick={() => void testConnection(selectedConnection)}>
3108 {t("settings.botTest")}
3109 </button>
3110 ) : null}
3111 </div>
3112 </div>
3113
3114 {diagnosticMessage(selectedDiagnostic) ? (
3115 <div className="bot-detail-notice">
3116 <span>{diagnosticMessage(selectedDiagnostic)}</span>
3117 {selectedDiagnosticDetail ? (
3118 <div className="bot-diagnostic-actions">
3119 <button type="button" className="btn btn--secondary btn--small" disabled={busy} onClick={() => void copyConnectionDiagnostic(selectedConnection)}>
3120 <Clipboard aria-hidden="true" />
3121 {t("settings.botCopyDiagnostic")}
3122 </button>
3123 <button type="button" className="btn btn--primary btn--small" disabled={busy} onClick={() => void reportConnectionDiagnostic(selectedConnection)}>
3124 <Send aria-hidden="true" />
3125 {t("settings.botSendDiagnostic")}
3126 </button>
3127 <small>{t("settings.botDiagnosticPrivacy")}</small>
3128 </div>
3129 ) : null}
3130 </div>
3131 ) : null}
3132
3133 <section className="bot-detail-section">
3134 <div className="bot-detail-section__head">{t("settings.botConnectionSummary")}</div>
3135 <div className="bot-detail-summary">
3136 <div>
3137 <span>{t("settings.botConnectionColumnChannel")}</span>
3138 <strong>{botConnectionLabel(selectedConnection, t)}</strong>
3139 </div>
3140 <div>
3141 <span>{t("settings.botConnectionColumnRemote")}</span>
3142 <code title={selectedConnectionRemote || undefined}>{selectedConnectionRemote || "—"}</code>
3143 </div>
3144 <div>
3145 <span>{t("settings.botConnectionColumnScope")}</span>
3146 <strong>{botConnectionScopeLabel(selectedConnection, t)}</strong>
3147 </div>
3148 <div>
3149 <span>{t("settings.botConnectionColumnStatus")}</span>
3150 <strong>{selectedConnection.status === "connected" ? t("settings.botConnectionConnected") : selectedConnection.status || t("settings.botConnectionDisconnected")}</strong>
3151 </div>
3152 </div>
3153 </section>
3154
3155 <section className="bot-detail-section bot-detail-section--runtime-primary">
3156 <SettingsField label={t("settings.botEnableBot")} hint={t("settings.botGatewayEnabled")}>
3157 <ToggleSegment
3158 value={selectedConnection.enabled}
3159 disabled={busy}
3160 onChange={(enabled) => void persistConnection(selectedConnection.id, { enabled })}
3161 />
3162 </SettingsField>
3163 <SettingsField label={t("settings.botToolApprovalMode")} hint={t("settings.botToolApprovalModeHint")}>
3164 <SettingsOptions className="provider-add-segmented" role="group" aria-label={t("settings.botToolApprovalMode")}>
3165 {TOOL_APPROVAL_MODES.map((mode) => (
3166 <button
3167 key={mode}
3168 type="button"
3169 className={selectedConnectionToolApprovalMode === mode ? "provider-add-segmented__item provider-add-segmented__item--active" : "provider-add-segmented__item"}
3170 disabled={busy}
3171 onClick={() => persistConnectionToolApprovalMode(selectedConnection.id, mode)}
3172 >
3173 {t(`settings.botToolApprovalMode.${mode}` as DictKey)}
3174 </button>
3175 ))}
3176 </SettingsOptions>
3177 </SettingsField>
3178 <SettingsField label={t("settings.botChannelModel")} hint={t("settings.botChannelModelHint")}>
3179 <ModelPicker
3180 s={s}
3181 refs={refs}
3182 value={toRef(selectedConnection.model, s)}
3183 disabled={busy}
3184 emptyOptionLabel={t("settings.botChannelModelAuto")}
3185 emptyOptionHint={settingsModelMeta(s, t)}
3186 onPick={(model) => void persistConnection(selectedConnection.id, { model })}
3187 />
3188 </SettingsField>
3189 </section>
3190
3191 {renderBotAccessSection(
3192 selectedConnection.id,
3193 selectedConnection.access,
3194 (patch) => updateConnectionAccess(selectedConnection.id, patch),
3195 (patch) => void persistConnectionAccess(selectedConnection, patch),
3196 )}
3197
3198 <section className="bot-detail-section">
3199 <div className="bot-detail-section__head">{t("settings.botRuntimeSettings")}</div>
3200 <SettingsField label={t("settings.botWorkspaceRoot")} hint={t("settings.botWorkspaceRootHint")}>
3201 <input
3202 className="mem-input"
3203 value={selectedConnection.workspaceRoot}
3204 disabled={busy}
3205 placeholder={t("settings.botWorkspaceRootPlaceholder")}
3206 spellCheck={false}
3207 onChange={(event) => updateConnection(selectedConnection.id, { workspaceRoot: event.target.value })}
3208 onBlur={(event) => void persistConnection(selectedConnection.id, { workspaceRoot: event.currentTarget.value })}
3209 />
3210 </SettingsField>
3211 </section>
3212
3213 <section className="bot-detail-section">
3214 <div className="bot-detail-section__head">{t("settings.botCredential")}</div>
3215 <div className="bot-credential-stack">
3216 <div className="bot-credential-line">
3217 <span>{botConnectionCredentialSummary(selectedConnection, t)}</span>
3218 <strong>{selectedConnection.credential.secretSet ? t("settings.botSecretSet") : t("settings.botSecretMissing")}</strong>
3219 </div>
3220 {botConnectionSecretEnv(selectedConnection) ? (
3221 <div className="bot-secret-row">
3222 <input
3223 className="mem-input"
3224 value={botConnectionSecretEnv(selectedConnection)}
3225 disabled={busy}
3226 spellCheck={false}
3227 onChange={(event) => updateConnectionCredential(selectedConnection.id, botConnectionSecretPatch(selectedConnection, event.target.value))}
3228 onBlur={(event) => void persistConnectionCredential(selectedConnection.id, botConnectionSecretPatch(selectedConnection, event.currentTarget.value))}
3229 />
3230 <input
3231 className="mem-input"
3232 type="password"
3233 value={connectionSecrets[selectedConnection.id] ?? ""}
3234 disabled={busy}
3235 placeholder={selectedConnection.credential.secretSet ? t("settings.botSecretReplace") : t("settings.botSecretPaste")}
3236 onChange={(event) => setConnectionSecrets((prev) => ({ ...prev, [selectedConnection.id]: event.target.value }))}
3237 />
3238 <div className="bot-secret-row__actions">
3239 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !(connectionSecrets[selectedConnection.id] ?? "").trim()} onClick={() => void saveConnectionSecret(selectedConnection)}>
3240 {t("settings.saveKey")}
3241 </button>
3242 <button type="button" className="btn btn--secondary btn--small" disabled={busy || !selectedConnection.credential.secretSet} onClick={() => void clearConnectionSecret(selectedConnection)}>
3243 {t("settings.clearKey")}
3244 </button>
3245 </div>
3246 </div>
3247 ) : null}
3248 </div>
3249 </section>
3250
3251 <section className="bot-detail-section bot-detail-section--danger">
3252 <div>
3253 <div className="bot-detail-section__head">{t("settings.botDangerZone")}</div>
3254 <p>{t("settings.deleteBotHint")}</p>
3255 </div>
3256 <InlineConfirmButton
3257 label={t("settings.deleteBot")}
3258 confirmLabel={t("settings.confirmDeleteBot")}
3259 cancelLabel={t("common.cancel")}
3260 disabled={busy}
3261 danger
3262 onConfirm={() => removeConnection(selectedConnection)}
3263 />
3264 </section>
3265 </article>
3266 ) : null;
3267
3268 const installPanelContent = (
3269 <>
3270 {isQQInstallTarget ? (
3271 <div className="bot-connect-panel bot-connect-panel--manual bot-connect-panel--qq">
3272 <div className="bot-connect-panel__body">
3273 <div className="bot-qq-simple__head">
3274 <div>
3275 <strong>{selectedInstallLabel}</strong>
3276 <p>{t("settings.botInstallManualQQ")}</p>
3277 </div>
3278 <span className={`bot-qq-simple__status${qqConfigured ? " bot-qq-simple__status--ready" : ""}`}>
3279 {qqConfigured ? <CheckCircle2 aria-hidden="true" /> : <KeyRound aria-hidden="true" />}
3280 {draft.qq.secretSet ? t("settings.botSecretSet") : t("settings.botSecretMissing")}
3281 </span>
3282 </div>
3283 <div className="bot-manual-form bot-manual-form--qq">
3284 <div className="bot-card-field">
3285 <span>{t("settings.botAppId")}</span>
3286 <div>
3287 <input
3288 className="mem-input"
3289 aria-label={t("settings.botAppId")}
3290 value={draft.qq.appId}
3291 disabled={busy}
3292 spellCheck={false}
3293 onChange={(event) => updateQQ({ appId: event.target.value })}
3294 onBlur={(event) => void persistQQ({ appId: event.currentTarget.value })}
3295 />
3296 </div>
3297 </div>
3298 <div className="bot-card-field">
3299 <span>{t("settings.botAppSecret")}</span>
3300 <div>
3301 <input
3302 className="mem-input"
3303 type="password"
3304 value={qqSecretValue}
3305 disabled={busy}
3306 placeholder={draft.qq.secretSet ? t("settings.botSecretSavedOptional") : t("settings.botSecretPaste")}
3307 spellCheck={false}
3308 aria-label={t("settings.botSecretValue")}
3309 onChange={(event) => setQQSecretValue(event.target.value)}
3310 />
3311 </div>
3312 </div>
3313 <div className="bot-qq-simple__actions">
3314 <button type="button" className="btn btn--primary btn--small" disabled={busy || !qqCanSaveAndEnable} onClick={() => void saveQQAndEnable()}>
3315 {t("settings.botSaveAndEnable")}
3316 </button>
3317 </div>
3318 {!qqCanEnableAccess ? <div className="bot-connect-panel__hint bot-connect-panel__hint--warning">{t("settings.botQQAccessRequired")}</div> : null}
3319 </div>
3320 </div>
3321 </div>
3322 ) : isDingtalkInstallTarget ? (
3323 <div className="bot-connect-panel bot-connect-panel--manual bot-connect-panel--dingtalk">
3324 <div className="bot-connect-panel__body">
3325 <div className="bot-qq-simple__head">
3326 <div>
3327 <strong>{selectedInstallLabel}</strong>
3328 <p>{t("settings.botInstallManualDingtalk")}</p>
3329 </div>
3330 <span className={`bot-qq-simple__status${dingtalkConfigured ? " bot-qq-simple__status--ready" : ""}`}>
3331 {dingtalkConfigured ? <CheckCircle2 aria-hidden="true" /> : <KeyRound aria-hidden="true" />}
3332 {draft.dingtalk.secretSet ? t("settings.botSecretSet") : t("settings.botSecretMissing")}
3333 </span>
3334 </div>
3335 <div className="bot-manual-form bot-manual-form--dingtalk">
3336 <div className="bot-card-field">
3337 <span>{t("settings.botDingtalkClientId")}</span>
3338 <div>
3339 <input
3340 className="mem-input"
3341 aria-label={t("settings.botDingtalkClientId")}
3342 value={draft.dingtalk.clientId}
3343 disabled={busy}
3344 spellCheck={false}
3345 onChange={(event) => updateDingtalk({ clientId: event.target.value })}
3346 onBlur={(event) => void persistDingtalk({ clientId: event.currentTarget.value })}
3347 />
3348 </div>
3349 </div>
3350 <div className="bot-card-field">
3351 <span>{t("settings.botDingtalkClientSecret")}</span>
3352 <div>
3353 <input
3354 className="mem-input"
3355 type="password"
3356 value={dingtalkSecretValue}
3357 disabled={busy}
3358 placeholder={draft.dingtalk.secretSet ? t("settings.botSecretSavedOptional") : t("settings.botSecretPaste")}
3359 spellCheck={false}
3360 aria-label={t("settings.botDingtalkClientSecret")}
3361 onChange={(event) => setDingtalkSecretValue(event.target.value)}
3362 />
3363 </div>
3364 </div>
3365 <div className="bot-card-field">
3366 <span>{t("settings.botDingtalkBotName")}</span>
3367 <div>
3368 <input
3369 className="mem-input"
3370 aria-label={t("settings.botDingtalkBotName")}
3371 value={draft.dingtalk.botName}
3372 disabled={busy}
3373 spellCheck={false}
3374 onChange={(event) => updateDingtalk({ botName: event.target.value })}
3375 onBlur={(event) => void persistDingtalk({ botName: event.currentTarget.value })}
3376 />
3377 </div>
3378 </div>
3379 <div className="bot-qq-simple__actions">
3380 <button type="button" className="btn btn--primary btn--small" disabled={busy || !dingtalkCanSaveAndEnable} onClick={() => void saveDingtalkAndEnable()}>
3381 {t("settings.botSaveAndEnable")}
3382 </button>
3383 </div>
3384 </div>
3385 </div>
3386 </div>
3387 ) : (
3388 <div className="bot-connect-panel bot-connect-panel--phone">
3389 <div className="bot-connect-panel__qr">
3390 {selectedInstallConnection ? (
3391 <div className="bot-connect-panel__state bot-connect-panel__state--success">
3392 <CheckCircle2 aria-hidden="true" />
3393 </div>
3394 ) : install.status === "showing" && installQrURL ? (
3395 installQrIsImage ? (
3396 <img src={installQrURL} alt={t("settings.botInstallQrAlt")} />
3397 ) : (
3398 <Suspense fallback={<div className="bot-connect-panel__state"><QrCode aria-hidden="true" /></div>}>
3399 <QRCodeSVG className="bot-connect-panel__qr-code" value={installQrURL} size={196} marginSize={1} />
3400 </Suspense>
3401 )
3402 ) : install.status === "starting" ? (
3403 <div className="bot-connect-panel__state">
3404 <Loader2 className="bot-spin" aria-hidden="true" />
3405 <span>{t("settings.botInstallStarting")}</span>
3406 </div>
3407 ) : install.status === "error" ? (
3408 <div className="bot-connect-panel__state bot-connect-panel__state--error">
3409 <RefreshCw aria-hidden="true" />
3410 </div>
3411 ) : (
3412 <div className="bot-connect-panel__state">
3413 <QrCode aria-hidden="true" />
3414 </div>
3415 )}
3416 </div>
3417 <div className="bot-connect-panel__body">
3418 <strong>{selectedInstallLabel}</strong>
3419 <p>
3420 {selectedInstallConnection
3421 ? t("settings.botInstallAlreadyConnected", { provider: selectedInstallLabel })
3422 : install.status === "error" ? <ErrorMessage error={install.message || t("settings.botInstallFailed")} /> : install.message || botTargetHint(installTarget, t)}
3423 </p>
3424 {install.status === "showing" && install.timeLeft > 0 ? (
3425 <span className="bot-connect-panel__timer">{t("settings.botInstallTimeLeft", { time: formatInstallTimeLeft(install.timeLeft) })}</span>
3426 ) : null}
3427 {installUserCode ? <code>{installUserCode}</code> : null}
3428 <div className="bot-connect-panel__actions">
3429 {!selectedInstallConnection && install.status !== "showing" && install.status !== "starting" ? (
3430 <button type="button" className="btn btn--primary btn--small" disabled={busy} onClick={() => void startInstall(installTarget)}>
3431 {install.status === "error" ? <RefreshCw aria-hidden="true" /> : <QrCode aria-hidden="true" />}
3432 {install.status === "error" ? t("settings.botInstallRetry") : t("settings.botInstallGenerate")}
3433 </button>
3434 ) : null}
3435 {install.status === "showing" ? (
3436 <button type="button" className="btn btn--secondary btn--small" disabled={busy} onClick={() => void pollInstall()}>
3437 {t("settings.botInstallCheck")}
3438 </button>
3439 ) : null}
3440 {selectedInstallConnection ? (
3441 <button type="button" className="btn btn--secondary btn--small" disabled={busy} onClick={() => void diagnoseConnection(selectedInstallConnection.id)}>
3442 {t("settings.botDiagnose")}
3443 </button>
3444 ) : null}
3445 </div>
3446 </div>
3447 </div>
3448 )}
3449 </>
3450 );
3451
3452 const botManager = (
3453 <section ref={stepConnectRef} id="bot-step-connect" className="bot-channel-manager-card">
3454 {browserPreviewBotConfigured ? (
3455 <div className="bot-connection-warning">{t("settings.botBrowserPreviewWarning")}</div>
3456 ) : null}
3457 <div className="bot-channel-manager">
3458 <div className="bot-channel-tabs" role="tablist" aria-label={t("settings.botChannelTabsLabel")}>
3459 {BOT_INSTALL_TARGETS.map((target) => {
3460 const configured = botChannelIsConfigured(target);
3461 const connected = target === "qq" ? qqOnline : botChannelConnectionForTarget(target)?.status === "connected";
3462 return (
3463 <button
3464 key={target}
3465 type="button"
3466 role="tab"
3467 aria-selected={installTarget === target}
3468 className={`bot-channel-tab${installTarget === target ? " bot-channel-tab--active" : ""}`}
3469 disabled={busy || install.status === "starting"}
3470 onClick={() => openBotChannel(target)}
3471 >
3472 <span className="bot-channel-tab__icon" aria-hidden="true">
3473 {(() => {
3474 const Icon = CHANNEL_ICONS[target];
3475 return <Icon className="bot-channel-tab__brand" />;
3476 })()}
3477 </span>
3478 <span className="bot-channel-tab__text">
3479 <strong>{botTargetLabel(target, t)}</strong>
3480 <small>{botTargetHint(target, t)}</small>
3481 </span>
3482 <span className={`bot-channel-tab__dot${connected ? " bot-channel-tab__dot--online" : configured ? " bot-channel-tab__dot--configured" : ""}`} />
3483 </button>
3484 );
3485 })}
3486 </div>
3487 <div className="bot-channel-manager__detail" role="tabpanel" aria-label={selectedInstallLabel}>
3488 {!selectedChannelConfigured ? (
3489 <article className="bot-channel-setup-card">
3490 {installPanelContent}
3491 </article>
3492 ) : selectedQQ ? (
3493 qqDetailCard
3494 ) : selectedDingtalk ? (
3495 dingtalkDetailCard
3496 ) : selectedConnection ? (
3497 connectionDetailCard
3498 ) : (
3499 <div className="bot-manager__empty">{t("settings.botSelectBotHint")}</div>
3500 )}
3501 </div>
3502 </div>
3503 </section>
3504 );
3505
3506 return (
3507 <div className="bot-phone-connect">
3508 {botManager}
3509
3510 <details
3511 id="bot-advanced-settings"
3512 className="bot-simple-advanced"
3513 open={advancedMode}
3514 onToggle={(event) => {
3515 const nextOpen = event.currentTarget.open;
3516 setAdvancedMode((current) => current === nextOpen ? current : nextOpen);
3517 }}
3518 >
3519 <summary className="bot-simple-advanced__summary">
3520 <span>
3521 <strong>{t("settings.botShowAdvancedSettings")}</strong>
3522 <small>{t("settings.botAdvancedSettingsHint")}</small>
3523 </span>
3524 <span className="bot-simple-advanced__toggle">
3525 {advancedMode ? t("common.collapse") : t("common.expand")}
3526 <ChevronDown aria-hidden="true" size={16} />
3527 </span>
3528 </summary>
3529 <div className="bot-simple-advanced__body">
3530 <details className="bot-access-panel bot-global-access-panel">
3531 <summary className="bot-access-panel__summary">
3532 <span>
3533 <strong>{t("settings.botGlobalAllowlist")}</strong>
3534 <small>{t("settings.botGlobalAllowlistHint")}</small>
3535 </span>
3536 <ChevronDown className="bot-access-panel__chevron" size={16} aria-hidden="true" />
3537 </summary>
3538 <div className="bot-access-panel__body">
3539 <div className="bot-choice-grid bot-choice-grid--access">
3540 <button
3541 type="button"
3542 className={`bot-choice-card${simpleAccessMode === "trusted" ? " bot-choice-card--active" : ""}`}
3543 disabled={busy}
3544 onClick={() => setSimpleAccessMode("trusted")}
3545 >
3546 <strong>{t("settings.botAccessTrusted")}</strong>
3547 <span>{t("settings.botAccessTrustedHint")}</span>
3548 </button>
3549 <button
3550 type="button"
3551 className={`bot-choice-card${simpleAccessMode === "everyone" ? " bot-choice-card--active" : ""}`}
3552 disabled={busy}
3553 onClick={() => setSimpleAccessMode("everyone")}
3554 >
3555 <strong>{t("settings.botAccessEveryone")}</strong>
3556 <span>{t("settings.botAccessEveryoneHint")}</span>
3557 </button>
3558 </div>
3559 <div className="bot-pairing-row">
3560 <div>
3561 <strong>{t("settings.botAccessPairing")}</strong>
3562 <span>{t("settings.botAccessPairingHint")}</span>
3563 </div>
3564 <ToggleSegment
3565 value={draft.pairing.enabled}
3566 disabled={busy}
3567 onChange={(enabled) => void persistBotSettings({ pairing: { ...draft.pairing, enabled } })}
3568 />
3569 </div>
3570 {draft.allowlist.allowAll ? (
3571 <div className="bot-access-panel__warning">{t("settings.botAllowAllWarn")}</div>
3572 ) : (
3573 <>
3574 <div className="bot-access-platforms">
3575 {visibleAccessPlatforms.map((platform) => (
3576 <div className="bot-access-platform" key={platform}>
3577 <div className="bot-access-platform__name">{botPlatformLabel(platform, t)}</div>
3578 <BotListInput
3579 label={t("settings.botListUsers")}
3580 value={allowlistText[botAllowlistKey(platform, "Users")]}
3581 disabled={busy}
3582 placeholder={t("settings.botListPlaceholder")}
3583 onChange={(value) => setAllowlistText((prev) => ({ ...prev, [botAllowlistKey(platform, "Users")]: value }))}
3584 onBlur={(value) => persistAllowlistText(botAllowlistKey(platform, "Users"), value)}
3585 />
3586 <BotListInput
3587 label={t("settings.botListGroups")}
3588 value={allowlistText[botAllowlistKey(platform, "Groups")]}
3589 disabled={busy}
3590 placeholder={t("settings.botListPlaceholder")}
3591 onChange={(value) => setAllowlistText((prev) => ({ ...prev, [botAllowlistKey(platform, "Groups")]: value }))}
3592 onBlur={(value) => persistAllowlistText(botAllowlistKey(platform, "Groups"), value)}
3593 />
3594 </div>
3595 ))}
3596 </div>
3597 {platformFilterAvailable ? (
3598 <button type="button" className="bot-access-platforms__toggle" onClick={() => setShowAllPlatforms((value) => !value)}>
3599 {showAllPlatforms ? t("settings.botAccessShowConnectedOnly") : t("settings.botAccessShowAllPlatforms")}
3600 </button>
3601 ) : null}
3602 </>
3603 )}
3604 <details className="bot-access-panel bot-simple-roles">
3605 <summary className="bot-access-panel__summary">
3606 <span>
3607 <strong>{t("settings.botRoleAccess")}</strong>
3608 <small>{t("settings.botRoleAccessHint")}</small>
3609 </span>
3610 <ChevronDown className="bot-access-panel__chevron" size={16} aria-hidden="true" />
3611 </summary>
3612 <div className="bot-access-panel__body">
3613 <div className="bot-access-platforms">
3614 {visibleAccessPlatforms.map((platform) => (
3615 <div className="bot-access-platform" key={platform}>
3616 <div className="bot-access-platform__name">{botPlatformLabel(platform, t)}</div>
3617 <BotListInput
3618 label={t("settings.botListApprovers")}
3619 value={allowlistText[botAllowlistKey(platform, "Approvers")]}
3620 disabled={busy || draft.allowlist.allowAll}
3621 placeholder={t("settings.botListPlaceholder")}
3622 onChange={(value) => setAllowlistText((prev) => ({ ...prev, [botAllowlistKey(platform, "Approvers")]: value }))}
3623 onBlur={(value) => persistAllowlistText(botAllowlistKey(platform, "Approvers"), value)}
3624 />
3625 <BotListInput
3626 label={t("settings.botListAdmins")}
3627 value={allowlistText[botAllowlistKey(platform, "Admins")]}
3628 disabled={busy || draft.allowlist.allowAll}
3629 placeholder={t("settings.botListPlaceholder")}
3630 onChange={(value) => setAllowlistText((prev) => ({ ...prev, [botAllowlistKey(platform, "Admins")]: value }))}
3631 onBlur={(value) => persistAllowlistText(botAllowlistKey(platform, "Admins"), value)}
3632 />
3633 </div>
3634 ))}
3635 </div>
3636 </div>
3637 </details>
3638 </div>
3639 </details>
3640 <details className="bot-access-panel bot-gateway-panel">
3641 <summary className="bot-access-panel__summary">
3642 <span>
3643 <strong>{t("settings.botGatewayDefaults")}</strong>
3644 <small>{t("settings.botGatewayDefaultsHint")}</small>
3645 </span>
3646 <ChevronDown className="bot-access-panel__chevron" size={16} aria-hidden="true" />
3647 </summary>
3648 <div className="bot-access-panel__body">
3649 <SettingsField label={t("settings.botRuntime")} hint={t("settings.botRuntimeHint")}>
3650 <div className="bot-inline-grid bot-inline-grid--runtime">
3651 <label>
3652 <span>{t("settings.botMaxSteps")}</span>
3653 <input
3654 className="mem-input"
3655 type="number"
3656 min={0}
3657 value={draft.maxSteps}
3658 disabled={busy}
3659 onChange={(event) => updateBotSettings({ maxSteps: Number(event.target.value) || 0 })}
3660 onBlur={(event) => void persistBotSettings({ maxSteps: Number(event.currentTarget.value) || 0 })}
3661 />
3662 </label>
3663 <label>
3664 <span>{t("settings.botDebounceMs")}</span>
3665 <input
3666 className="mem-input"
3667 type="number"
3668 min={0}
3669 value={draft.debounceMs}
3670 disabled={busy}
3671 onChange={(event) => updateBotSettings({ debounceMs: Number(event.target.value) || 0 })}
3672 onBlur={(event) => void persistBotSettings({ debounceMs: Number(event.currentTarget.value) || 0 })}
3673 />
3674 </label>
3675 <label>
3676 <span>{t("settings.botQueueCap")}</span>
3677 <input
3678 className="mem-input"
3679 type="number"
3680 min={0}
3681 value={draft.queueCap}
3682 disabled={busy}
3683 onChange={(event) => updateBotSettings({ queueCap: Number(event.target.value) || 0 })}
3684 onBlur={(event) => void persistBotSettings({ queueCap: Number(event.currentTarget.value) || 0 })}
3685 />
3686 </label>
3687 </div>
3688 </SettingsField>
3689 <SettingsField label={t("settings.botQueueModeSimple")} hint={t("settings.botQueueModeSimpleHint")}>
3690 <SettingsSelect
3691 className="mem-select"
3692 value={normalizeBotQueueMode(draft.queueMode)}
3693 disabled={busy}
3694 onValueChange={(value) => void persistBotSettings({ queueMode: value })}
3695 >
3696 {BOT_QUEUE_MODES.map((mode) => (
3697 <option key={mode} value={mode}>{t(`settings.botQueueMode.${mode}` as DictKey)}</option>
3698 ))}
3699 </SettingsSelect>
3700 </SettingsField>
3701 <SettingsField label={t("settings.botQueueDropLabel")} hint={t("settings.botQueueDropHint")}>
3702 <SettingsSelect
3703 className="mem-select"
3704 value={normalizeBotQueueDrop(draft.queueDrop)}
3705 disabled={busy}
3706 onValueChange={(value) => void persistBotSettings({ queueDrop: value })}
3707 >
3708 {BOT_QUEUE_DROPS.map((mode) => (
3709 <option key={mode} value={mode}>{t(`settings.botQueueDrop.${mode}` as DictKey)}</option>
3710 ))}
3711 </SettingsSelect>
3712 </SettingsField>
3713 <SettingsField label={t("settings.botIgnoreSelfMessages")} hint={t("settings.botIgnoreSelfMessagesHint")}>
3714 <ToggleSegment
3715 value={draft.ignoreSelfMessages}
3716 disabled={busy}
3717 onChange={(ignoreSelfMessages) => void persistBotSettings({ ignoreSelfMessages })}
3718 />
3719 </SettingsField>
3720 <SettingsField label={t("settings.botSelfUserIds")} hint={t("settings.botSelfUserIdsHint")}>
3721 <div className="bot-list-grid">
3722 <BotListInput
3723 label={t("settings.botQQUsers")}
3724 value={selfUserText.qq}
3725 disabled={busy}
3726 placeholder={t("settings.botListPlaceholder")}
3727 onChange={(value) => updateSelfUserText("qq", value)}
3728 onBlur={(value) => persistSelfUserText("qq", value)}
3729 />
3730 <BotListInput
3731 label={t("settings.botFeishuLarkUsers")}
3732 value={selfUserText.feishu}
3733 disabled={busy}
3734 placeholder={t("settings.botListPlaceholder")}
3735 onChange={(value) => updateSelfUserText("feishu", value)}
3736 onBlur={(value) => persistSelfUserText("feishu", value)}
3737 />
3738 <BotListInput
3739 label={t("settings.botWeixinUsers")}
3740 value={selfUserText.weixin}
3741 disabled={busy}
3742 placeholder={t("settings.botListPlaceholder")}
3743 onChange={(value) => updateSelfUserText("weixin", value)}
3744 onBlur={(value) => persistSelfUserText("weixin", value)}
3745 />
3746 </div>
3747 </SettingsField>
3748 <SettingsField label={t("settings.botPairing")} hint={t("settings.botPairingDetailHint")}>
3749 <div className="bot-inline-grid bot-inline-grid--runtime">
3750 <label>
3751 <span>{t("settings.botPairingTTL")}</span>
3752 <input
3753 className="mem-input"
3754 type="number"
3755 min={0}
3756 value={draft.pairing.requestTtlMinutes}
3757 disabled={busy}
3758 onChange={(event) => updateBotSettings({ pairing: { ...draft.pairing, requestTtlMinutes: Number(event.target.value) || 0 } })}
3759 onBlur={(event) => void persistBotSettings({ pairing: { ...draft.pairing, requestTtlMinutes: Number(event.currentTarget.value) || 0 } })}
3760 />
3761 </label>
3762 <label>
3763 <span>{t("settings.botPairingMaxPending")}</span>
3764 <input
3765 className="mem-input"
3766 type="number"
3767 min={0}
3768 value={draft.pairing.maxPendingPerPlatform}
3769 disabled={busy}
3770 onChange={(event) => updateBotSettings({ pairing: { ...draft.pairing, maxPendingPerPlatform: Number(event.target.value) || 0 } })}
3771 onBlur={(event) => void persistBotSettings({ pairing: { ...draft.pairing, maxPendingPerPlatform: Number(event.currentTarget.value) || 0 } })}
3772 />
3773 </label>
3774 </div>
3775 </SettingsField>
3776 </div>
3777 </details>
3778
3779 <details className="bot-access-panel bot-routes-panel">
3780 <summary className="bot-access-panel__summary">
3781 <span>
3782 <strong>{t("settings.botRoutes")}</strong>
3783 <small>{t("settings.botRoutesHint")}</small>
3784 </span>
3785 <ChevronDown className="bot-access-panel__chevron" size={16} aria-hidden="true" />
3786 </summary>
3787 <div className="bot-access-panel__body">
3788 {draft.routes.length === 0 ? (
3789 <div className="bot-route-empty">{t("settings.botRoutesEmpty")}</div>
3790 ) : (
3791 <div className="bot-route-list">
3792 {draft.routes.map((route, index) => (
3793 <div className="bot-route-row" key={index}>
3794 <div className="bot-route-row__head">
3795 <strong>{t("settings.botRouteTitle", { n: index + 1 })}</strong>
3796 <button type="button" className="btn btn--secondary btn--small" disabled={busy} onClick={() => removeRoute(index)}>
3797 {t("common.delete")}
3798 </button>
3799 </div>
3800 <div className="bot-route-grid">
3801 <label>
3802 <span>{t("settings.botRouteConnection")}</span>
3803 <SettingsSelect
3804 className="mem-select"
3805 value={route.connectionId}
3806 disabled={busy}
3807 onValueChange={(value) => {
3808 updateRoute(index, { connectionId: value });
3809 void persistRoute(index, { connectionId: value });
3810 }}
3811 >
3812 <option value="">{t("settings.botRouteAny")}</option>
3813 {routeConnectionOptions.map((option) => (
3814 <option key={option.id} value={option.id}>{option.label} · {option.id}</option>
3815 ))}
3816 </SettingsSelect>
3817 </label>
3818 <label>
3819 <span>{t("settings.botRoutePlatform")}</span>
3820 <SettingsSelect
3821 className="mem-select"
3822 value={route.platform}
3823 disabled={busy}
3824 onValueChange={(value) => {
3825 updateRoute(index, { platform: value });
3826 void persistRoute(index, { platform: value });
3827 }}
3828 >
3829 <option value="">{t("settings.botRouteAny")}</option>
3830 <option value="qq">QQ</option>
3831 <option value="feishu">{t("settings.botFeishu")}</option>
3832 <option value="weixin">{t("settings.botWeixin")}</option>
3833 </SettingsSelect>
3834 </label>
3835 <label>
3836 <span>{t("settings.botRouteChatType")}</span>
3837 <SettingsSelect
3838 className="mem-select"
3839 value={route.chatType}
3840 disabled={busy}
3841 onValueChange={(value) => {
3842 updateRoute(index, { chatType: value });
3843 void persistRoute(index, { chatType: value });
3844 }}
3845 >
3846 {BOT_ROUTE_CHAT_TYPES.map((chatType) => (
3847 <option key={chatType || "any"} value={chatType}>{t(`settings.botRouteChatType.${chatType || "any"}` as DictKey)}</option>
3848 ))}
3849 </SettingsSelect>
3850 </label>
3851 <label>
3852 <span>{t("settings.botRouteChatId")}</span>
3853 <input
3854 className="mem-input"
3855 value={route.chatId}
3856 disabled={busy}
3857 spellCheck={false}
3858 onChange={(event) => updateRoute(index, { chatId: event.target.value })}
3859 onBlur={(event) => void persistRoute(index, { chatId: event.currentTarget.value })}
3860 />
3861 </label>
3862 <label>
3863 <span>{t("settings.botRouteUserId")}</span>
3864 <input
3865 className="mem-input"
3866 value={route.userId}
3867 disabled={busy}
3868 spellCheck={false}
3869 onChange={(event) => updateRoute(index, { userId: event.target.value })}
3870 onBlur={(event) => void persistRoute(index, { userId: event.currentTarget.value })}
3871 />
3872 </label>
3873 <label>
3874 <span>{t("settings.botRouteThreadId")}</span>
3875 <input
3876 className="mem-input"
3877 value={route.threadId}
3878 disabled={busy}
3879 spellCheck={false}
3880 onChange={(event) => updateRoute(index, { threadId: event.target.value })}
3881 onBlur={(event) => void persistRoute(index, { threadId: event.currentTarget.value })}
3882 />
3883 </label>
3884 </div>
3885 <div className="bot-route-grid bot-route-grid--outputs">
3886 <label>
3887 <span>{t("settings.botWorkspaceRoot")}</span>
3888 <input
3889 className="mem-input"
3890 value={route.workspaceRoot}
3891 disabled={busy}
3892 placeholder={t("settings.botWorkspaceRootPlaceholder")}
3893 spellCheck={false}
3894 onChange={(event) => updateRoute(index, { workspaceRoot: event.target.value })}
3895 onBlur={(event) => void persistRoute(index, { workspaceRoot: event.currentTarget.value })}
3896 />
3897 </label>
3898 <label>
3899 <span>{t("settings.botChannelModel")}</span>
3900 <ModelPicker
3901 s={s}
3902 refs={refs}
3903 value={toRef(route.model, s)}
3904 disabled={busy}
3905 emptyOptionLabel={t("settings.botChannelModelAuto")}
3906 emptyOptionHint={settingsModelMeta(s, t)}
3907 onPick={(model) => void persistRoute(index, { model })}
3908 />
3909 </label>
3910 <label>
3911 <span>{t("settings.botToolApprovalMode")}</span>
3912 <SettingsSelect
3913 className="mem-select"
3914 value={route.toolApprovalMode}
3915 disabled={busy}
3916 onValueChange={(value) => {
3917 updateRoute(index, { toolApprovalMode: value });
3918 void persistRoute(index, { toolApprovalMode: value });
3919 }}
3920 >
3921 {BOT_TOOL_APPROVAL_MODES.map((mode) => (
3922 <option key={mode || "inherit"} value={mode}>{t(`settings.botToolApprovalMode.${mode || "inherit"}` as DictKey)}</option>
3923 ))}
3924 </SettingsSelect>
3925 </label>
3926 </div>
3927 </div>
3928 ))}
3929 </div>
3930 )}
3931 <button type="button" className="btn btn--secondary btn--small bot-route-add" disabled={busy} onClick={addRoute}>
3932 {t("settings.botAddRoute")}
3933 </button>
3934 </div>
3935 </details>
3936 </div>
3937 </details>
3938 </div>
3939 );
3940 }
3941
3942 function ToggleSegment({
3943 value,
3944 disabled,
3945 onLabel,
3946 offLabel,
3947 onChange,
3948 }: {
3949 value: boolean;
3950 disabled: boolean;
3951 onLabel?: string;
3952 offLabel?: string;
3953 onChange: (value: boolean) => void;
3954 }) {
3955 const t = useT();
3956 return (
3957 <SettingsOptions className="set-seg">
3958 <button
3959 type="button"
3960 className={`set-seg__btn${value ? " set-seg__btn--on" : ""}`}
3961 disabled={disabled}
3962 onClick={() => onChange(true)}
3963 >
3964 {onLabel ?? t("settings.toggleOn")}
3965 </button>
3966 <button
3967 type="button"
3968 className={`set-seg__btn${!value ? " set-seg__btn--on" : ""}`}
3969 disabled={disabled}
3970 onClick={() => onChange(false)}
3971 >
3972 {offLabel ?? t("settings.toggleOff")}
3973 </button>
3974 </SettingsOptions>
3975 );
3976 }
3977
3978 function BotListInput({
3979 label,
3980 value,
3981 disabled,
3982 placeholder,
3983 onChange,
3984 onBlur,
3985 }: {
3986 label: ReactNode;
3987 value: string;
3988 disabled: boolean;
3989 placeholder: string;
3990 onChange: (value: string) => void;
3991 onBlur: (value: string) => void;
3992 }) {
3993 return (
3994 <label className="bot-list-input">
3995 <span>{label}</span>
3996 <textarea
3997 className="mem-input bot-list-input__textarea"
3998 value={value}
3999 disabled={disabled}
4000 placeholder={placeholder}
4001 spellCheck={false}
4002 onChange={(event) => onChange(event.target.value)}
4003 onBlur={(event) => onBlur(event.currentTarget.value)}
4004 />
4005 </label>
4006 );
4007 }
4008
4009 function sanitizeBotDraft(draft: BotSettingsView): BotSettingsView {
4010 const bot = normalizeBotSettings(draft);
4011 return {
4012 ...bot,
4013 model: bot.model.trim(),
4014 toolApprovalMode: normalizeBotToolApprovalMode(bot.toolApprovalMode),
4015 maxSteps: Math.max(0, Math.floor(bot.maxSteps || 0)),
4016 debounceMs: Math.max(0, Math.floor(bot.debounceMs || 0)),
4017 queueMode: normalizeBotQueueMode(bot.queueMode),
4018 queueCap: Math.max(0, Math.floor(bot.queueCap || 0)),
4019 queueDrop: normalizeBotQueueDrop(bot.queueDrop),
4020 selfUserIds: {
4021 qq: uniqueStrings(bot.selfUserIds.qq.map((v) => v.trim())),
4022 feishu: uniqueStrings(bot.selfUserIds.feishu.map((v) => v.trim())),
4023 weixin: uniqueStrings(bot.selfUserIds.weixin.map((v) => v.trim())),
4024 dingtalk: uniqueStrings(bot.selfUserIds.dingtalk.map((v) => v.trim())),
4025 },
4026 control: {
4027 enabled: bot.control.enabled,
4028 addr: bot.control.addr.trim(),
4029 tokenEnv: bot.control.tokenEnv.trim(),
4030 },
4031 pairing: {
4032 enabled: bot.pairing.enabled,
4033 requestTtlMinutes: Math.max(0, Math.floor(bot.pairing.requestTtlMinutes || 0)),
4034 maxPendingPerPlatform: Math.max(0, Math.floor(bot.pairing.maxPendingPerPlatform || 0)),
4035 },
4036 routes: bot.routes.map(normalizeBotRoute).filter(botRouteHasValue),
4037 allowlist: {
4038 ...bot.allowlist,
4039 qqUsers: uniqueStrings(bot.allowlist.qqUsers.map((v) => v.trim())),
4040 feishuUsers: uniqueStrings(bot.allowlist.feishuUsers.map((v) => v.trim())),
4041 weixinUsers: uniqueStrings(bot.allowlist.weixinUsers.map((v) => v.trim())),
4042 qqApprovers: uniqueStrings(bot.allowlist.qqApprovers.map((v) => v.trim())),
4043 feishuApprovers: uniqueStrings(bot.allowlist.feishuApprovers.map((v) => v.trim())),
4044 weixinApprovers: uniqueStrings(bot.allowlist.weixinApprovers.map((v) => v.trim())),
4045 qqAdmins: uniqueStrings(bot.allowlist.qqAdmins.map((v) => v.trim())),
4046 feishuAdmins: uniqueStrings(bot.allowlist.feishuAdmins.map((v) => v.trim())),
4047 weixinAdmins: uniqueStrings(bot.allowlist.weixinAdmins.map((v) => v.trim())),
4048 qqGroups: uniqueStrings(bot.allowlist.qqGroups.map((v) => v.trim())),
4049 feishuGroups: uniqueStrings(bot.allowlist.feishuGroups.map((v) => v.trim())),
4050 weixinGroups: uniqueStrings(bot.allowlist.weixinGroups.map((v) => v.trim())),
4051 dingtalkUsers: uniqueStrings(bot.allowlist.dingtalkUsers.map((v) => v.trim())),
4052 dingtalkApprovers: uniqueStrings(bot.allowlist.dingtalkApprovers.map((v) => v.trim())),
4053 dingtalkAdmins: uniqueStrings(bot.allowlist.dingtalkAdmins.map((v) => v.trim())),
4054 dingtalkGroups: uniqueStrings(bot.allowlist.dingtalkGroups.map((v) => v.trim())),
4055 },
4056 qq: {
4057 ...bot.qq,
4058 appId: bot.qq.appId.trim(),
4059 appSecretEnv: bot.qq.appSecretEnv.trim(),
4060 model: bot.qq.model.trim(),
4061 toolApprovalMode: normalizeBotToolApprovalMode(bot.qq.toolApprovalMode),
4062 workspaceRoot: bot.qq.workspaceRoot.trim(),
4063 access: sanitizeBotAccess(bot.qq.access),
4064 },
4065 feishu: {
4066 ...bot.feishu,
4067 domain: bot.feishu.domain === "lark" ? "lark" : "feishu",
4068 appId: bot.feishu.appId.trim(),
4069 appSecretEnv: bot.feishu.appSecretEnv.trim(),
4070 verificationToken: bot.feishu.verificationToken.trim(),
4071 mode: bot.feishu.mode === "websocket" ? "websocket" : "webhook",
4072 webhookPort: Math.max(0, Math.floor(bot.feishu.webhookPort || 0)),
4073 },
4074 weixin: {
4075 ...bot.weixin,
4076 accountId: bot.weixin.accountId.trim(),
4077 tokenEnv: bot.weixin.tokenEnv.trim(),
4078 apiBase: bot.weixin.apiBase.trim().replace(/\/+$/, ""),
4079 },
4080 dingtalk: {
4081 ...bot.dingtalk,
4082 clientId: bot.dingtalk.clientId.trim(),
4083 clientSecretEnv: bot.dingtalk.clientSecretEnv.trim(),
4084 botName: bot.dingtalk.botName.trim(),
4085 toolApprovalMode: normalizeBotToolApprovalMode(bot.dingtalk.toolApprovalMode),
4086 access: sanitizeBotAccess(bot.dingtalk.access),
4087 },
4088 connections: bot.connections.map((conn) => ({ ...normalizeBotConnection(conn), access: sanitizeBotAccess(conn.access) })).filter((conn) => conn.id && conn.provider),
4089 };
4090 }
4091
4092 function sanitizeBotAccess(access: BotAccessView): BotAccessView {
4093 const normalized = normalizeBotAccess(access);
4094 return {
4095 ...normalized,
4096 users: uniqueStrings(normalized.users.map((v) => v.trim()).filter(Boolean)),
4097 groups: uniqueStrings(normalized.groups.map((v) => v.trim()).filter(Boolean)),
4098 approvers: uniqueStrings(normalized.approvers.map((v) => v.trim()).filter(Boolean)),
4099 admins: uniqueStrings(normalized.admins.map((v) => v.trim()).filter(Boolean)),
4100 };
4101 }
4102
4103 function botDraftWithDerivedGatewayState(draft: BotSettingsView): BotSettingsView {
4104 const bot = sanitizeBotDraft(draft);
4105 return {
4106 ...bot,
4107 enabled: bot.qq.enabled || bot.dingtalk.enabled || bot.connections.some((connection) => connection.enabled),
4108 };
4109 }
4110
4111 export function ModelsSection({ s, busy, apply, backgroundApply, subtab, onboarding, focusProvider, focusRequestId, onOnboardingComplete, onOpenProviders }: ModelsSectionProps) {
4112 const t = useT();
4113 const autoRefreshKeyRef = useRef("");
4114 const autoRefreshGenerationRef = useRef(0);
4115 const refs = useMemo(() => allRefs(s), [s.providers]);
4116 const defaultRef = toRef(s.defaultModel, s);
4117 const plannerRef = toRef(s.plannerModel, s);
4118 const subagentRef = toRef(s.subagentModel, s);
4119 const subagentOption = modelOptionFromRef(subagentRef || defaultRef, s);
4120 const subagentLevels = providerModelReasoningLevels(subagentOption?.providerView, subagentOption?.model ?? "");
4121
4122 const visionRef = s.visionModel === "auto" ? "auto" : toRef(s.visionModel, s);
4123 const [defaultProvider] = defaultRef.split("/");
4124 const defaultProviderView = s.providers.find((p) => p.name === defaultProvider);
4125 const modelIssue = !defaultProviderView
4126 ? t("settings.modelUnavailable", { ref: defaultRef || t("common.none") })
4127 : !providerIsConfigured(defaultProviderView)
4128 ? t("settings.modelNeedsKey", { provider: modelProviderLabel(defaultProvider, defaultProviderView, t) })
4129 : "";
4130 const agent = s.agent ?? { temperature: 0, maxSteps: 0, plannerMaxSteps: 0, maxSubagentDepth: 2, maxSubagentConcurrency: 6, maxParallelWriters: 3, systemPrompt: "", reasoningLanguage: "auto", compactRatio: 0.80 };
4131 const compactRatio = agent.compactRatio ?? 0.80;
4132 const compactRatioPercent = Math.round(compactRatio * 1000) / 10;
4133 const compactRatioPreset = COMPACT_RATIO_PRESETS.find(([ratio]) => Math.abs(compactRatio - ratio) < 0.0001);
4134 const [compactRatioDraft, setCompactRatioDraft] = useState(() => compactRatioPreset ? "" : String(compactRatioPercent));
4135 const [compactRatioCustomEditing, setCompactRatioCustomEditing] = useState(false);
4136 const compactRatioCustomInputRef = useRef<HTMLInputElement>(null);
4137 const compactRatioCancelBlurRef = useRef(false);
4138 const compactRatioDraftPercent = Number(compactRatioDraft);
4139 const compactRatioDraftValid = compactRatioDraft !== ""
4140 && Number.isFinite(compactRatioDraftPercent)
4141 && compactRatioDraftPercent >= COMPACT_RATIO_MIN_PERCENT
4142 && compactRatioDraftPercent <= COMPACT_RATIO_MAX_PERCENT;
4143 const compactRatioImpact = t("settings.compactRatioImpact");
4144 const compactRatioOverrideHint = agent.compactRatioOverridden
4145 ? t("settings.compactRatioProjectOverride", { percent: Math.round((agent.effectiveCompactRatio ?? compactRatio) * 100) })
4146 : "";
4147 const subagentDepth = Number.isFinite(agent.maxSubagentDepth) && agent.maxSubagentDepth <= 1 ? 1 : 2;
4148 const subagentConcurrency = Number.isFinite(agent.maxSubagentConcurrency) && agent.maxSubagentConcurrency > 0
4149 ? Math.max(1, Math.min(32, Math.floor(agent.maxSubagentConcurrency)))
4150 : 6;
4151 const parallelWriters = Number.isFinite(agent.maxParallelWriters) && agent.maxParallelWriters > 0
4152 ? Math.max(1, Math.min(subagentConcurrency, Math.floor(agent.maxParallelWriters)))
4153 : Math.min(3, subagentConcurrency);
4154 const visionRefs = useMemo(() => {
4155 const defaultProviderName = defaultRef.split("/")[0];
4156 const candidates = refs.filter((ref) => {
4157 const [provider, ...parts] = ref.split("/");
4158 const model = parts.join("/");
4159 const view = s.providers.find((item) => item.name === provider);
4160 return Boolean(view && providerVisionModelsForView(view).includes(model));
4161 });
4162 return candidates.sort((a, b) => {
4163 const aSame = a.startsWith(`${defaultProviderName}/`);
4164 const bSame = b.startsWith(`${defaultProviderName}/`);
4165 return aSame === bSame ? a.localeCompare(b) : aSame ? -1 : 1;
4166 });
4167 }, [defaultRef, refs, s.providers]);
4168
4169 useEffect(() => {
4170 if (!compactRatioCustomEditing) setCompactRatioDraft(compactRatioPreset ? "" : String(compactRatioPercent));
4171 }, [compactRatioCustomEditing, compactRatioPercent, compactRatioPreset]);
4172
4173 const persistCompactRatio = async (ratio: number) => {
4174 return await apply(() => app.SetCompactRatio(ratio));
4175 };
4176
4177 const focusCompactRatioCustom = () => {
4178 setCompactRatioCustomEditing(true);
4179 requestAnimationFrame(() => compactRatioCustomInputRef.current?.focus());
4180 };
4181
4182 const selectCompactRatioPreset = async (ratio: number) => {
4183 // A preset click replaces the draft; do not also persist it on blur.
4184 if (document.activeElement === compactRatioCustomInputRef.current) {
4185 compactRatioCancelBlurRef.current = true;
4186 compactRatioCustomInputRef.current?.blur();
4187 }
4188 setCompactRatioCustomEditing(false);
4189 if (Math.abs(compactRatio - ratio) < 0.0001) {
4190 return;
4191 }
4192 await persistCompactRatio(ratio);
4193 };
4194
4195 const commitCompactRatioDraft = async (rawValue: string) => {
4196 const percent = Number(rawValue);
4197 const valid = rawValue !== ""
4198 && Number.isFinite(percent)
4199 && percent >= COMPACT_RATIO_MIN_PERCENT
4200 && percent <= COMPACT_RATIO_MAX_PERCENT;
4201 const dirty = valid && Math.abs(percent / 100 - compactRatio) > 0.0001;
4202 if (!valid && rawValue !== "") return;
4203 if (!valid || busy) {
4204 setCompactRatioCustomEditing(false);
4205 return;
4206 }
4207 if (dirty && !await persistCompactRatio(percent / 100)) return;
4208 setCompactRatioCustomEditing(false);
4209 };
4210
4211 useEffect(() => {
4212 const generation = ++autoRefreshGenerationRef.current;
4213 let cancelled = false;
4214 const stale = () => cancelled || autoRefreshGenerationRef.current !== generation;
4215 if (subtab !== "usage") return;
4216 const groups = providerAccessGroups(s.providers.filter((p) => p.added), t);
4217 const candidates = groups
4218 .map((group) => {
4219 const provider = group.providers.find((p) => providerIsConfigured(p) && p.baseUrl);
4220 return provider ? { group, provider } : null;
4221 })
4222 .filter((item): item is { group: ProviderAccessGroup; provider: ProviderView } => Boolean(item));
4223 // The backend token covers provider identity, current catalog, headers,
4224 // and credential revision without persisting sensitive header values in
4225 // sessionStorage. Older payloads without the token simply skip this
4226 // opportunistic background refresh; manual refresh remains available.
4227 if (candidates.some(({ provider }) => !provider.modelCatalogFingerprint?.trim())) return;
4228 const refreshKey = candidates.map(({ group, provider }) => JSON.stringify([
4229 group.id,
4230 provider.modelCatalogFingerprint!.trim(),
4231 ])).join("|");
4232 if (!refreshKey || autoRefreshKeyRef.current === refreshKey) return;
4233
4234 // Session-level cooldown per provider set: reopening the panel does not
4235 // refetch the same providers, while a changed set refreshes immediately.
4236 const autoRefreshStorageKey = `settings-auto-refresh-at:${refreshKey}`;
4237 const lastAutoRefresh = sessionStorage.getItem(autoRefreshStorageKey);
4238 if (lastAutoRefresh && Date.now() - Number(lastAutoRefresh) < 30_000) return;
4239
4240 // Respect slow network hints; background model-list refresh can wait.
4241 if (shouldSkipAutoRefresh()) return;
4242
4243 autoRefreshKeyRef.current = refreshKey;
4244 sessionStorage.setItem(autoRefreshStorageKey, String(Date.now()));
4245
4246 void backgroundApply(async () => {
4247 // Batch-fetch models for all candidates in one round-trip.
4248 const providersToFetch = candidates.map((c) => c.provider).filter((p) => p.models && p.models.length > 0);
4249 let batchResults: Record<string, ProviderModelCapabilityView[]> = {};
4250 try {
4251 batchResults = await app.FetchAllProviderModelCatalogs(providersToFetch);
4252 } catch {
4253 // Batch failed entirely — fall back to per-provider cached calls below.
4254 }
4255 if (stale()) return;
4256
4257 const updates: ProviderModelCatalogUpdate[] = [];
4258 for (const { provider } of candidates) {
4259 if (stale()) return;
4260 if (!provider.models || provider.models.length === 0) continue;
4261 try {
4262 const fetched = batchResults[provider.name]?.map((item) => item.model)
4263 ?? await cachedFetchProviderModels((p) => app.FetchProviderModels(p), provider);
4264 if (stale()) return;
4265 if (!fetched || fetched.length === 0) continue;
4266 const models = mergedFetchedProviderModels(provider.models, fetched, { preserveCurated: true });
4267 const currentDefault = providerDefaultModel(provider.default, models);
4268 const visionModels = provider.visionModels.filter((model) => models.includes(model));
4269 if (sameStringList(provider.models, models) && provider.default === currentDefault && sameStringList(provider.visionModels, visionModels)) continue;
4270 const expectedFingerprint = provider.modelCatalogFingerprint?.trim() ?? "";
4271 if (!expectedFingerprint) continue;
4272 updates.push({ name: provider.name, expectedFingerprint, models, default: currentDefault, visionModels });
4273 } catch {
4274 // Background discovery is opportunistic; manual refresh shows errors.
4275 }
4276 }
4277 if (updates.length > 0) {
4278 try {
4279 if (stale()) return;
4280 // Compare and apply narrow catalog updates in one transaction.
4281 await saveModelSettings(s, {kind: "catalogs", catalogs: updates});
4282 } catch {
4283 // Background discovery is opportunistic; explicit edits show errors.
4284 }
4285 }
4286 });
4287 return () => {
4288 cancelled = true;
4289 if (autoRefreshGenerationRef.current === generation) autoRefreshGenerationRef.current += 1;
4290 };
4291 }, [backgroundApply, s.providers, subtab, t]);
4292
4293 return (
4294 <>
4295 {subtab === "usage" ? (
4296 <div className="model-preferences">
4297 <SettingsSection className="model-assignment-section" title={t("settings.models.preferences")} description={t("settings.models.preferencesApplyHint")}>
4298 <div className="model-assignment-head"><span>{t("settings.modelPurpose")}</span><span>{t("settings.modelUsage")}</span><span>{t("settings.modelConnection")}</span></div>
4299 <SettingsField className="model-assignment-row" label={<ModelSettingHelp label={t("settings.defaultModel")} text={t("providerUI.defaultModelHelp")} />}>
4300 <ModelPicker
4301 s={s}
4302 refs={refs}
4303 value={toRef(s.defaultModel, s)}
4304 disabled={busy}
4305 ariaLabel={t("settings.defaultModel")}
4306 onPick={(ref) => void apply(() => saveModelSettings(s, {kind: "preference", field: "default", ref: ref}))}
4307 />
4308 <span className="model-assignment-connection">{toRef(s.defaultModel, s) && toRef(s.defaultModel, s) !== "auto" ? modelOptionMeta(modelOptionFromRef(toRef(s.defaultModel, s), s)!, t) : t("settings.connectionAutomatic")}</span>
4309 </SettingsField>
4310
4311 <SettingsField className="model-assignment-row" label={<ModelSettingHelp label={t("settings.plannerModel")} text={t("providerUI.plannerModelHelp")} />}>
4312 <ModelPicker
4313 s={s}
4314 refs={refs}
4315 value={plannerRef}
4316 disabled={busy}
4317 ariaLabel={t("settings.plannerModel")}
4318 includeSameDefault
4319 onPick={(ref) => void apply(() => saveModelSettings(s, {kind: "preference", field: "planner", ref: ref}))}
4320 />
4321 <span className="model-assignment-connection">{plannerRef && plannerRef !== "auto" ? modelOptionMeta(modelOptionFromRef(plannerRef, s)!, t) : t("settings.connectionFollowSession")}</span>
4322 </SettingsField>
4323
4324 <SettingsField className="model-assignment-row" label={<ModelSettingHelp label={t("settings.imageUnderstandingModel")} text={t("providerUI.visionModelHelp")} />}>
4325 <ModelPicker
4326 s={s}
4327 refs={visionRefs}
4328 value={visionRef}
4329 disabled={busy}
4330 ariaLabel={t("settings.imageUnderstandingModel")}
4331 emptyOptionLabel={t("common.none")}
4332 autoOptionLabel={t("common.auto")}
4333 onPick={(ref) => void apply(() => saveModelSettings(s, {kind: "preference", field: "vision", ref: ref}))}
4334 />
4335 <span className="model-assignment-connection">{visionRef && visionRef !== "auto" ? modelOptionMeta(modelOptionFromRef(visionRef, s)!, t) : (visionRef === "auto" ? t("settings.connectionAutomatic") : t("common.none"))}</span>
4336 </SettingsField>
4337
4338
4339 <SettingsField className="model-assignment-row" label={<ModelSettingHelp label={t("settings.webSearchModel")} text={t("providerUI.searchModelHelp")} />}>
4340 <div className="web-search-assignment-control">
4341 <ModelPicker s={s} refs={s.webSearchModels ?? []} value={s.webSearchModel || "auto"}
4342 disabled={busy} ariaLabel={t("settings.webSearchModel")} autoOptionLabel={t("common.auto")}
4343 onPick={(ref) => void apply(() => saveModelSettings(s, {kind: "preference", field: "search", ref: ref}))} />
4344 {(s.webSearchModelStatus === "invalid" || Boolean(s.webSearchModel && s.webSearchModel !== "auto" && !(s.webSearchModels ?? []).includes(s.webSearchModel))) && <p role="status" className="web-search-assignment-hint">{t("settings.webSearchModelUnavailable")} {s.webSearchModelReason}</p>}
4345 {s.webSearchModelOverridden && <p className="web-search-assignment-hint">{t("settings.webSearchModelOverride", { model: s.effectiveWebSearchModel || t("common.auto") })}</p>}
4346 {(s.webSearchModels ?? []).length === 0 && <p className="web-search-assignment-hint">{t("settings.webSearchModelEmpty")} {onOpenProviders && <button type="button" className="btn btn--small" onClick={onOpenProviders}>{t("settings.webSearchModelConnections")}</button>}</p>}
4347 </div>
4348 <span className="model-assignment-connection">{!s.webSearchModel || s.webSearchModel === "auto" ? t("settings.webSearchModelAutomatic") : (s.providers.find(p => p.name === s.webSearchModel?.split("/")[0])?.displayName || s.webSearchModel.split("/")[0])}</span>
4349 </SettingsField>
4350
4351 <SettingsField className="model-assignment-row" label={<ModelSettingHelp label={t("settings.subagentModel")} text={t("providerUI.subagentModelHelp")} />}>
4352 <ModelPicker
4353 s={s}
4354 refs={refs}
4355 value={subagentRef}
4356 disabled={busy}
4357 ariaLabel={t("settings.subagentModel")}
4358 emptyOptionLabel={t("settings.subagentModelDefault")}
4359 emptyOptionHint={t("settings.subagentModelFollowHint")}
4360 onPick={(ref) => void apply(() => saveModelSettings(s, {kind: "preference", field: "subagent", ref: ref}))}
4361 />
4362 <span className="model-assignment-connection">{subagentRef && subagentRef !== "auto" ? modelOptionMeta(modelOptionFromRef(subagentRef, s)!, t) : t("settings.connectionFollowParent")}</span>
4363 </SettingsField>
4364
4365 <SettingsField className="model-assignment-effort" label={<ModelSettingHelp label={t("settings.subagentReasoning")} text={t("providerUI.subagentEffortHelp")} />}>
4366 <SettingsSelect
4367 className="mem-select set-grow"
4368 aria-label={t("settings.subagentReasoning")}
4369 value={s.subagentEffort || ""}
4370 disabled={busy}
4371 onValueChange={(value) => void apply(() => saveModelSettings(s, {kind: "preference", field: "subagent_effort", ref: value}))}
4372 >
4373 <option value="">{t("settings.subagentEffortDefault")}</option>
4374 {s.subagentEffort && !subagentLevels.includes(s.subagentEffort) && <option value={s.subagentEffort} disabled>{s.subagentEffort}</option>}
4375 {subagentLevels.map((level) => (
4376 <option key={level} value={level}>
4377 {level}
4378 </option>
4379 ))}
4380 </SettingsSelect>
4381 </SettingsField>
4382
4383 <details className="settings-subagent-advanced"><summary>{t("settings.subagentAdvanced")}</summary>
4384 <SettingsField label={t("settings.subagentDepth")} hint={t("settings.subagentDepthHint")}>
4385 <SettingsOptions className="provider-add-segmented" role="group" aria-label={t("settings.subagentDepth")}>
4386 {[1, 2].map((depth) => (
4387 <button
4388 key={depth}
4389 type="button"
4390 className={subagentDepth === depth ? "provider-add-segmented__item provider-add-segmented__item--active" : "provider-add-segmented__item"}
4391 disabled={busy}
4392 aria-pressed={subagentDepth === depth}
4393 onClick={() => void apply(() => saveModelSettings(s, {kind: "preference", field: "depth", number: depth}))}
4394 >
4395 {depth === 1 ? t("settings.subagentDepthOne") : t("settings.subagentDepthTwo")}
4396 </button>
4397 ))}
4398 </SettingsOptions>
4399 </SettingsField>
4400
4401 <SettingsField label={t("settings.subagentConcurrency")} hint={t("settings.subagentConcurrencyHint")}>
4402 <input
4403 className="mem-input"
4404 type="number"
4405 min={1}
4406 max={32}
4407 value={subagentConcurrency}
4408 disabled={busy}
4409 onChange={(e) => {
4410 const n = Number(e.target.value);
4411 if (!Number.isFinite(n)) return;
4412 void apply(() => saveModelSettings(s, {kind: "preference", field: "concurrency", number: n}));
4413 }}
4414 />
4415 </SettingsField>
4416
4417 <SettingsField label={t("settings.parallelWriters")} hint={t("settings.parallelWritersHint")}>
4418 <input
4419 className="mem-input"
4420 type="number"
4421 min={1}
4422 max={subagentConcurrency}
4423 value={parallelWriters}
4424 disabled={busy}
4425 onChange={(e) => {
4426 const n = Number(e.target.value);
4427 if (!Number.isFinite(n)) return;
4428 void apply(() => saveModelSettings(s, {kind: "preference", field: "writers", number: n}));
4429 }}
4430 />
4431 </SettingsField>
4432
4433 {modelIssue && <div className="provider-fetch-banner provider-fetch-banner--warn"><ErrorMessage error={modelIssue} /></div>}
4434 </details>
4435 </SettingsSection>
4436 <SettingsSection className="model-runtime-preferences" title={t("settings.runtimePreferences")}>
4437 <SettingsField label={t("settings.reasoningLanguage")} hint={t("settings.reasoningLanguageHint")}>
4438 <SettingsOptions layout="field" className="set-seg" role="radiogroup" aria-label={t("settings.reasoningLanguage")}>
4439 {(["auto", "zh", "en"] as const).map((lang) => (
4440 <button
4441 key={lang}
4442 type="button"
4443 role="radio"
4444 aria-checked={agent.reasoningLanguage === lang}
4445 className={`set-seg__btn${agent.reasoningLanguage === lang ? " set-seg__btn--on" : ""}`}
4446 disabled={busy}
4447 onClick={() => void apply(() => app.SetReasoningLanguage(lang))}
4448 >
4449 {t(`settings.reasoningLanguage.${lang}`)}
4450 </button>
4451 ))}
4452 </SettingsOptions>
4453 </SettingsField>
4454 <SettingsField label={t("settings.compactRatio")} hint={t("settings.compactRatioHint")} stacked>
4455 <div className="compact-ratio-controls">
4456 <fieldset className="compact-ratio-choice-list">
4457 <legend className="sr-only">{t("settings.compactRatio")}</legend>
4458 {COMPACT_RATIO_PRESETS.map(([ratio, labelKey, effectKey]) => {
4459 const selected = Math.abs(compactRatio - ratio) < 0.0001;
4460 const active = selected;
4461 const [percent, name] = t(labelKey).split(" · ");
4462 return (
4463 <div key={ratio} className="compact-ratio-choice" data-selected={active || undefined}>
4464 <label className="compact-ratio-choice__row"
4465 onPointerDown={(event) => {
4466 if (event.button === 0 && document.activeElement === compactRatioCustomInputRef.current) event.preventDefault();
4467 }}
4468 onMouseDown={(event) => {
4469 // Keep focus until click so blur cannot disable the intended preset.
4470 if (event.button === 0 && document.activeElement === compactRatioCustomInputRef.current) event.preventDefault();
4471 }}
4472 onClick={() => {
4473 if (selected && !busy) void selectCompactRatioPreset(ratio);
4474 }}
4475 >
4476 <input
4477 type="radio"
4478 name="settings-compact-ratio"
4479 value={ratio}
4480 checked={active}
4481 disabled={busy}
4482 aria-label={t(labelKey)}
4483 onChange={() => void selectCompactRatioPreset(ratio)}
4484 />
4485 <span className="compact-ratio-choice__name">{name}</span>
4486 <span className="compact-ratio-choice__percent">{percent}</span>
4487 <span className="compact-ratio-choice__effect">— {t(effectKey)}</span>
4488 {Math.abs(ratio - 0.8) < 0.0001 && <span className="compact-ratio-choice__badge">{t("settings.recommended")}</span>}
4489 </label>
4490 </div>
4491 );
4492 })}
4493 <div className="compact-ratio-choice" data-selected={!compactRatioPreset || undefined}>
4494 <div className="compact-ratio-choice__row compact-ratio-choice__row--custom">
4495 <input
4496 id="settings-compact-ratio-custom-choice"
4497 type="radio"
4498 name="settings-compact-ratio"
4499 value="custom"
4500 checked={!compactRatioPreset}
4501 disabled={busy}
4502 aria-label={t("settings.compactRatioCustomOption")}
4503 onChange={focusCompactRatioCustom}
4504 />
4505 <label className="compact-ratio-choice__name" htmlFor="settings-compact-ratio-custom-choice">
4506 {t("settings.typography.customized")}
4507 </label>
4508 <label className="compact-ratio-choice__inline-input" htmlFor="settings-compact-ratio-custom">
4509 <input
4510 ref={compactRatioCustomInputRef}
4511 id="settings-compact-ratio-custom"
4512 type="number"
4513 min={COMPACT_RATIO_MIN_PERCENT}
4514 max={COMPACT_RATIO_MAX_PERCENT}
4515 step={0.1}
4516 inputMode="decimal"
4517 value={compactRatioDraft}
4518 placeholder={t("settings.compactRatioCustomPlaceholder")}
4519 disabled={busy}
4520 aria-label={t("settings.compactRatioCustomAria")}
4521 aria-invalid={compactRatioDraft !== "" && !compactRatioDraftValid}
4522 onFocus={() => setCompactRatioCustomEditing(true)}
4523 onInput={(event) => setCompactRatioDraft(event.currentTarget.value)}
4524 onBlur={(event) => {
4525 if (compactRatioCancelBlurRef.current) {
4526 compactRatioCancelBlurRef.current = false;
4527 return;
4528 }
4529 void commitCompactRatioDraft(event.currentTarget.value);
4530 }}
4531 onKeyDown={(event) => {
4532 if (event.key === "Enter") {
4533 event.preventDefault();
4534 event.currentTarget.blur();
4535 }
4536 if (event.key === "Escape") {
4537 event.preventDefault();
4538 compactRatioCancelBlurRef.current = true;
4539 setCompactRatioDraft(compactRatioPreset ? "" : String(compactRatioPercent));
4540 setCompactRatioCustomEditing(false);
4541 event.currentTarget.blur();
4542 }
4543 }}
4544 />
4545 <span aria-hidden="true">%</span>
4546 </label>
4547 </div>
4548 </div>
4549 </fieldset>
4550 <div className="compact-ratio-impact">{compactRatioImpact}</div>
4551 </div>
4552 </SettingsField>
4553 {compactRatioOverrideHint && <div className="provider-fetch-banner provider-fetch-banner--warn">{compactRatioOverrideHint}</div>}
4554 </SettingsSection>
4555 </div>
4556 ) : null}
4557 <div className="model-access-page" hidden={subtab !== "access"}>
4558 <ProvidersSection s={s} busy={busy} apply={apply} onboarding={onboarding} focusProvider={focusProvider} focusRequestId={focusRequestId} onOnboardingComplete={onOnboardingComplete} />
4559 </div>
4560 {subtab === "stats" && (
4561 <Suspense fallback={<div className="empty">{t("settings.loading")}</div>}>
4562 <UsageStatsPanel />
4563 </Suspense>
4564 )}
4565 </>
4566 );
4567 }
4568
4569 type ModelPickerOption = {
4570 ref: string;
4571 provider: string;
4572 model: string;
4573 providerView?: ProviderView;
4574 };
4575
4576 export function ModelPicker({
4577 s,
4578 refs,
4579 value,
4580 disabled,
4581 includeSameDefault = false,
4582 ariaLabel,
4583 emptyOptionLabel,
4584 emptyOptionHint,
4585 autoOptionLabel,
4586 autoOptionHint,
4587 onPick,
4588 }: {
4589 s: SettingsView;
4590 refs: string[];
4591 value: string;
4592 disabled: boolean;
4593 includeSameDefault?: boolean;
4594 ariaLabel?: string;
4595 emptyOptionLabel?: string;
4596 emptyOptionHint?: string;
4597 autoOptionLabel?: string;
4598 autoOptionHint?: string;
4599 onPick: (ref: string) => void;
4600 }) {
4601 const t = useT();
4602 const emptyLabel = includeSameDefault ? t("settings.plannerNone") : emptyOptionLabel;
4603 const emptyHint = includeSameDefault ? t("settings.plannerNoneHint") : emptyOptionHint;
4604 const emptyMeta = includeSameDefault ? t("settings.plannerNoneHintShort") : emptyOptionHint;
4605 const autoLabel = autoOptionLabel;
4606 const autoHint = autoOptionHint;
4607 const selected = refs.includes(value) ? modelOptionFromRef(value, s) : null;
4608 const selectedLabel = value === "auto" && autoLabel
4609 ? autoLabel
4610 : value === "" && emptyLabel
4611 ? emptyLabel
4612 : selected?.model || value || t("common.none");
4613 const selectedMeta = value === "auto" && autoLabel
4614 ? autoHint || ""
4615 : value === "" && emptyLabel
4616 ? emptyMeta || ""
4617 : selected
4618 ? modelOptionMeta(selected, t)
4619 : t("settings.noModelsConfigured");
4620
4621 const groups = useMemo(() => {
4622 const providerOrder: string[] = [];
4623 const providerSeen = new Set<string>();
4624 for (const p of s.providers) {
4625 const id = p.name;
4626 if (!providerSeen.has(id)) {
4627 providerOrder.push(id);
4628 providerSeen.add(id);
4629 }
4630 }
4631 const options = refs
4632 .map((ref) => modelOptionFromRef(ref, s))
4633 .filter((opt): opt is ModelPickerOption => Boolean(opt))
4634 ;
4635 for (const opt of options) {
4636 const groupID = modelOptionGroupID(opt);
4637 if (!providerSeen.has(groupID)) {
4638 providerOrder.push(groupID);
4639 providerSeen.add(groupID);
4640 }
4641 }
4642 return providerOrder
4643 .map((groupID) => {
4644 const providerViews = s.providers.filter((p) => p.name === groupID);
4645 const firstProvider = providerViews[0];
4646 return {
4647 groupID,
4648 label: firstProvider ? (firstProvider.displayName || firstProvider.name) : groupID,
4649 keySet: providerViews.some((p) => p.keySet),
4650 requiresKey: providerViews.every((p) => providerRequiresKey(p)),
4651 options: uniqueModelOptions(options.filter((opt) => modelOptionGroupID(opt) === groupID)),
4652 };
4653 })
4654 .filter((group) => group.options.length > 0);
4655 }, [refs, s, t]);
4656
4657 return (
4658 <div className="settings-model-picker">
4659 <SettingsSelect
4660 value={value}
4661 selectedLabel={selectedLabel}
4662 title={selectedMeta || undefined}
4663 disabled={disabled || (!emptyLabel && !autoLabel && refs.length === 0)}
4664 aria-label={ariaLabel}
4665 searchPlaceholder={t("settings.searchModels")}
4666 emptyLabel={t("settings.noMatchingModels")}
4667 onValueChange={onPick}
4668 options={[
4669 ...(emptyLabel ? [{ value: "", label: emptyLabel, hint: emptyHint }] : []),
4670 ...(autoLabel ? [{ value: "auto", label: autoLabel, hint: autoHint }] : []),
4671 ...groups.flatMap(group => group.options.map(opt => ({
4672 value: opt.ref,
4673 label: opt.model,
4674 group: group.groupID,
4675 groupLabel: group.requiresKey && !group.keySet ? `${group.label} · ${t("settings.noKey")}` : group.label,
4676 searchText: `${opt.ref} ${modelProviderLabel(opt.provider, opt.providerView, t)}`,
4677 }))),
4678 ]}
4679 />
4680 </div>
4681 );
4682 }
4683
4684 function modelOptionFromRef(ref: string, s: SettingsView): ModelPickerOption | null {
4685 if (!ref) return null;
4686 const [provider, ...modelParts] = ref.split("/");
4687 const model = modelParts.join("/") || ref;
4688 return {
4689 ref,
4690 provider,
4691 model,
4692 providerView: s.providers.find((p) => p.name === provider),
4693 };
4694 }
4695
4696 function modelOptionMeta(option: ModelPickerOption, t: ReturnType<typeof useT>): string {
4697 const key = option.providerView ? providerKeyStatusLabel(option.providerView, t) : t("settings.noKey");
4698 return `${option.providerView?.displayName || option.provider}${option.providerView && providerRequiresKey(option.providerView) && !option.providerView.keySet ? ` · ${key}` : ""}`;
4699 }
4700
4701 function providerKeyStatusLabel(provider: { keySet: boolean; requiresKey?: boolean; apiKeyEnv?: string }, t: ReturnType<typeof useT>): string {
4702 if (!providerRequiresKey(provider)) return t("settings.noKeyRequired");
4703 return provider.keySet ? t("settings.keySet") : t("settings.noKey");
4704 }
4705
4706 function modelProviderLabel(provider: string, providerView: ProviderView | undefined, t: ReturnType<typeof useT>): string {
4707 return providerView?.displayName || (providerView ? providerGroupLabel(providerView, t) : provider);
4708 }
4709
4710 function modelOptionGroupID(option: ModelPickerOption): string {
4711 return option.provider;
4712 }
4713
4714 function uniqueModelOptions(options: ModelPickerOption[]): ModelPickerOption[] {
4715 const indexByModel = new Map<string, number>();
4716 const out: ModelPickerOption[] = [];
4717 for (const option of options) {
4718 const existingIndex = indexByModel.get(option.model);
4719 if (existingIndex !== undefined) {
4720 const existing = out[existingIndex];
4721 if (!existing?.providerView?.webSearch && option.providerView?.webSearch) {
4722 out[existingIndex] = option;
4723 }
4724 continue;
4725 }
4726 indexByModel.set(option.model, out.length);
4727 out.push(option);
4728 }
4729 return out;
4730 }
4731
4732 function sameStringList(a: string[], b: string[]): boolean {
4733 if (a.length !== b.length) return false;
4734 return a.every((value, i) => value === b[i]);
4735 }
4736
4737 function proxyModeLabel(mode: ProxyMode, t: ReturnType<typeof useT>): string {
4738 switch (mode) {
4739 case "auto":
4740 return t("settings.proxyMode.auto");
4741 case "custom":
4742 return t("settings.proxyMode.custom");
4743 case "off":
4744 return t("settings.proxyMode.off");
4745 }
4746 }
4747
4748 export function ProvidersSection({ s, busy, apply, onboarding, focusProvider, focusRequestId, onOnboardingComplete }: SectionProps & { onboarding?: boolean; focusProvider?: string; focusRequestId?: number; onOnboardingComplete?: () => void }) {
4749 const t = useT();
4750 const existingConnection = s.providers.find(p => p.added);
4751 const [editing, setEditing] = useState<string | null>(() => onboarding ? existingConnection?.name ?? null : null);
4752 const [adding, setAdding] = useState<AddProviderMode>(() => onboarding && !existingConnection ? "official" : null);
4753 const [revealedProvider, setRevealedProvider] = useState<string | null>(() => onboarding ? existingConnection?.name ?? null : null);
4754 useEffect(() => {
4755 if (!focusProvider) return;
4756 if (s.providers.some((provider) => provider.name === focusProvider)) {
4757 setRevealedProvider(focusProvider);
4758 setEditing(focusProvider);
4759 } else {
4760 setRevealedProvider(null);
4761 setEditing(null);
4762 }
4763 }, [focusProvider, focusRequestId, s.providers]);
4764 const readyConnection = s.providers.find(p => p.added && providerIsConfigured(p) && p.models.length > 0);
4765 const startUsing = async () => {
4766 if (!readyConnection) return;
4767 const model = providerDefaultModel(readyConnection.default, readyConnection.models);
4768 if (await apply(() => saveModelSettings(s, {kind: "preference", field: "default", ref: `${readyConnection.name}/${model}`}))) onOnboardingComplete?.();
4769 };
4770 const [fetchingProviders, setFetchingProviders] = useState<Set<string>>(() => new Set());
4771 const fetchGate = useMemo(createLatestRequestGate, []);
4772 const [fetchResults, setFetchResults] = useState<Record<string, ProviderFetchResult>>({});
4773 const [modelDrafts, setModelDrafts] = useState<Record<string, ProviderModelDraft>>({});
4774 const visibleProviders = useMemo(() => s.providers.filter((p) => p.added || p.name === revealedProvider), [s.providers, revealedProvider]);
4775 const groups = useMemo(() => visibleProviders.map(p => ({...providerAccessGroups([p], t)[0], id: `connection:${p.name}`, label: p.displayName || p.name})), [visibleProviders, t]);
4776
4777 useEffect(() => {
4778 if (revealedProvider && !s.providers.some((p) => p.name === revealedProvider)) {
4779 setRevealedProvider(null);
4780 if (editing === revealedProvider) setEditing(null);
4781 }
4782 }, [editing, revealedProvider, s.providers]);
4783
4784 const setGroupFetchResult = (groupID: string, result: ProviderFetchResult | null) => {
4785 setFetchResults((prev) => {
4786 const next = { ...prev };
4787 if (result) next[groupID] = result;
4788 else delete next[groupID];
4789 return next;
4790 });
4791 };
4792
4793 const setGroupModelDraft = (groupID: string, draft: ProviderModelDraft | null) => {
4794 setModelDrafts((prev) => {
4795 const next = { ...prev };
4796 if (draft) next[groupID] = draft;
4797 else delete next[groupID];
4798 return next;
4799 });
4800 };
4801
4802 const beginGroupFetch = (groupID: string): number => {
4803 const generation = fetchGate.begin(groupID);
4804 setFetchingProviders((current) => {
4805 if (current.has(groupID)) return current;
4806 const next = new Set(current);
4807 next.add(groupID);
4808 return next;
4809 });
4810 return generation;
4811 };
4812
4813 const groupFetchIsCurrent = (groupID: string, generation: number): boolean => (
4814 fetchGate.isCurrent(groupID, generation)
4815 );
4816
4817 const finishGroupFetch = (groupID: string, generation: number) => {
4818 if (!groupFetchIsCurrent(groupID, generation)) return;
4819 setFetchingProviders((current) => {
4820 if (!current.has(groupID)) return current;
4821 const next = new Set(current);
4822 next.delete(groupID);
4823 return next;
4824 });
4825 };
4826
4827 const cancelGroupFetch = (groupID: string) => {
4828 fetchGate.cancel(groupID);
4829 setFetchingProviders((current) => {
4830 if (!current.has(groupID)) return current;
4831 const next = new Set(current);
4832 next.delete(groupID);
4833 return next;
4834 });
4835 };
4836
4837 const modelDraftForFetch = (p: ProviderView, fetched: string[], capabilities: ProviderModelCapabilityView[] = []): ProviderModelDraft => {
4838 const candidates = providerModelCandidates(p.models, fetched);
4839 const selected = mergedFetchedProviderModels(p.models, fetched, { preserveCurated: true });
4840 const configuredVision = providerVisionModelsForView(p, candidates);
4841 return {
4842 providerName: p.name,
4843 candidates,
4844 selected: candidates.filter((model) => selected.includes(model)),
4845 visionModels: configuredVision,
4846 visionModelsConfigured: p.visionModelsConfigured,
4847 modelCapabilities: capabilities,
4848 };
4849 };
4850
4851 const updateModelDraftSelection = (groupID: string, nextSelected: (draft: ProviderModelDraft) => string[]) => {
4852 setModelDrafts((prev) => {
4853 const draft = prev[groupID];
4854 if (!draft) return prev;
4855 const selectedSet = new Set(nextSelected(draft));
4856 return {
4857 ...prev,
4858 [groupID]: {
4859 ...draft,
4860 selected: draft.candidates.filter((model) => selectedSet.has(model)),
4861 },
4862 };
4863 });
4864 };
4865
4866
4867 const refreshModels = async (group: ProviderAccessGroup, p: ProviderView) => {
4868 const generation = beginGroupFetch(group.id);
4869 setGroupFetchResult(group.id, null);
4870 setGroupModelDraft(group.id, null);
4871 try {
4872 let fetched: string[];
4873 let fetchedCapabilities: ProviderModelCapabilityView[] = [];
4874 try {
4875 fetchedCapabilities = await cachedFetchProviderModelCatalog((provider) => app.FetchProviderModelCatalog(provider), p, true);
4876 fetched = fetchedCapabilities.map((item) => item.model);
4877 } catch (e) {
4878 if (!groupFetchIsCurrent(group.id, generation)) return;
4879 setGroupFetchResult(group.id, {
4880 kind: "warn",
4881 text: t("settings.fetchModelsFailedForProvider", { provider: group.label, err: String((e as Error)?.message ?? e) }),
4882 });
4883 return;
4884 }
4885 if (!groupFetchIsCurrent(group.id, generation)) return;
4886 if (fetched.length === 0) {
4887 setGroupFetchResult(group.id, {
4888 kind: "warn",
4889 text: t("settings.fetchModelsEmptyForProvider", { provider: group.label }),
4890 });
4891 return;
4892 }
4893 const draft = modelDraftForFetch(p, fetched, fetchedCapabilities);
4894 startTransition(() => {
4895 setGroupModelDraft(group.id, draft);
4896 setGroupFetchResult(group.id, {
4897 kind: "ok",
4898 text: t("settings.fetchModelsReadyForProvider", { provider: group.label, n: draft.candidates.length }),
4899 });
4900 });
4901 } finally {
4902 finishGroupFetch(group.id, generation);
4903 }
4904 };
4905
4906 const saveProviderKey = async (group: ProviderAccessGroup, apiKeyEnv: string, value: string) => {
4907 if (!apiKeyEnv) return;
4908 cancelGroupFetch(group.id);
4909 setGroupFetchResult(group.id, null);
4910 setGroupModelDraft(group.id, null);
4911 const saved = await apply(async () => {
4912 const warning = await saveModelSettings(s, {kind: "credential", names: group.providers.filter(p => p.apiKeyEnv === apiKeyEnv).map(p => p.name), key: value});
4913 invalidateProviderCacheByAPIKeyEnv(apiKeyEnv);
4914 return warning;
4915 });
4916 if (!saved) throw new Error(t("settings.models.keySaveFailed"));
4917 };
4918
4919 const clearProviderKey = async (group: ProviderAccessGroup, apiKeyEnv: string) => {
4920 if (!apiKeyEnv) return;
4921 cancelGroupFetch(group.id);
4922 await apply(async () => {
4923 await saveModelSettings(s, {kind: "credential", names: group.providers.filter(p => p.apiKeyEnv === apiKeyEnv).map(p => p.name), key: ""});
4924 invalidateProviderCacheByAPIKeyEnv(apiKeyEnv);
4925 });
4926 };
4927
4928 const saveProvider = async (provider: ProviderView, key: string, create = false) => {
4929 if (create || !s.providers.some(p => p.name === provider.name)) {
4930 const id = crypto.randomUUID().replaceAll("-", "");
4931 provider = {...provider, displayName: provider.displayName || provider.name, name: `${provider.name}-${id}`, apiKeyEnv: `REASONIX_CONNECTION_${id.toUpperCase()}_KEY`};
4932 }
4933 if (key) {
4934 provider = {...provider, apiKeyEnv: `REASONIX_CONNECTION_${crypto.randomUUID().replaceAll("-", "").toUpperCase()}_KEY`};
4935 const warning = await saveModelSettings(s, {kind: "provider_save", provider, key});
4936 invalidateProviderCacheByAPIKeyEnv(provider.apiKeyEnv);
4937 return warning;
4938 }
4939 return saveModelSettings(s, {kind: "provider_save", provider});
4940 };
4941
4942 const saveModelDraft = async (group: ProviderAccessGroup) => {
4943 const draft = modelDrafts[group.id];
4944 const provider = draft ? group.providers.find((p) => p.name === draft.providerName) : null;
4945 const models = uniqueStrings(draft?.selected ?? []);
4946 if (!draft || !provider || models.length === 0) return;
4947 let saved = false;
4948 await apply(async () => {
4949 const result = await saveModelSettings(s, {kind: "provider_save", provider: {
4950 ...provider,
4951 models,
4952 // Vision capability is derived from model metadata. Keep legacy
4953 // fields untouched so old configurations remain readable.
4954 default: providerDefaultModel(provider.default, models),
4955 }});
4956 saved = true;
4957 return result;
4958 });
4959 if (!saved) return;
4960 setGroupModelDraft(group.id, null);
4961 setGroupFetchResult(group.id, {
4962 kind: "ok",
4963 text: t("settings.enabledModelsSavedForProvider", { provider: group.label, n: models.length }),
4964 });
4965 };
4966
4967 return (
4968 <SettingsSection
4969 title={t("settings.providerAccess")}
4970 description={t("settings.providerAccessHint")}
4971 actions={
4972 <button className="btn btn--small" disabled={busy || adding !== null} onClick={() => setAdding("official")}>
4973 {t("settings.addProvider")}
4974 </button>
4975 }
4976 >
4977 {onboarding && <div id="provider-onboarding" className="banner banner--actionable" role="status">
4978 <span className="banner__msg">{t(readyConnection ? "onboarding.connectionReady" : existingConnection ? "onboarding.repairConnection" : "onboarding.addConnection")}</span>
4979 {readyConnection && <button type="button" className="btn btn--primary" disabled={busy} onClick={() => void startUsing()}>{t("onboarding.startUsing")}</button>}
4980 </div>}
4981 <div className="provider-access-grid">
4982 {groups.length === 0 && adding === null && (
4983 <div className="provider-empty">
4984 <strong>{t("settings.providerAccessEmptyTitle")}</strong>
4985 <span>{t("settings.providerAccessEmptyHint")}</span>
4986 <div className="provider-empty__actions">
4987 <button type="button" className="btn btn--small" disabled={busy} onClick={() => setAdding("official")}>
4988 {t("settings.addProvider.officialChoice")}
4989 </button>
4990 <button type="button" className="btn btn--small" disabled={busy} onClick={() => setAdding("custom")}>
4991 {t("settings.addProvider.customChoice")}
4992 </button>
4993 </div>
4994 </div>
4995 )}
4996 {adding !== null && (
4997 <AddProviderPanel
4998 mode={adding}
4999 kinds={s.providerKinds}
5000 officialProviders={s.officialProviders}
5001 providerPresets={s.providerPresets}
5002 busy={busy}
5003 onMode={setAdding}
5004 onCancel={() => onboarding ? onOnboardingComplete?.() : setAdding(null)}
5005 onAddOfficial={(kind, key, baseURL, format) => apply(() => saveModelSettings(s, {kind: "connection_add", name: s.providers.find(p => officialProviderKind(p) === kind)?.name ?? "deepseek-flash", key, baseURL, protocol: format})).then(saved => { if (saved) setAdding(null); })}
5006 onAddPreset={(id, key, baseURL, format) => apply(() => saveModelSettings(s, {kind: "connection_add", presetId: id, key, baseURL, protocol: format})).then(saved => { if (saved) setAdding(null); })}
5007 onViewPresetConflict={(providerName) => {
5008 setRevealedProvider(providerName);
5009 setEditing(providerName);
5010 setAdding(null);
5011 }}
5012 onResetPreset={(id) => apply(() => saveModelSettings(s, {kind: "preset_reset", presetId: id})).then(saved => { if (saved) setAdding(null); })}
5013 onAddCustom={(pv, key) => apply(() => saveProvider(pv, key ?? "", true)).then(saved => { if (saved) setAdding(null); })}
5014 />
5015 )}
5016 <ProviderConnections groups={groups} presets={s.providerPresets} revealedProvider={revealedProvider} hidden={adding !== null} busy={busy} onAdd={() => setAdding("official")} renderDetail={(group) => (
5017 <ProviderAccessCard
5018 key={group.id}
5019 detail
5020 onCopy={() => void apply(() => saveModelSettings(s, {kind: "connection_add", name: group.providers[0].name, key: ""}))}
5021 onRename={(label) => apply(() => {
5022 if (typeof app.RenameProviderConnections !== "function") throw new Error(t("settings.connections.restartRequired"));
5023 return saveModelSettings(s, {kind: "rename", names: group.providers.map(p => p.name), ref: label});
5024 })}
5025 group={group}
5026 providerPresets={s.providerPresets}
5027 busy={busy}
5028 fetching={fetchingProviders.has(group.id)}
5029 fetchResult={fetchResults[group.id]}
5030 modelDraft={modelDrafts[group.id]}
5031 editing={editing}
5032 kinds={s.providerKinds}
5033 onEdit={setEditing}
5034 onCancelEdit={() => setEditing(null)}
5035 onSave={(pv, key) => {
5036 cancelGroupFetch(group.id);
5037 return apply(() => saveProvider(pv, key ?? "")).then((saved) => {
5038 if (!saved) throw new Error(t("settings.connections.renameFailed"));
5039 setGroupModelDraft(group.id, null);
5040 });
5041 }}
5042 onRefresh={(provider) => void refreshModels(group, provider)}
5043 onToggleDraftModel={(model) => updateModelDraftSelection(group.id, (draft) => (
5044 draft.selected.includes(model)
5045 ? draft.selected.filter((candidate) => candidate !== model)
5046 : [...draft.selected, model]
5047 ))}
5048 onSelectAllDraftModels={() => updateModelDraftSelection(group.id, (draft) => draft.candidates)}
5049 onClearDraftModels={() => updateModelDraftSelection(group.id, () => [])}
5050 onCancelDraftModels={() => {
5051 setGroupModelDraft(group.id, null);
5052 setGroupFetchResult(group.id, null);
5053 }}
5054 onSaveDraftModels={() => void saveModelDraft(group)}
5055 onToggleWebSearch={(enabled) => {
5056 if (group.id === "custom:opencode-go") {
5057 const searchProviderNames = group.providers
5058 .map((provider) => provider.name)
5059 .filter((name) => name.startsWith("opencode-go-deepseek-"));
5060 if (enabled) {
5061 void apply(() => saveModelSettings(s, {kind: "preset_add", presetId: "opencode-go-deepseek-responses", key: ""}));
5062 } else if (searchProviderNames.length > 0) {
5063 void apply(() => saveModelSettings(s, {kind: "access_remove", names: searchProviderNames}));
5064 }
5065 return;
5066 }
5067 const providerNames = group.providers.map((provider) => provider.name);
5068 if (providerNames.length === 0) return;
5069 void apply(() => saveModelSettings(s, {kind: "web_search_capability", names: providerNames, enabled}));
5070 }}
5071 onUpgradeRecommended={(name) => {
5072 cancelGroupFetch(group.id);
5073 return apply(() => saveModelSettings(s, {kind: "protocol_upgrade", name})).then((upgraded) => {
5074 if (upgraded) {
5075 setEditing(null);
5076 setGroupModelDraft(group.id, null);
5077 }
5078 });
5079 }}
5080 onSaveEditorKey={(env, value) => saveProviderKey(group, env, value)}
5081 onClearEditorKey={(env) => clearProviderKey(group, env)}
5082 onDelete={(providers) => {
5083 cancelGroupFetch(group.id);
5084 const providerNames = providers.map(({ name }) => name);
5085 return apply(() => saveModelSettings(s, {kind: "access_remove", names: providerNames})).then(() => {
5086 if (revealedProvider && providerNames.includes(revealedProvider)) {
5087 setRevealedProvider(null);
5088 setEditing(null);
5089 }
5090 });
5091 }}
5092 />
5093 )} />
5094 </div>
5095 </SettingsSection>
5096 );
5097 }
5098
5099 export type ProviderAccessGroup = {
5100 id: string;
5101 label: string;
5102 description: string;
5103 builtIn: boolean;
5104 providers: ProviderView[];
5105 apiKeyEnv: string;
5106 keySet: boolean;
5107 requiresKey: boolean;
5108 configured: boolean;
5109 keySource?: string;
5110 keySourcePath?: string;
5111 baseUrl: string;
5112 kind: string;
5113 models: string[];
5114 recommendedUpgradeAvailable: boolean;
5115 };
5116
5117 type ProviderFetchResult = {
5118 kind: "ok" | "warn";
5119 text: string;
5120 };
5121
5122 type ProviderModelDraft = {
5123 providerName: string;
5124 candidates: string[];
5125 selected: string[];
5126 visionModels: string[];
5127 visionModelsConfigured: boolean;
5128 modelCapabilities: ProviderModelCapabilityView[];
5129 };
5130
5131 type AddProviderMode = null | "official" | "custom";
5132 type OfficialProviderKind = "deepseek";
5133
5134 const OFFICIAL_PROVIDER_CHOICES: Array<{ kind: OfficialProviderKind; labelKey: DictKey; descKey: DictKey; keyEnv: string }> = [
5135 { kind: "deepseek", labelKey: "settings.addProvider.official.deepseek", descKey: "settings.addProvider.official.deepseekDesc", keyEnv: "DEEPSEEK_API_KEY" },
5136 ];
5137
5138 type ProviderTemplateChoice =
5139 | { id: string; source: "official"; kind: OfficialProviderKind; label: string; description: string; keyEnv: string; added: boolean; keySet: boolean }
5140 | {
5141 id: string; source: "preset"; presetID: string; label: string; description: string; keyEnv: string;
5142 added: boolean; status: ProviderPresetStatus; statusProviderNames: string[]; missingProviderNames: string[]; keySet: boolean;
5143 recommended: boolean; billingMode: string; displayGroup: string; displaySection: string;
5144 displayTier: string; routeKind: string; optional: boolean; displayOrder: number;
5145 };
5146
5147 export function AddProviderPanel({
5148 mode,
5149 kinds,
5150 officialProviders,
5151 providerPresets,
5152 busy,
5153 onMode,
5154 onCancel,
5155 onAddOfficial,
5156 onAddPreset,
5157 onViewPresetConflict,
5158 onResetPreset,
5159 onAddCustom,
5160 }: {
5161 mode: AddProviderMode; kinds: string[]; officialProviders: ProviderView[];
5162 providerPresets: ProviderPresetView[];
5163 busy: boolean;
5164 onMode: (mode: AddProviderMode) => void;
5165 onCancel: () => void;
5166 onAddOfficial: (kind: OfficialProviderKind, key: string, baseURL?: string, format?: string) => Promise<void>;
5167 onAddPreset: (id: string, key: string, baseURL?: string, format?: string) => Promise<void>;
5168 onViewPresetConflict: (providerName: string) => void;
5169 onResetPreset: (id: string) => Promise<void>;
5170 onAddCustom: (p: ProviderView, key?: string) => void | Promise<void>;
5171 }) {
5172 const t = useT();
5173 const choices: CatalogChoice[] = [
5174 ...OFFICIAL_PROVIDER_CHOICES.map(choice => {
5175 const provider = officialProviders.find(p => officialProviderKind(p) === choice.kind);
5176
5177 return {
5178 id: `official:${choice.kind}`,
5179 catalog: { brandId: "deepseek", brandLabel: "DeepSeek", region: "global", product: "api", format: "anthropic", baseUrl: "https://api.deepseek.com/anthropic" },
5180 keyEnv: provider?.apiKeyEnv || choice.keyEnv, keySet: Boolean(provider?.keySet),
5181 models: providerPresets.find(p => p.id === "deepseek-chat")?.models ?? ["deepseek-flash", "deepseek-v4-pro"],
5182 canAdd: true, status: "available",
5183 statusLabel: "",
5184 actionLabel: t("settings.addProvider.confirm"),
5185 };
5186 }),
5187 ...providerPresets.map(preset => {
5188 const choice: ProviderTemplateChoice = {
5189 id: `preset:${preset.id}`, source: "preset", presetID: preset.id,
5190 label: preset.label, description: preset.description, keyEnv: preset.keyEnv,
5191 added: preset.added, status: normalizeProviderPresetStatus(preset.status, preset.added),
5192 statusProviderNames: asArray(preset.statusProviderNames), missingProviderNames: asArray(preset.missingProviderNames),
5193 keySet: preset.keySet, recommended: Boolean(preset.recommended), billingMode: preset.billingMode ?? "",
5194 displayGroup: preset.displayGroup ?? "", displaySection: preset.displaySection ?? "",
5195 displayTier: preset.displayTier ?? "", routeKind: preset.routeKind ?? "", optional: Boolean(preset.optional), displayOrder: preset.displayOrder ?? 0,
5196 };
5197 return {
5198 id: choice.id, label: preset.label,
5199 // Older hosts can omit the additive catalog field; their presets remain usable.
5200 catalog: catalogForPreset(preset),
5201 keyEnv: preset.keyEnv, keySet: preset.keySet, models: preset.models,
5202 canAdd: true, status: "available",
5203 statusLabel: "", actionLabel: t("settings.addProvider.confirm"),
5204 conflictName: undefined,
5205 };
5206 }),
5207 ];
5208 return <div className="provider-add-panel">
5209 <div className="provider-add-panel__head">
5210 <div><strong>{t("settings.addProvider.chooseTitle")}</strong><span>{t("settings.catalog.hint")}</span></div>
5211 <button type="button" className="btn btn--small" disabled={busy} onClick={onCancel}>{t("common.cancel")}</button>
5212 </div>
5213 <SettingsOptions className="provider-add-segmented" role="tablist" aria-label={t("settings.addProvider.chooseTitle")}>
5214 <button type="button" role="tab" aria-selected={mode === "official"} className="provider-add-segmented__item" disabled={busy} onClick={() => onMode("official")}>{t("settings.addProvider.officialChoice")}</button>
5215 <button type="button" role="tab" aria-selected={mode === "custom"} className="provider-add-segmented__item" disabled={busy} onClick={() => onMode("custom")}>{t("settings.addProvider.customChoice")}</button>
5216 </SettingsOptions>
5217 {mode === "official" && <ProviderCatalogPicker choices={choices} busy={busy}
5218 onConnect={(id, key, baseURL, format) => { if (id.startsWith("official:")) void onAddOfficial("deepseek", key, baseURL, format); else void onAddPreset(id.slice(7), key, baseURL, format); }}
5219 onView={onViewPresetConflict} onReset={id => { if (id.startsWith("preset:")) void onResetPreset(id.slice(7)); }} />}
5220 {mode === "custom" && <ProviderEditor kinds={kinds} busy={busy} onCancel={onCancel} onSave={onAddCustom} />}
5221 </div>;
5222 }
5223
5224 export function ProviderAccessCard({
5225 detail = false,
5226 onCopy,
5227 onRename,
5228 group,
5229 providerPresets,
5230 busy,
5231 fetching,
5232 fetchResult,
5233 modelDraft,
5234 editing,
5235 kinds,
5236 onEdit,
5237 onCancelEdit,
5238 onSave,
5239 onRefresh,
5240 onToggleDraftModel,
5241 onSelectAllDraftModels,
5242 onClearDraftModels,
5243 onCancelDraftModels,
5244 onSaveDraftModels,
5245 onToggleWebSearch,
5246 onUpgradeRecommended,
5247 onSaveEditorKey,
5248 onClearEditorKey,
5249 onDelete,
5250 }: {
5251 detail?: boolean;
5252 onCopy?: () => void;
5253 onRename?: (label: string) => Promise<boolean>;
5254 group: ProviderAccessGroup;
5255 providerPresets?: ProviderPresetView[];
5256 busy: boolean;
5257 fetching: boolean;
5258 fetchResult?: ProviderFetchResult;
5259 modelDraft?: ProviderModelDraft;
5260 editing: string | null;
5261 kinds: string[];
5262 onEdit: (name: string) => void;
5263 onCancelEdit: () => void;
5264 onSave: (p: ProviderView, key?: string) => void | Promise<void>;
5265 onRefresh: (p: ProviderView) => void;
5266 onToggleDraftModel: (model: string) => void;
5267 onSelectAllDraftModels: () => void;
5268 onClearDraftModels: () => void;
5269 onCancelDraftModels: () => void;
5270 onSaveDraftModels: () => void;
5271 onToggleWebSearch: (enabled: boolean) => void;
5272 onUpgradeRecommended: (name: string) => void | Promise<void>;
5273 onSaveEditorKey: (apiKeyEnv: string, value: string) => Promise<void>;
5274 onClearEditorKey?: (apiKeyEnv: string) => Promise<void>;
5275 onDelete?: (providers: ProviderView[]) => Promise<void>;
5276 }) {
5277 const t = useT();
5278 const editableProvider = group.providers[0];
5279 const isOpenCodeGoConnection = group.id === "custom:opencode-go";
5280 const [editorRevision, setEditorRevision] = useState(0);
5281 const editingProvider = group.providers.find((p) => editing === p.name) ?? (detail && !isOpenCodeGoConnection ? editableProvider : undefined);
5282 const upgradeProvider = group.providers.find((p) => p.recommendedUpgradeAvailable);
5283 const primaryProviderExpanded = Boolean(editableProvider && editing === editableProvider.name);
5284 const supportsServerWebSearch = isOpenCodeGoConnection
5285 || (group.providers.length > 0 && group.providers.every(providerSupportsServerWebSearchForView));
5286 const webSearchEnabled = supportsServerWebSearch && (isOpenCodeGoConnection
5287 ? group.providers.some((provider) => provider.name.startsWith("opencode-go-deepseek-") && Boolean(provider.webSearch))
5288 : group.providers.every((provider) => Boolean(provider.webSearch)));
5289 const visibleModels = group.models.slice(0, 6);
5290 const hiddenModelCount = Math.max(0, group.models.length - visibleModels.length);
5291 const providerProfiles = (
5292 <div className="provider-profiles">
5293 {group.providers.map((p) => {
5294 const profileExpanded = editing === p.name;
5295 return (
5296 <div className="provider-profile-row" key={p.name}>
5297 <span>{p.name}</span>
5298 <span>{p.models.join(", ") || t("common.none")}</span>
5299 <button
5300 className="btn btn--small provider-profile-row__refresh"
5301 disabled={busy || fetching || !p.baseUrl || !providerIsConfigured(p)}
5302 onClick={() => onRefresh(p)}
5303 >
5304 {fetching ? t("settings.fetchingModels") : t("settings.fetchModels")}
5305 </button>
5306 <button
5307 className="btn btn--small provider-profile-row__configure"
5308 disabled={busy}
5309 aria-expanded={profileExpanded}
5310 onClick={() => profileExpanded ? onCancelEdit() : onEdit(p.name)}
5311 >
5312 {profileExpanded ? t("common.collapse") : t("settings.configureProfile")}
5313 </button>
5314 </div>
5315 );
5316 })}
5317 </div>
5318 );
5319 return (
5320 <article className={`provider-access-card${detail ? " provider-access-card--detail" : ""}${group.builtIn ? " provider-access-card--builtin" : ""}`}>
5321 <div className="provider-access-card__head">
5322 <div className="provider-access-card__identity">
5323 <div className="provider-access-card__title">
5324 {onRename ? <ConnectionTitle label={group.label} busy={busy} onSave={onRename} /> : group.label}
5325 {!detail && <span className={`badge ${group.builtIn ? "badge--project" : "badge--neutral"}`}>
5326 {group.builtIn ? t("settings.builtinProviderBadge") : t("settings.customProviderBadge")}
5327 </span>}
5328 <span className={`badge ${group.keySet ? "badge--project" : "badge--feedback"}`}>
5329 {providerKeyStatusLabel(group, t)}
5330 </span>
5331 </div>
5332 </div>
5333 <div className="provider-access-card__actions">
5334 {onCopy && <button type="button" className="btn provider-icon-action" disabled={busy} onClick={onCopy} title={t("settings.connections.copy")} aria-label={t("settings.connections.copy")}><Files size={17} /></button>}
5335 {editableProvider && !isOpenCodeGoConnection && !detail && (
5336 <button
5337 className="btn btn--small"
5338 disabled={busy}
5339 aria-expanded={primaryProviderExpanded}
5340 onClick={() => primaryProviderExpanded ? onCancelEdit() : onEdit(editableProvider.name)}
5341 >
5342 {primaryProviderExpanded ? t("common.collapse") : t("settings.configureProvider")}
5343 </button>
5344 )}
5345 {editableProvider && group.providers.length === 1 && !detail && (
5346 <button
5347 className="btn btn--small"
5348 disabled={busy || fetching || !editableProvider.baseUrl || !group.configured}
5349 onClick={() => onRefresh(editableProvider)}
5350 >
5351 {fetching ? t("settings.fetchingModels") : t("settings.fetchModels")}
5352 </button>
5353 )}
5354 {editableProvider && onDelete && (
5355 <ProviderAccessMoreMenu
5356 busy={busy}
5357 builtIn={group.builtIn}
5358 onRemove={() => onDelete(group.providers)}
5359 />
5360 )}
5361 </div>
5362 </div>
5363 {group.description && !editingProvider && <div className="provider-access-card__desc">{group.description}</div>}
5364
5365 {upgradeProvider && (
5366 <div className="provider-protocol-upgrade">
5367 <div className="provider-protocol-upgrade__copy">
5368 <div className="provider-protocol-upgrade__title">
5369 {t("settings.providerProtocol")}: OpenAI Chat Completions
5370 </div>
5371 <div className="provider-protocol-upgrade__desc">{t("settings.addProvider.official.deepseekDesc")}</div>
5372 </div>
5373 <div className="provider-protocol-upgrade__actions">
5374 <InlineConfirmButton
5375 label={<>{t("settings.upgradeRecommendedProtocol")}<ArrowRight size={13} aria-hidden="true" /></>}
5376 confirmLabel={t("common.confirm")}
5377 cancelLabel={t("common.cancel")}
5378 disabled={busy}
5379 primary
5380 onConfirm={() => onUpgradeRecommended(canonicalOfficialProviderName(upgradeProvider.name))}
5381 />
5382 </div>
5383 </div>
5384 )}
5385
5386 {!supportsServerWebSearch && !(detail && editingProvider) && (
5387 <ProviderModelSummary
5388 configured={group.configured}
5389 models={visibleModels}
5390 hiddenModelCount={hiddenModelCount}
5391 />
5392 )}
5393
5394 {!group.configured && group.requiresKey && (
5395 <div className="provider-card-status provider-card-status--warn">
5396 {t("settings.modelsRequireKey")}
5397 </div>
5398 )}
5399 {fetchResult && (
5400 <div className={`provider-card-status provider-card-status--${fetchResult.kind}`}>
5401 {fetchResult.kind === "warn" ? <ErrorMessage error={fetchResult.text} /> : fetchResult.text}
5402 </div>
5403 )}
5404
5405 {modelDraft && (
5406 <ProviderModelDraftPicker
5407 draft={modelDraft}
5408 busy={busy}
5409 fetching={fetching}
5410 onToggle={onToggleDraftModel}
5411 onSelectAll={onSelectAllDraftModels}
5412 onClear={onClearDraftModels}
5413 onCancel={onCancelDraftModels}
5414 onSave={onSaveDraftModels}
5415 />
5416 )}
5417
5418 {editableProvider && !(detail && editingProvider) && (
5419 <ProviderServiceCapabilities
5420 supported={supportsServerWebSearch}
5421 configured={group.configured}
5422 models={visibleModels}
5423 hiddenModelCount={hiddenModelCount}
5424 showModelSummary
5425 enabled={webSearchEnabled}
5426 disabled={busy}
5427 onChange={onToggleWebSearch}
5428 />
5429 )}
5430
5431 {!detail && <ProviderTechnicalDetails group={group} />}
5432
5433 {group.providers.length > 1 && (isOpenCodeGoConnection ? (
5434 <details className="provider-route-settings">
5435 <summary>{t("settings.addProvider.manageRoutes")}</summary>
5436 {providerProfiles}
5437 </details>
5438 ) : providerProfiles)}
5439
5440 {editingProvider && (
5441 <ProviderEditor
5442 key={`${editingProvider.name}:${editorRevision}`}
5443 initial={editingProvider}
5444 hideConnectionName={detail}
5445 providerPresets={providerPresets}
5446 kinds={kinds}
5447 busy={busy}
5448 onCancel={() => { onCancelEdit(); setEditorRevision((n) => n + 1); }}
5449 onSave={onSave}
5450 onSaveKey={onSaveEditorKey}
5451 onClearKey={onClearEditorKey}
5452 />
5453 )}
5454 </article>
5455 );
5456 }
5457
5458 function ProviderModelSummary({
5459 configured,
5460 models,
5461 hiddenModelCount,
5462 compact = false,
5463 }: {
5464 configured: boolean;
5465 models: string[];
5466 hiddenModelCount: number;
5467 compact?: boolean;
5468 }) {
5469 const t = useT();
5470 const label = t(configured ? "settings.enabledModels" : "settings.modelList");
5471 return (
5472 <div className={`provider-card-block${compact ? " provider-card-block--inline" : ""}`}>
5473 <div className="provider-card-block__label">{label}</div>
5474 <div className="provider-model-chips" aria-label={label}>
5475 {models.length > 0 ? models.map((model) => (
5476 <span className="provider-model-chip" key={model}>
5477 {model}
5478 </span>
5479 )) : <span className="provider-model-chip provider-model-chip--empty">{t("settings.noModelsConfigured")}</span>}
5480 {hiddenModelCount > 0 && (
5481 <span className="provider-model-chip provider-model-chip--more">
5482 {t("settings.moreModels", { n: hiddenModelCount })}
5483 </span>
5484 )}
5485 </div>
5486 </div>
5487 );
5488 }
5489
5490 function ProviderTechnicalDetails({ group }: { group: ProviderAccessGroup }) {
5491 const t = useT();
5492 const imageInputUnsupported = group.providers.length > 0 && group.providers.every((provider) => providerVisionCapabilityForView(provider) === "unsupported");
5493 return (
5494 <details className="provider-technical-details">
5495 <summary>{t("settings.providerAccess")}</summary>
5496 <dl>
5497 {group.providers.length === 1 ? (
5498 <>
5499 <div><dt>{t("settings.providerProtocol")}</dt><dd>{providerProtocolDisplayName(group.kind)}</dd></div>
5500 <div><dt>{t("settings.providerBaseUrlLabel")}</dt><dd>{group.baseUrl || t("common.none")}</dd></div>
5501 </>
5502 ) : group.providers.map((provider) => (
5503 <div key={provider.name}><dt>{provider.name}</dt><dd>{providerProtocolDisplayName(provider.kind)} · {provider.baseUrl || t("common.none")}</dd></div>
5504 ))}
5505 <div>
5506 <dt>{t("settings.providerApiKeyEnv")}</dt>
5507 <dd>{group.apiKeyEnv || t("common.none")}</dd>
5508 </div>
5509 {imageInputUnsupported && (
5510 <div>
5511 <dt>{t("settings.visionModel")}</dt>
5512 <dd>{t("settings.imageInputUnsupported")}</dd>
5513 </div>
5514 )}
5515 {group.keySource && (
5516 <div>
5517 <dt>{t("settings.providerKey")}</dt>
5518 <dd title={group.keySourcePath || undefined}>{group.keySource}</dd>
5519 </div>
5520 )}
5521 </dl>
5522 </details>
5523 );
5524 }
5525
5526 function providerProtocolDisplayName(kind: string): string {
5527 return providerProtocolLabel(kind);
5528 }
5529
5530 function ProviderAccessMoreMenu({
5531 busy,
5532 builtIn,
5533 onRemove,
5534 }: {
5535 busy: boolean;
5536 builtIn: boolean;
5537 onRemove: () => void | Promise<void>;
5538 }) {
5539 const t = useT();
5540 const [open, setOpen] = useState(false);
5541 const triggerRef = useRef<HTMLButtonElement>(null);
5542 const disabled = busy;
5543 const tooltip = t("settings.themeGallery.moreActions");
5544
5545 return (
5546 <div className="provider-access-more">
5547 <Tooltip label={tooltip}>
5548 <button
5549 ref={triggerRef}
5550 type="button"
5551 className="btn btn--small provider-access-more__trigger"
5552 aria-label={t("settings.themeGallery.moreActions")}
5553 aria-haspopup="menu"
5554 aria-expanded={open}
5555 disabled={disabled}
5556 onClick={() => setOpen((current) => !current)}
5557 >
5558 <MoreHorizontal size={16} aria-hidden="true" />
5559 </button>
5560 </Tooltip>
5561 <AnchoredPopover
5562 open={open && !disabled}
5563 anchorRef={triggerRef}
5564 onClose={() => setOpen(false)}
5565 className="provider-access-more__menu"
5566 align="end"
5567 placement="bottom"
5568 >
5569 <div className="provider-access-more__items" role="menu" aria-label={t("settings.themeGallery.moreActions")}>
5570 <InlineConfirmButton
5571 label={<><Trash2 size={14} aria-hidden="true" />{t("settings.removeProviderAccess")}</>}
5572 confirmLabel={builtIn ? t("settings.confirmRemoveProviderAccess") : t("settings.confirmDeleteProvider")}
5573 cancelLabel={t("common.cancel")}
5574 danger={!builtIn}
5575 buttonRole="menuitem"
5576 onConfirm={async () => {
5577 setOpen(false);
5578 await onRemove();
5579 }}
5580 />
5581 </div>
5582 </AnchoredPopover>
5583 </div>
5584 );
5585 }
5586
5587 function ProviderModelDraftPicker({
5588 draft,
5589 busy,
5590 fetching,
5591 onToggle,
5592 onSelectAll,
5593 onClear,
5594 onCancel,
5595 onSave,
5596 }: {
5597 draft: ProviderModelDraft;
5598 busy: boolean;
5599 fetching: boolean;
5600 onToggle: (model: string) => void;
5601 onSelectAll: () => void;
5602 onClear: () => void;
5603 onCancel: () => void;
5604 onSave: () => void;
5605 }) {
5606 const t = useT();
5607 const [query, setQuery] = useState("");
5608 const [debouncedQuery, setDebouncedQuery] = useState("");
5609 // Debounce search to avoid expensive filtering on every keystroke
5610 useEffect(() => {
5611 const timer = setTimeout(() => setDebouncedQuery(query), 150);
5612 return () => clearTimeout(timer);
5613 }, [query]);
5614 const selected = new Set(draft.selected);
5615 const q = debouncedQuery.trim().toLowerCase();
5616 const visibleCandidates = useMemo(
5617 () => (q ? draft.candidates.filter((model) => model.toLowerCase().includes(q)) : draft.candidates),
5618 [draft.candidates, q],
5619 );
5620 const deferredCandidates = useDeferredValue(visibleCandidates);
5621 const disabled = busy || fetching;
5622
5623 return (
5624 <div className="provider-model-draft">
5625 <div className="provider-model-draft__head">
5626 <div>
5627 <span>{t("settings.modelCandidatesSelected", { n: draft.selected.length })}</span>
5628 </div>
5629 <div className="provider-model-draft__tools">
5630 <button type="button" className="btn btn--small" disabled={disabled || draft.selected.length === draft.candidates.length} onClick={onSelectAll} title={t("settings.selectAllModels")} aria-label={t("settings.selectAllModels")}>
5631 <ListChecks size={17} />
5632 </button>
5633 <button type="button" className="btn btn--small" disabled={disabled || draft.selected.length === 0} onClick={onClear} title={t("settings.clearModelSelection")} aria-label={t("settings.clearModelSelection")}>
5634 <Check size={17} style={{ opacity: .4 }} />
5635 </button>
5636 </div>
5637 </div>
5638 <input
5639 className="mem-input provider-model-draft__search"
5640 placeholder={t("settings.modelCandidateSearch")}
5641 value={query}
5642 disabled={disabled}
5643 onChange={(e) => setQuery(e.target.value)}
5644 />
5645 <div className="provider-model-draft__list" role="list" aria-label={t("settings.modelList")}>
5646 {deferredCandidates.length > 0 ? deferredCandidates.map((model) => {
5647 const enabled = selected.has(model);
5648 const capability = providerModelVisionCapability(
5649 { visionModelsConfigured: draft.visionModelsConfigured, modelCapabilities: draft.modelCapabilities },
5650 model,
5651 draft.visionModels,
5652 );
5653 return (
5654 <div className="provider-model-draft__option" key={model} role="listitem">
5655 <label className="provider-model-draft__model">
5656 <input
5657 type="checkbox"
5658 checked={enabled}
5659 disabled={disabled}
5660 onChange={() => onToggle(model)}
5661 />
5662 <span>{model}</span>
5663 </label>
5664 <div className="provider-model-draft__capabilities" aria-label={t("settings.modelCapabilitiesAria", { model })}>
5665 <span>{t("settings.textInput")}</span>
5666 <span>{capability === "supported"
5667 ? t("settings.visionModel")
5668 : capability === "unsupported"
5669 ? t("settings.imageInputUnsupported")
5670 : t("settings.imageInputUnknown")}</span>
5671 </div>
5672 </div>
5673 );
5674 }) : (
5675 <div className="provider-model-draft__empty">{t("settings.noMatchingCandidateModels")}</div>
5676 )}
5677 </div>
5678 <div className="provider-model-draft__actions">
5679 <button type="button" className="btn btn--small" disabled={disabled} onClick={onCancel}>
5680 {t("common.cancel")}
5681 </button>
5682 <button type="button" className="btn btn--primary btn--small" disabled={disabled || draft.selected.length === 0} onClick={onSave}>
5683 {t("settings.saveEnabledModels")}
5684 </button>
5685 </div>
5686 </div>
5687 );
5688 }
5689
5690 function ProviderServiceCapabilities({
5691 supported,
5692 configured,
5693 models,
5694 hiddenModelCount,
5695 showModelSummary = false,
5696 enabled,
5697 disabled,
5698 onChange,
5699 }: {
5700 supported: boolean;
5701 configured?: boolean;
5702 models: string[];
5703 hiddenModelCount?: number;
5704 showModelSummary?: boolean;
5705 enabled: boolean;
5706 disabled: boolean;
5707 onChange: (enabled: boolean) => void;
5708 }) {
5709 const t = useT();
5710 const capabilityID = useId();
5711 if (!supported) return null;
5712 return (
5713 <section className="provider-capabilities" aria-labelledby={capabilityID}>
5714 <div className="provider-card-block__label" id={capabilityID}>
5715 {t("settings.providerCapabilities")}
5716 </div>
5717 {showModelSummary && (
5718 <ProviderModelSummary
5719 configured={Boolean(configured)}
5720 models={models}
5721 hiddenModelCount={hiddenModelCount ?? 0}
5722 compact
5723 />
5724 )}
5725 <label className="provider-capability-row">
5726 <span className="provider-capability-row__copy">
5727 <span className="provider-capability-row__title">
5728 {t("settings.serverWebSearch")}
5729 <span className="badge badge--project">{t("settings.recommended")}</span>
5730 </span>
5731 <span>{t("settings.serverWebSearchHint")}</span>
5732 </span>
5733 <input
5734 className="provider-capability-row__switch"
5735 type="checkbox"
5736 role="switch"
5737 checked={enabled}
5738 disabled={disabled}
5739 onChange={(event) => onChange(event.target.checked)}
5740 />
5741 </label>
5742 </section>
5743 );
5744 }
5745
5746 export function providerAccessGroups(providers: ProviderView[], t: ReturnType<typeof useT>): ProviderAccessGroup[] {
5747 const groups = new Map<string, ProviderAccessGroup>();
5748 for (const p of providers) {
5749 const id = providerGroupID(p);
5750 const builtIn = id.startsWith("builtin:");
5751 const existing = groups.get(id);
5752 if (existing) {
5753 existing.providers.push(p);
5754 existing.keySet = existing.keySet || p.keySet;
5755 existing.requiresKey = existing.requiresKey && providerRequiresKey(p);
5756 existing.configured = existing.configured || providerIsConfigured(p);
5757 existing.recommendedUpgradeAvailable = existing.recommendedUpgradeAvailable || Boolean(p.recommendedUpgradeAvailable);
5758 if (existing.recommendedUpgradeAvailable && existing.id === "builtin:deepseek") {
5759 existing.description = "";
5760 }
5761 if (!existing.keySource && p.keySource) existing.keySource = p.keySource;
5762 if (!existing.keySourcePath && p.keySourcePath) existing.keySourcePath = p.keySourcePath;
5763 existing.models = uniqueStrings([...existing.models, ...p.models]);
5764 continue;
5765 }
5766 groups.set(id, {
5767 id,
5768 label: providerGroupLabel(p, t),
5769 description: providerGroupDescription(p, t),
5770 builtIn,
5771 providers: [p],
5772 apiKeyEnv: p.apiKeyEnv,
5773 keySet: p.keySet,
5774 requiresKey: providerRequiresKey(p),
5775 configured: providerIsConfigured(p),
5776 keySource: p.keySource,
5777 keySourcePath: p.keySourcePath,
5778 baseUrl: p.baseUrl,
5779 kind: p.kind,
5780 models: uniqueStrings(p.models),
5781 recommendedUpgradeAvailable: Boolean(p.recommendedUpgradeAvailable),
5782 });
5783 }
5784 return Array.from(groups.values());
5785 }
5786
5787 function providerBaseHost(baseUrl: string): string {
5788 try {
5789 return new URL(baseUrl).hostname.toLowerCase();
5790 } catch {
5791 return "";
5792 }
5793 }
5794
5795 type ProviderVisionCapability = "configurable" | "unsupported";
5796
5797
5798
5799 export function providerSupportsServerWebSearchForView(
5800 provider: Pick<ProviderView, "kind" | "baseUrl" | "serverWebSearchCapability">,
5801 ): boolean {
5802 if (typeof provider.serverWebSearchCapability === "boolean") {
5803 return provider.serverWebSearchCapability;
5804 }
5805 return providerSupportsServerWebSearch(provider.kind, provider.baseUrl);
5806 }
5807
5808 export function providerVisionCapabilityForView(
5809 provider: Pick<ProviderView, "kind" | "baseUrl" | "visionCapability">,
5810 ): ProviderVisionCapability {
5811 if (provider.visionCapability === "unsupported") {
5812 return "unsupported";
5813 }
5814 return "configurable";
5815 }
5816
5817 function canonicalOfficialProviderName(name: string): string {
5818 switch (name.trim()) {
5819 case "deepseek-flash":
5820 case "deepseek-pro":
5821 return "deepseek";
5822 default:
5823 return name.trim();
5824 }
5825 }
5826
5827 function officialProviderKind(p: ProviderView): string {
5828 if (!p.builtIn) return "";
5829 const name = canonicalOfficialProviderName(p.name);
5830 const host = providerBaseHost(p.baseUrl);
5831 if (name === "deepseek" && host === "api.deepseek.com") return "deepseek";
5832 return "";
5833 }
5834
5835 function providerGroupID(p: ProviderView): string {
5836 const official = officialProviderKind(p);
5837 if (official) return `builtin:${official}`;
5838 if (isOpenCodeGoProviderName(p.name)) return "custom:opencode-go";
5839 if (p.name === "opencode-zen-anthropic") return "custom:opencode-zen";
5840 return `custom:${p.name}`;
5841 }
5842
5843 function providerGroupLabel(p: ProviderView, t?: ReturnType<typeof useT>): string {
5844 if (p.displayName?.trim()) return p.displayName.trim();
5845 const id = providerGroupID(p);
5846 if (id === "builtin:deepseek") return t ? t("settings.providerLabel.deepseek") : "DeepSeek";
5847 if (id === "custom:opencode-go") return t ? t("settings.providerLabel.opencodeGo") : "OpenCode Go";
5848 if (id === "custom:opencode-zen") return t ? t("settings.providerLabel.opencodeZen") : "OpenCode Zen";
5849 return p.name;
5850 }
5851
5852 function providerGroupDescription(p: ProviderView, t: ReturnType<typeof useT>): string {
5853 const id = providerGroupID(p);
5854 if (id === "builtin:deepseek") {
5855 return p.recommendedUpgradeAvailable ? "" : providerProtocolLabel(p.kind);
5856 }
5857 if (id === "custom:opencode-go") return t("settings.providerDesc.opencodeGo");
5858 if (id === "custom:opencode-zen") return t("settings.providerDesc.opencodeZen");
5859 return "";
5860 }
5861
5862 function isOpenCodeGoProviderName(name: string): boolean {
5863 switch (name.trim()) {
5864 case "opencode-go":
5865 case "opencode-go-anthropic":
5866 case "opencode-go-responses":
5867 case "opencode-go-deepseek-anthropic":
5868 case "opencode-go-deepseek-responses":
5869 return true;
5870 default:
5871 return false;
5872 }
5873 }
5874
5875 function uniqueStrings(values: string[]): string[] {
5876 const seen = new Set<string>();
5877 const out: string[] = [];
5878 for (const value of values) {
5879 if (value && !seen.has(value)) {
5880 seen.add(value);
5881 out.push(value);
5882 }
5883 }
5884 return out;
5885 }
5886
5887 function parseProviderListInput(value: string): string[] {
5888 return uniqueStrings(value
5889 .split(/[,,]/)
5890 .map((entry) => entry.trim())
5891 .filter(Boolean));
5892 }
5893
5894 function botAllowlistTextValues(allowlist: BotAllowlistView): Record<BotAllowlistTextKey, string> {
5895 return {
5896 qqUsers: allowlist.qqUsers.join("\n"),
5897 feishuUsers: allowlist.feishuUsers.join("\n"),
5898 weixinUsers: allowlist.weixinUsers.join("\n"),
5899 qqApprovers: allowlist.qqApprovers.join("\n"),
5900 feishuApprovers: allowlist.feishuApprovers.join("\n"),
5901 weixinApprovers: allowlist.weixinApprovers.join("\n"),
5902 qqAdmins: allowlist.qqAdmins.join("\n"),
5903 feishuAdmins: allowlist.feishuAdmins.join("\n"),
5904 weixinAdmins: allowlist.weixinAdmins.join("\n"),
5905 qqGroups: allowlist.qqGroups.join("\n"),
5906 feishuGroups: allowlist.feishuGroups.join("\n"),
5907 weixinGroups: allowlist.weixinGroups.join("\n"),
5908 dingtalkUsers: allowlist.dingtalkUsers.join("\n"),
5909 dingtalkApprovers: allowlist.dingtalkApprovers.join("\n"),
5910 dingtalkAdmins: allowlist.dingtalkAdmins.join("\n"),
5911 dingtalkGroups: allowlist.dingtalkGroups.join("\n"),
5912 };
5913 }
5914
5915 function botSelfUserTextValues(selfUserIds: BotSettingsView["selfUserIds"]): Record<BotSelfUserTextKey, string> {
5916 return {
5917 qq: selfUserIds.qq.join("\n"),
5918 feishu: selfUserIds.feishu.join("\n"),
5919 weixin: selfUserIds.weixin.join("\n"),
5920 dingtalk: selfUserIds.dingtalk.join("\n"),
5921 };
5922 }
5923
5924 function parseBotListInput(value: string): string[] {
5925 return uniqueStrings(value
5926 .split(/[\n,,]+/)
5927 .map((entry) => entry.trim())
5928 .filter(Boolean));
5929 }
5930
5931 const ProviderModelDialog = lazy(() => import("./ProviderModelDialog"));
5932
5933 export const ProviderEditorModelPicker = memo(function ProviderEditorModelPicker({
5934 actions,
5935 candidates,
5936 selectedModels,
5937 visionModels,
5938 visionModelsConfigured,
5939 modelCapabilities,
5940 contextWindows,
5941 inheritedContextWindow,
5942 disabled,
5943 onToggleModel,
5944 onEditModel,
5945 onSelectAll,
5946 onClear,
5947 }: {
5948 actions?: ReactNode;
5949 candidates: string[];
5950 selectedModels: string[];
5951 visionModels: string[];
5952 visionModelsConfigured: boolean;
5953 modelCapabilities: ProviderModelCapabilityView[];
5954 contextWindows: Record<string, string>;
5955 inheritedContextWindow?: number;
5956 disabled: boolean;
5957 onToggleModel: (model: string) => void;
5958 onEditModel?: (model: string) => void;
5959 onSelectAll: () => void;
5960 onClear: () => void;
5961 }) {
5962 const t = useT();
5963 const [query, setQuery] = useState("");
5964 const [debouncedQuery, setDebouncedQuery] = useState("");
5965 useEffect(() => {
5966 const timer = setTimeout(() => setDebouncedQuery(query), 150);
5967 return () => clearTimeout(timer);
5968 }, [query]);
5969 const q = debouncedQuery.trim().toLowerCase();
5970 const visibleCandidates = q
5971 ? candidates.filter((model) => model.toLowerCase().includes(q))
5972 : candidates;
5973 const deferredCandidates = useDeferredValue(visibleCandidates);
5974 const selected = new Set(selectedModels);
5975 return (
5976 <div className="provider-model-draft provider-model-draft--inline">
5977 <div className="provider-model-draft__head provider-model-toolbar">
5978 <strong>{t("settings.modelList")}</strong>
5979 <span>{t("settings.modelCandidatesSelected", { n: selectedModels.length })}</span>
5980 <div className="provider-model-draft__tools">
5981 {actions}
5982 <details className="provider-key-compact__more">
5983 <summary className="btn provider-icon-action" title={t("settings.themeGallery.moreActions")} aria-label={t("settings.themeGallery.moreActions")}><MoreHorizontal size={17} /></summary>
5984 <div className="provider-key-compact__menu">
5985 <button type="button" className="btn" disabled={disabled || selectedModels.length === candidates.length} onClick={onSelectAll}>{t("settings.selectAllModels")}</button>
5986 <button type="button" className="btn" disabled={disabled || selectedModels.length === 0} onClick={onClear}>{t("settings.clearModelSelection")}</button>
5987 </div>
5988 </details>
5989 </div>
5990 </div>
5991
5992 {candidates.length > 8 && (
5993 <input
5994 className="mem-input provider-model-draft__search"
5995 placeholder={t("settings.modelCandidateSearch")}
5996 value={query}
5997 disabled={disabled}
5998 onChange={(e) => setQuery(e.target.value)}
5999 />
6000 )}
6001 <div className="provider-model-draft__list" role="list" aria-label={t("settings.modelList")}>
6002 {deferredCandidates.length > 0 ? deferredCandidates.map((model) => {
6003 const enabled = selected.has(model);
6004 const capability = providerModelVisionCapability(
6005 { visionModelsConfigured, modelCapabilities },
6006 model,
6007 visionModels,
6008 );
6009 return (
6010 <div className="provider-model-draft__option" key={model} role="listitem">
6011 <label className="provider-model-draft__model">
6012 <input
6013 type="checkbox"
6014 checked={enabled}
6015 disabled={disabled}
6016 onChange={() => onToggleModel(model)}
6017 />
6018 <span title={model}>{model}</span>
6019 </label>
6020 <div className="provider-model-draft__capabilities" aria-label={t("settings.modelCapabilitiesAria", { model })}>
6021 {capability === "supported" && <span>{t("settings.visionModel")}</span>}
6022 {capability === "unknown" && <span>{t("settings.imageInputUnknown")}</span>}
6023 </div>
6024 <span className="provider-context-badge">{Number(contextWindows[model]) || inheritedContextWindow ? new Intl.NumberFormat("en", {notation:"compact",maximumFractionDigits:1}).format(Number(contextWindows[model]) || inheritedContextWindow!) : t("settings.models.inherit")}</span>
6025 <button type="button" className="btn provider-icon-action" title={t("settings.models.options")} aria-label={`${t("settings.models.options")}: ${model}`} aria-haspopup="dialog" disabled={disabled || !onEditModel} onClick={()=>onEditModel?.(model)}><SlidersHorizontal size={17}/></button>
6026 </div>
6027 );
6028 }) : (
6029 <div className="provider-model-draft__empty">{t("settings.noMatchingCandidateModels")}</div>
6030 )}
6031 </div>
6032 </div>
6033 );
6034 });
6035
6036 export function ProviderEditor({
6037 hideConnectionName = false,
6038 initial,
6039 providerPresets = [],
6040 kinds,
6041 busy,
6042 onCancel,
6043 onSave,
6044 }: {
6045 hideConnectionName?: boolean;
6046 initial?: ProviderView;
6047 providerPresets?: ProviderPresetView[];
6048 kinds: string[];
6049 busy: boolean;
6050 onCancel: () => void;
6051 onSave: (p: ProviderView, key?: string) => void | Promise<void>;
6052 onSaveKey?: (apiKeyEnv: string, value: string) => Promise<void>;
6053 onClearKey?: (apiKeyEnv: string) => Promise<void>;
6054 }) {
6055 const t = useT();
6056 const [name, setName] = useState(initial?.name ?? "");
6057 const [displayName, setDisplayName] = useState(initial?.displayName ?? "");
6058 const [kind, setKind] = useState(initial?.kind ?? "openai");
6059 const [requestUrl, setRequestUrl] = useState(() => providerRequestURLFromConfig(
6060 initial?.kind ?? "openai",
6061 initial?.baseUrl ?? "",
6062 initial?.requestUrl ?? "",
6063 initial?.chatUrl ?? "",
6064 ));
6065 const providerNameInputId = useId();
6066 const providerUrlInputId = useId();
6067 const providerUrlHelpId = useId();
6068 const [models, setModels] = useState((initial?.models ?? []).join(", "));
6069 const [modelDialog, setModelDialog] = useState<string | null>(null);
6070 const [modelOverrides, setModelOverrides] = useState(initial?.modelOverrides ?? []);
6071 const [showKey, setShowKey] = useState(false);
6072 const [modelCandidates, setModelCandidates] = useState<string[]>(initial?.models ?? []);
6073 const [legacyVisionModels, setLegacyVisionModels] = useState(initial?.visionModels ?? []);
6074 const [modelCapabilities, setModelCapabilities] = useState<ProviderModelCapabilityView[]>(initial?.modelCapabilities ?? []);
6075 const visionModelsConfigured = Boolean(initial?.visionModelsConfigured ?? legacyVisionModels.length > 0);
6076 const [modelsUrl, setModelsUrl] = useState(initial?.modelsUrl ?? "");
6077 const [apiKeyEnv, setApiKeyEnv] = useState(initial?.apiKeyEnv ?? "");
6078 useEffect(() => { if (initial) setApiKeyEnv(initial.apiKeyEnv); }, [initial?.apiKeyEnv]);
6079 const [headersDraft, setHeadersDraft] = useState(formatProviderHeaders(initial?.headers));
6080 const [extraBodyDraft, setExtraBodyDraft] = useState(formatProviderExtraBody(initial?.extraBody));
6081 const [authHeader, setAuthHeader] = useState(Boolean(initial?.authHeader));
6082 const [noProxy, setNoProxy] = useState(Boolean(initial?.noProxy));
6083 const [keyDraft, setKeyDraft] = useState("");
6084 const [balanceUrl, setBalanceUrl] = useState(initial?.balanceUrl ?? "");
6085 // Empty when unset so the placeholder (and its "0 = disabled" hint) reads instead
6086 // of a bare "0"; saved back as 0.
6087 const [ctx, setCtx] = useState(initial?.contextWindow ? String(initial.contextWindow) : "");
6088 const [modelContextWindows, setModelContextWindows] = useState<Record<string, string>>(
6089 () => providerModelContextWindowDrafts(initial?.modelOverrides),
6090 );
6091 const [reasoningProtocol, setReasoningProtocol] = useState(normalizeReasoningProtocol(initial?.reasoningProtocol));
6092 const [thinking, setThinking] = useState(normalizeThinkingMode(initial?.thinking));
6093 const [webSearch, setWebSearch] = useState(Boolean(initial?.webSearch));
6094 const [supportedEfforts] = useState<string[]>(initial?.supportedEfforts ?? []);
6095 const [defaultEffort] = useState(initial?.defaultEffort ?? "");
6096 const [fetchingModels, setFetchingModels] = useState(false);
6097 const [fetchStatus, setFetchStatus] = useState<string | null>(null);
6098 const [fetchFallback, setFetchFallback] = useState<string | null>(null);
6099 const [advancedOpen, setAdvancedOpen] = useState(false);
6100 const draftSnapshot = JSON.stringify([name, hideConnectionName ? "" : displayName, kind, requestUrl, models, modelsUrl, headersDraft, extraBodyDraft, authHeader, noProxy, keyDraft, balanceUrl, ctx, modelContextWindows, modelOverrides, modelCapabilities, legacyVisionModels, reasoningProtocol, thinking, webSearch]);
6101 const [savedSnapshot, setSavedSnapshot] = useState(draftSnapshot);
6102 const latestDraftSnapshot = useRef(draftSnapshot);
6103 const saveGeneration = useRef(0);
6104 latestDraftSnapshot.current = draftSnapshot;
6105 const dirty = draftSnapshot !== savedSnapshot;
6106 const isNewCustomProvider = !initial;
6107 const editorCatalog = useMemo(() => {
6108 if (initial?.catalog) return initial.catalog;
6109 if (initial?.presetId) {
6110 const preset = providerPresets.find(item => item.id === initial.presetId);
6111 if (preset) return catalogForPreset(preset);
6112 }
6113 const catalogs = providerPresets.map(catalogForPreset);
6114 return catalogs.find(catalog => Object.entries(catalog.protocols ?? {}).some(([routeKind, route]) =>
6115 providerRequestURLFromConfig(routeKind, route.baseUrl, "") === requestUrl,
6116 ));
6117 }, [initial?.catalog, initial?.presetId, providerPresets, requestUrl]);
6118 const providerKindChoices = useMemo(() => {
6119 const registered = editorCatalog ? Object.keys(editorCatalog.protocols ?? {}) : kinds;
6120 const choices = providerProtocolChoices(kind, initial?.kind, registered, Boolean(editorCatalog));
6121 return choices.length > 0 ? choices : ["openai"];
6122 }, [editorCatalog, kind, initial?.kind, kinds]);
6123 const effectiveKind = providerEditorEffectiveKind(isNewCustomProvider, kind, providerKindChoices);
6124 const effectiveRequestUrl = requestUrl.trim();
6125 const endpointMismatch = providerEndpointMismatchDetail(effectiveKind, effectiveRequestUrl, editorCatalog);
6126 const effectiveBaseUrl = providerBaseURLForSave(initial, effectiveKind, effectiveRequestUrl);
6127 const effectiveLegacyChatUrl = effectiveKind.toLowerCase() === "openai" ? effectiveRequestUrl : initial?.chatUrl ?? "";
6128 const effectiveModelsUrl = modelsUrl.trim();
6129 const initialEffectiveBaseUrl = initial ? trimmedBaseURL(initial.baseUrl) : "";
6130 const retainedServerWebSearchCapability = initial &&
6131 effectiveKind.trim().toLowerCase() === initial.kind.trim().toLowerCase() &&
6132 trimmedBaseURL(effectiveBaseUrl) === initialEffectiveBaseUrl
6133 ? initial.serverWebSearchCapability
6134 : undefined;
6135 const effectiveServerWebSearchCapability = retainedServerWebSearchCapability ??
6136 providerSupportsServerWebSearch(effectiveKind, effectiveBaseUrl);
6137 const effectiveHeaders = parseProviderHeaders(headersDraft);
6138 const extraBodyParse = useMemo(() => {
6139 try {
6140 return { value: parseProviderExtraBody(extraBodyDraft, t), error: "" };
6141 } catch (e) {
6142 return { value: {}, error: providerExtraBodyParseError(e, t) };
6143 }
6144 }, [extraBodyDraft, t]);
6145 const effectiveExtraBody = extraBodyParse.value;
6146 const extraBodyInvalid = Boolean(extraBodyDraft.trim() && extraBodyParse.error);
6147 const modelNames = useMemo(
6148 () => parseProviderListInput(models),
6149 [models],
6150 );
6151 const modelCandidateNames = useMemo(
6152 () => uniqueStrings([...modelCandidates, ...modelNames]),
6153 [modelCandidates, modelNames],
6154 );
6155 const visionModelNames = useMemo(
6156 () => providerVisionModelsForView({models:modelNames, visionModels:legacyVisionModels, modelOverrides, modelCapabilities}),
6157 [modelNames, legacyVisionModels, modelOverrides, modelCapabilities],
6158 );
6159
6160 // Empty supportedEfforts means "use protocol defaults". The simplified
6161 // provider flow no longer edits these levels directly, but it preserves
6162 // existing advanced TOML unless the user explicitly disables reasoning.
6163 const cleanedSupportedEfforts = reasoningProtocol !== "none"
6164 ? uniqueStrings(
6165 supportedEfforts
6166 .map((level) => level.toLowerCase().trim())
6167 .filter((level) => level && level !== "auto")
6168 )
6169 : [];
6170 // An empty explicit list inherits backend options; it does not invalidate a
6171 // saved default. Preserve declarations (and diagnostics) on unrelated edits.
6172 const cleanDefaultEffort = reasoningProtocol === "none" ? "" : defaultEffort.toLowerCase().trim();
6173
6174 const fetchModels = async () => {
6175 if (extraBodyInvalid) return;
6176 setFetchingModels(true);
6177 setFetchStatus(null);
6178 setFetchFallback(null);
6179 try {
6180 const effectiveApiKeyEnv = providerApiKeyEnvForSave(name, apiKeyEnv, keyDraft);
6181 if (!apiKeyEnv.trim()) setApiKeyEnv(effectiveApiKeyEnv);
6182 const fetchCatalog = (provider: ProviderView) => keyDraft.trim()
6183 ? app.FetchProviderModelCatalogDraft(provider, keyDraft.trim())
6184 : cachedFetchProviderModelCatalog(p => app.FetchProviderModelCatalog(p), provider, true);
6185 const fetchedCapabilities = await fetchCatalog({
6186 name: name.trim() || t("settings.newProviderDraftName"),
6187 builtIn: initial?.builtIn ?? false,
6188 added: initial?.added ?? true,
6189 kind: effectiveKind,
6190 baseUrl: effectiveBaseUrl,
6191 chatUrl: effectiveLegacyChatUrl,
6192 requestUrl: effectiveRequestUrl,
6193 modelsUrl: effectiveModelsUrl,
6194 models: [],
6195 visionModels: [],
6196 visionModelsConfigured: false,
6197 default: "",
6198 apiKeyEnv: effectiveApiKeyEnv,
6199 headers: effectiveHeaders,
6200 extraBody: effectiveExtraBody,
6201 authHeader,
6202 noProxy,
6203 keySet: Boolean(keyDraft.trim()) || (initial?.keySet ?? false),
6204 balanceUrl: balanceUrl.trim(),
6205 contextWindow: Number(ctx) || 0,
6206 reasoningProtocol,
6207 thinking,
6208 webSearch: effectiveServerWebSearchCapability && webSearch,
6209 serverWebSearchCapability: effectiveServerWebSearchCapability,
6210 supportedEfforts: cleanedSupportedEfforts,
6211 defaultEffort: cleanDefaultEffort,
6212 modelOverrides: mergeProviderModelContextWindows(modelOverrides, parseProviderListInput(models), modelContextWindows),
6213 });
6214 const fetched = fetchedCapabilities.map((item) => item.model);
6215 if (fetched.length === 0) {
6216 setFetchFallback(t("settings.fetchModelsManualFallbackEmpty"));
6217 return;
6218 }
6219 setModelCandidates(current => uniqueStrings([...current, ...fetched]));
6220 setModelCapabilities(current => [...current.filter(item => !fetched.includes(item.model)), ...fetchedCapabilities]);
6221 setFetchStatus(t("settings.fetchModelsSuccess", { n: fetched.length }));
6222 } catch (e) {
6223 setFetchFallback(providerModelFetchFallbackMessage(e, t));
6224 } finally {
6225 setFetchingModels(false);
6226 }
6227 };
6228
6229 const save = async () => {
6230 if (extraBodyInvalid) return;
6231 const generation = ++saveGeneration.current;
6232 setFetchStatus(null);
6233 setFetchFallback(null);
6234 const ms = parseProviderListInput(models);
6235 const vms = legacyVisionModels.filter((model) => ms.includes(model));
6236 const effectiveApiKeyEnv = providerApiKeyEnvForSave(name, apiKeyEnv, keyDraft);
6237 const provider: ProviderView = {
6238 name: name.trim(),
6239 ...(hideConnectionName ? {} : { displayName: displayName.trim() }),
6240 ...(initial?.presetId ? { presetId: initial.presetId } : {}),
6241 ...(initial?.catalog ? { catalog: initial.catalog } : {}),
6242 builtIn: initial?.builtIn ?? false,
6243 added: initial?.added ?? true,
6244 kind: effectiveKind,
6245 baseUrl: effectiveBaseUrl,
6246 chatUrl: effectiveLegacyChatUrl,
6247 requestUrl: effectiveRequestUrl,
6248 models: ms,
6249 visionModels: vms,
6250 visionModelsConfigured,
6251 default: providerDefaultModel(initial?.default ?? "", ms),
6252 apiKeyEnv: effectiveApiKeyEnv,
6253 headers: effectiveHeaders,
6254 extraBody: effectiveExtraBody,
6255 authHeader,
6256 noProxy,
6257 modelsUrl: effectiveModelsUrl,
6258 keySet: Boolean(keyDraft.trim()) || (initial?.keySet ?? false),
6259 balanceUrl: balanceUrl.trim(),
6260 contextWindow: Number(ctx) || 0,
6261 reasoningProtocol,
6262 thinking,
6263 webSearch: effectiveServerWebSearchCapability && webSearch,
6264 serverWebSearchCapability: effectiveServerWebSearchCapability,
6265 supportedEfforts: cleanedSupportedEfforts,
6266 defaultEffort: cleanDefaultEffort,
6267 modelOverrides: mergeProviderModelContextWindows(modelOverrides, ms, modelContextWindows),
6268 modelCapabilities,
6269 };
6270 try {
6271 await onSave(provider, keyDraft.trim() || undefined);
6272 if (generation !== saveGeneration.current) return;
6273 setShowKey(false);
6274 if (latestDraftSnapshot.current === draftSnapshot) {
6275 const committed = JSON.parse(draftSnapshot) as unknown[];
6276 committed[10] = ""; // The key draft is cleared only if no newer edit exists.
6277 setKeyDraft("");
6278 setSavedSnapshot(JSON.stringify(committed));
6279 } else {
6280 setSavedSnapshot(draftSnapshot);
6281 }
6282 } catch (e) {
6283 if (generation === saveGeneration.current && latestDraftSnapshot.current === draftSnapshot) {
6284 setFetchFallback(String((e as Error)?.message ?? e));
6285 }
6286 }
6287 };
6288
6289 const canFetch = Boolean(name.trim() && effectiveBaseUrl);
6290
6291 const setModelsFromList = (nextModels: string[]) => {
6292 setModels(uniqueStrings(nextModels).join(", "));
6293 };
6294
6295 const toggleEditorModel = (model: string) => {
6296 const selected = new Set(modelNames);
6297 if (selected.has(model)) selected.delete(model);
6298 else selected.add(model);
6299 setModelsFromList(modelCandidateNames.filter((candidate) => selected.has(candidate)));
6300 };
6301
6302 const applyModelDetails = (draft: ModelDetailsDraft) => {
6303 if (modelDialog === "") {
6304 setModelCandidates(current => uniqueStrings([...current, draft.model]));
6305 setModels(current => uniqueStrings([...parseProviderListInput(current), draft.model]).join(", "));
6306 }
6307 setModelContextWindows(current => ({...current, [draft.model]:draft.contextWindow}));
6308 setModelOverrides(current => {
6309 const previous = current.find(item => item.model === draft.model);
6310 return [...current.filter(item => item.model !== draft.model), {...previous, model:draft.model, reasoningProtocol:previous?.reasoningProtocol ?? "", supportedEfforts:draft.supportedEfforts, defaultEffort:draft.defaultEffort, vision:draft.vision, maxOutputTokens:draft.maxOutputTokens}];
6311 });
6312 setModelDialog(null);
6313 };
6314
6315 const deleteModel = () => {
6316 if (!modelDialog || busy || fetchingModels) return;
6317 const model = modelDialog;
6318 setModels(current => parseProviderListInput(current).filter(item => item !== model).join(", "));
6319 setModelCandidates(current => current.filter(item => item !== model));
6320 setModelOverrides(current => current.filter(item => item.model !== model));
6321 setModelCapabilities(current => current.filter(item => item.model !== model));
6322 setLegacyVisionModels(current => current.filter(item => item !== model));
6323 setModelContextWindows(current => Object.fromEntries(Object.entries(current).filter(([key]) => key !== model)));
6324 setModelDialog(null);
6325 };
6326
6327 const selectAllEditorModels = () => {
6328 setModelsFromList(modelCandidateNames);
6329 };
6330
6331 const clearEditorModels = () => {
6332 setModels("");
6333 };
6334
6335 const advancedFields = (
6336 <details className="provider-editor-advanced" open={advancedOpen} onToggle={(e) => setAdvancedOpen(e.currentTarget.open)}>
6337 <summary>
6338 <span className="provider-editor-advanced__title">
6339 <ChevronDown className="provider-editor-advanced__icon" size={16} aria-hidden="true" />
6340 {t("settings.providerAdvancedSettings")}
6341 </span>
6342 <span className="provider-editor-advanced__hint">
6343 {advancedOpen ? t("settings.providerAdvancedCollapseHint") : t("settings.providerAdvancedExpandHint")}
6344 </span>
6345 </summary>
6346 <div className="provider-editor-advanced__body">
6347 <label className="set-label">{t("settings.providerModelsUrl")}</label>
6348 <input
6349 className="mem-input"
6350 placeholder={t("settings.providerModelsUrlPlaceholder")}
6351 value={modelsUrl}
6352 onChange={(e) => setModelsUrl(e.target.value)}
6353 />
6354 <div className="mem-hint">{t("settings.providerModelsUrlHint")}</div>
6355 <label className="set-label">{t("settings.providerHeaders")}</label>
6356 <textarea
6357 className="mem-textarea provider-headers-textarea"
6358 placeholder={t("settings.providerHeadersPlaceholder")}
6359 value={headersDraft}
6360 onChange={(e) => setHeadersDraft(e.target.value)}
6361 rows={3}
6362 />
6363 <div className="mem-hint">{t("settings.providerHeadersHint")}</div>
6364 <label className="set-label">{t("settings.providerExtraBody")}</label>
6365 <textarea
6366 className="mem-textarea provider-headers-textarea"
6367 placeholder={t("settings.providerExtraBodyPlaceholder")}
6368 value={extraBodyDraft}
6369 onChange={(e) => setExtraBodyDraft(e.target.value)}
6370 rows={4}
6371 />
6372 <div className={`mem-hint${extraBodyInvalid ? " mem-hint--error" : ""}`}>
6373 {extraBodyInvalid ? <ErrorMessage error={extraBodyParse.error} /> : t("settings.providerExtraBodyHint")}
6374 </div>
6375 <label className="set-check">
6376 <input
6377 type="checkbox"
6378 checked={authHeader}
6379 onChange={(e) => setAuthHeader(e.target.checked)}
6380 />
6381 {t("settings.providerAuthHeader")}
6382 </label>
6383 <div className="mem-hint">{t("settings.providerAuthHeaderHint")}</div>
6384 <label className="set-check">
6385 <input
6386 type="checkbox"
6387 checked={noProxy}
6388 onChange={(e) => setNoProxy(e.target.checked)}
6389 />
6390 {t("settings.providerNoProxy")}
6391 </label>
6392 <div className="mem-hint">{t("settings.providerNoProxyHint")}</div>
6393 <label className="set-label">{t("settings.reasoningProtocol")}</label>
6394 <SettingsSelect className="mem-select" aria-label={t("settings.reasoningProtocol")} value={reasoningProtocol} onValueChange={(value) => setReasoningProtocol(value)}>
6395 {REASONING_PROTOCOLS.map((protocol) => (
6396 <option key={protocol || "auto"} value={protocol}>
6397 {reasoningProtocolLabel(protocol, t)}
6398 </option>
6399 ))}
6400 </SettingsSelect>
6401 <div className="mem-hint">{t("settings.reasoningProtocolHint")}</div>
6402 <label className="set-label">{t("settings.thinkingMode")}</label>
6403 <SettingsSelect className="mem-select" aria-label={t("settings.thinkingMode")} value={thinking} onValueChange={(value) => setThinking(normalizeThinkingMode(value))}>
6404 {THINKING_MODES.map((mode) => (
6405 <option key={mode || "auto"} value={mode}>
6406 {thinkingModeLabel(mode, t)}
6407 </option>
6408 ))}
6409 </SettingsSelect>
6410 <div className="mem-hint">{t("settings.thinkingModeHint")}</div>
6411 <label className="set-label">{t("settings.providerBalanceUrl")}</label>
6412 <input
6413 className="mem-input"
6414 placeholder={t("settings.balanceUrlPlaceholder")}
6415 value={balanceUrl}
6416 onChange={(e) => setBalanceUrl(e.target.value)}
6417 />
6418 <div className="mem-hint">{t("settings.balanceUrlHint")}</div>
6419 <label className="set-label">{t("settings.providerContextWindow")}</label>
6420 <input
6421 className="mem-input"
6422 inputMode="numeric"
6423 min={0}
6424 placeholder={t("settings.contextWindowPlaceholder")}
6425 type="number"
6426 value={ctx}
6427 onChange={(e) => setCtx(e.target.value)}
6428 />
6429 <div className="mem-hint">{t("settings.contextWindowHint")}</div>
6430 </div>
6431 </details>
6432 );
6433
6434 return (
6435 <div className={`provider-editor provider-editor--compact${isNewCustomProvider ? " provider-editor--wizard" : ""}`}>
6436 <div className="provider-editor__body">
6437 {!hideConnectionName && <>
6438 <label className="set-label" htmlFor={providerNameInputId}>{t(initial ? "settings.connections.name" : "settings.customProviderName")}</label>
6439 <input id={providerNameInputId} className="mem-input provider-name-input"
6440 placeholder={initial ? initial.name : t("settings.customProviderNamePlaceholder")}
6441 value={initial ? displayName : name} disabled={busy}
6442 onChange={(e) => initial ? setDisplayName(e.target.value) : setName(e.target.value)} />
6443 {initial && <details className="mem-hint"><summary>{t("settings.connections.id")}</summary><code>{initial.name}</code></details>}
6444 </>}
6445 <section className="provider-connection-fields">
6446 <div className="provider-connection-field">
6447 <label className="set-label" htmlFor={providerUrlInputId}>
6448 {t("settings.providerBaseUrlLabel")}
6449 </label>
6450 <input
6451 id={providerUrlInputId}
6452 className="mem-input provider-url-input"
6453 aria-describedby={providerUrlHelpId}
6454 placeholder={t("settings.providerChatUrlPlaceholder")}
6455 value={requestUrl}
6456 onChange={(e) => setRequestUrl(e.target.value)}
6457 />
6458 <span id={providerUrlHelpId} className="provider-field-help">{t("settings.providerRequestUrlHint")}</span>
6459 </div>
6460 <div className="provider-connection-field">
6461 <label className="set-label">{t("settings.providerProtocol")}</label>
6462 <SettingsSelect className="mem-select" aria-label={t("settings.providerProtocol")} title={providerKindHint(effectiveKind, t)} value={kind} disabled={busy || fetchingModels} onValueChange={(value) => {
6463 const nextKind = value;
6464 setRequestUrl(current => {
6465 return providerRequestURLForCatalogFormatChange(kind, nextKind, current, editorCatalog);
6466 });
6467 setKind(nextKind);
6468 }}>
6469 {providerKindChoices.map((choice) => (
6470 <option key={choice} value={choice}>
6471 {providerKindLabel(choice, t)}
6472 </option>
6473 ))}
6474 </SettingsSelect>
6475 {endpointMismatch.mismatch && <div role="alert" className="banner banner--warning">
6476 <span>{t("settings.providerProtocolMismatch")}</span>
6477 {endpointMismatch.recommendedUrl && <button type="button" className="btn btn--small" title={endpointMismatch.recommendedUrl} onClick={() => setRequestUrl(endpointMismatch.recommendedUrl)}>{t("settings.compactRatioApply")}</button>}
6478 </div>}
6479 </div>
6480 <div className="provider-key-single">
6481 <label htmlFor={`provider-key-${initial?.name ?? "new"}`}>API Key</label>
6482 <div className="provider-key-single__input">
6483 <input id={`provider-key-${initial?.name ?? "new"}`} className="mem-input"
6484 type={showKey ? "text" : "password"} autoComplete="new-password" spellCheck={false}
6485 placeholder={initial?.keySet ? "••••••••••••••••••••" : "API Key"}
6486 value={keyDraft} disabled={busy}
6487 onChange={e => setKeyDraft(e.target.value)} />
6488 <button type="button" className="btn provider-icon-action" aria-label={showKey ? "Hide API Key" : "Show API Key"}
6489 title={showKey ? "Hide API Key" : "Show API Key"} aria-pressed={showKey}
6490 disabled={!keyDraft} onClick={() => setShowKey(value => !value)}>
6491 {showKey ? <EyeOff size={17} /> : <Eye size={17} />}
6492 </button>
6493 </div>
6494 </div>
6495 </section>
6496 {fetchStatus && <div role="status" className="provider-fetch-status provider-fetch-status--ok">{fetchStatus}</div>}
6497 {fetchFallback && <div role="alert" className="provider-fetch-status provider-fetch-status--warn"><ErrorMessage error={fetchFallback} /></div>}
6498 {modelDialog !== null && <Suspense fallback={null}><ProviderModelDialog
6499 baseURL={effectiveRequestUrl} candidates={modelCandidateNames} contextDefault={Number(ctx) || undefined}
6500 effortOptions={Array.from(new Set([...(modelCapabilities.find(item=>item.model === modelDialog)?.reasoning?.options ?? []).map(option=>option.id), ...(modelOverrides.find(item=>item.model === modelDialog)?.supportedEfforts ?? supportedEfforts ?? [])])).filter(Boolean)}
6501 initial={modelDialog ? (() => { const override = modelOverrides.find(item=>item.model === modelDialog); return {model:modelDialog, contextWindow:modelContextWindows[modelDialog] ?? "", maxOutputTokens:override?.maxOutputTokens ?? 0, vision:override?.vision ?? null, supportedEfforts:override?.supportedEfforts ?? [], defaultEffort:override?.defaultEffort ?? ""}; })() : undefined}
6502 capability={modelCapabilities.find(item=>item.model === modelDialog)} busy={busy || fetchingModels}
6503 onClose={()=>setModelDialog(null)} onApply={applyModelDetails} onDelete={deleteModel}/></Suspense>}
6504 <ProviderEditorModelPicker
6505 actions={<>
6506 <button type="button" className="btn provider-icon-action" title={t("settings.fetchModels")} aria-label={t(fetchingModels ? "settings.fetchingModels" : "settings.fetchModels")} disabled={busy || fetchingModels || !canFetch || extraBodyInvalid} onClick={() => void fetchModels()}>{fetchingModels ? <Loader2 size={17} /> : <RefreshCw size={17} />}</button>
6507 <button className="btn btn--small" disabled={busy || fetchingModels} onClick={() => setModelDialog("")}>{t("settings.models.add")}</button>
6508 </>}
6509 candidates={modelCandidateNames}
6510 selectedModels={modelNames}
6511 visionModels={visionModelNames}
6512 visionModelsConfigured={visionModelsConfigured}
6513 modelCapabilities={modelCandidateNames.map(model => { const override = modelOverrides.find(item=>item.model === model)?.vision; const info = modelCapabilities.find(item=>item.model === model); return override == null ? info : {...info, model, state:override ? "supported" : "unsupported", inputModalities:override ? ["text","image"] : ["text"], source:"override"}; }).filter((item): item is ProviderModelCapabilityView => Boolean(item))}
6514 contextWindows={modelContextWindows}
6515 inheritedContextWindow={Number(ctx) || undefined}
6516 disabled={busy || fetchingModels}
6517 onToggleModel={toggleEditorModel}
6518 onEditModel={setModelDialog}
6519 onSelectAll={selectAllEditorModels}
6520 onClear={clearEditorModels}
6521 />
6522 <ProviderServiceCapabilities
6523 supported={effectiveServerWebSearchCapability}
6524 models={modelNames}
6525 enabled={webSearch}
6526 disabled={busy || fetchingModels}
6527 onChange={setWebSearch}
6528 />
6529 {advancedFields}
6530 </div>
6531 <div className="prov-card__actions provider-editor-footer">
6532 <span role="status">{t(dirty ? "settings.models.unsaved" : "settings.models.saved")}</span>
6533 <button className="btn btn--small" onClick={onCancel} disabled={busy}>
6534 {t("common.cancel")}
6535 </button>
6536 <button className="btn btn--primary btn--small" onClick={() => void save()} disabled={busy || fetchingModels || (Boolean(initial) && !dirty) || !name.trim() || !effectiveBaseUrl || !models.trim() || extraBodyInvalid || endpointMismatch.mismatch}>
6537 {t("settings.models.saveChanges")}
6538 </button>
6539 </div>
6540 </div>
6541 );
6542 }
6543
6544 function PermissionsSection({ s, busy, apply }: SectionProps) {
6545 const t = useT();
6546 return (
6547 <SettingsSection title={t("settings.permissionRules")} description={t("settings.ruleForm")}>
6548 <div className="set-rules-grid">
6549 {(["deny", "ask", "allow"] as const).map((list) => (
6550 <RuleList
6551 key={list}
6552 list={list}
6553 rules={s.permissions[list]}
6554 busy={busy}
6555 onAdd={(rule) => apply(() => app.AddPermissionRule(list, rule))}
6556 onRemove={async (rule) => { await apply(() => app.RemovePermissionRule(list, rule)); }}
6557 />
6558 ))}
6559 </div>
6560 </SettingsSection>
6561 );
6562 }
6563
6564 type HookScope = "global" | "project";
6565
6566 function HooksSection({ onChanged }: { onChanged: (settings?: SettingsView | null) => void }) {
6567 const t = useT();
6568 const [scope, setScope] = useState<HookScope>("global");
6569 const [view, setView] = useState<HooksSettingsView | null>(null);
6570 const [jsonText, setJsonText] = useState("");
6571 const [jsonMessage, setJsonMessage] = useState<string | null>(null);
6572 const [jsonError, setJsonError] = useState<string | null>(null);
6573 const [pathMessage, setPathMessage] = useState<string | null>(null);
6574 const [busy, setBusy] = useState(false);
6575 const [err, setErr] = useState<string | null>(null);
6576
6577 const load = useCallback(async (nextScope: HookScope) => {
6578 setBusy(true);
6579 setErr(null);
6580 try {
6581 const next = normalizeHooksSettingsView(await app.HooksSettings(nextScope), nextScope);
6582 setView(next);
6583 setJsonText(formatHooksJSON(next.hooks, next.events));
6584 setJsonMessage(null);
6585 setJsonError(null);
6586 setPathMessage(null);
6587 } catch (e) {
6588 setErr(String((e as Error)?.message ?? e));
6589 setView(null);
6590 setJsonText("");
6591 setJsonMessage(null);
6592 setJsonError(null);
6593 setPathMessage(null);
6594 } finally {
6595 setBusy(false);
6596 }
6597 }, []);
6598
6599 useEffect(() => {
6600 void load(scope);
6601 }, [load, scope]);
6602
6603 const parseHooksEditorJSON = (raw = jsonText): { hooks: HookConfigView[]; text: string } | null => {
6604 try {
6605 const hooks = parseHooksJSON(raw, view?.events ?? [], t);
6606 const text = formatHooksJSON(hooks, view?.events ?? []);
6607 setJsonText(text);
6608 setJsonError(null);
6609 return { hooks, text };
6610 } catch (e) {
6611 setJsonError(t("settings.hooksJsonInvalid", { error: String((e as Error)?.message ?? e) }));
6612 setJsonMessage(null);
6613 return null;
6614 }
6615 };
6616 const copyHooksJSON = async () => {
6617 const parsed = parseHooksEditorJSON();
6618 if (!parsed) return;
6619 try {
6620 await navigator.clipboard?.writeText(parsed.text);
6621 setJsonMessage(t("settings.hooksJsonCopied"));
6622 } catch {
6623 setJsonMessage(t("settings.hooksJsonClipboardUnavailable"));
6624 }
6625 };
6626 const formatHooksEditorJSON = (raw = jsonText) => {
6627 const parsed = parseHooksEditorJSON(raw);
6628 if (parsed) setJsonMessage(t("settings.hooksJsonFormatted"));
6629 };
6630 const pasteHooksJSON = async () => {
6631 try {
6632 const raw = await navigator.clipboard?.readText();
6633 if (!raw) throw new Error(t("settings.hooksJsonClipboardEmpty"));
6634 setJsonText(raw);
6635 formatHooksEditorJSON(raw);
6636 } catch (e) {
6637 setJsonError(t("settings.hooksJsonPasteFailed", { error: String((e as Error)?.message ?? e) }));
6638 setJsonMessage(null);
6639 }
6640 };
6641 const copyHooksPath = async () => {
6642 const path = view?.path?.trim();
6643 if (!path) {
6644 setPathMessage(t("settings.hooksPathUnavailable"));
6645 return;
6646 }
6647 try {
6648 await navigator.clipboard?.writeText(path);
6649 setPathMessage(t("settings.hooksPathCopied"));
6650 } catch {
6651 setPathMessage(t("settings.hooksJsonClipboardUnavailable"));
6652 }
6653 };
6654 const approve = async () => {
6655 setBusy(true);
6656 setErr(null);
6657 try {
6658 await app.TrustProjectHooksForRoot(view?.projectRoot?.trim() ?? "");
6659 await load(scope);
6660 onChanged();
6661 } catch (e) {
6662 setErr(String((e as Error)?.message ?? e));
6663 } finally {
6664 setBusy(false);
6665 }
6666 };
6667 const save = async () => {
6668 setBusy(true);
6669 setErr(null);
6670 try {
6671 const parsed = parseHooksEditorJSON();
6672 if (!parsed) return;
6673 await app.SaveHooksSettingsForRoot(scope, view?.projectRoot?.trim() ?? "", parsed.hooks);
6674 await load(scope);
6675 onChanged();
6676 } catch (e) {
6677 setErr(String((e as Error)?.message ?? e));
6678 } finally {
6679 setBusy(false);
6680 }
6681 };
6682 return (
6683 <>
6684 {err && <div className="banner banner--error"><ErrorMessage error={err} /></div>}
6685 <SettingsSection title={t("settings.hooksScopeSection")} description={t("settings.hooksScopeHint")}>
6686 <SettingsField label={t("settings.hooksScopeField")}>
6687 <SettingsSelect name="hooks-scope" className="mem-select set-grow" value={scope} disabled={busy} onValueChange={(value) => setScope(value === "project" ? "project" : "global")}>
6688 <option value="global">{t("settings.hooksGlobal")}</option>
6689 <option value="project">{t("settings.hooksProject")}</option>
6690 </SettingsSelect>
6691 </SettingsField>
6692 <SettingsField label={t("settings.hooksPath")} hint={scope === "project" ? t("settings.hooksPathProjectHint") : t("settings.hooksPathGlobalHint")}>
6693 <div className="hooks-path-stack">
6694 <div className={`hooks-path-display${view?.path ? "" : " hooks-path-display--empty"}`}>
6695 <code className="hooks-path-display__value" title={view?.path || t("settings.hooksPathUnavailable")}>
6696 {view?.path || t("settings.hooksPathUnavailable")}
6697 </code>
6698 <button className="btn btn--small" disabled={busy || !view?.path} onClick={() => void copyHooksPath()}>{t("settings.hooksPathCopy")}</button>
6699 </div>
6700 {pathMessage && <div className="hooks-path-display__message">{pathMessage}</div>}
6701 </div>
6702 </SettingsField>
6703 </SettingsSection>
6704
6705 <SettingsSection
6706 title={t("settings.hooks")}
6707 description={scope === "project" ? t("settings.hooksProjectHint") : t("settings.hooksGlobalHint")}
6708 >
6709 {view && scope === "project" && !view.trusted && view.hooks.length > 0 && (
6710 <div className="banner banner--warning" role="status">
6711 <span>{t("settings.hooksAwaitingApproval")}</span>
6712 <button className="btn btn--small" disabled={busy} onClick={() => void approve()}>{t("settings.hooksApprove")}</button>
6713 </div>
6714 )}
6715 {view && (
6716 <div className="hooks-json-panel">
6717 <div className="hooks-json-panel__head">
6718 <div>
6719 <div className="set-rules__label">{t("settings.hooksJsonTitle")}</div>
6720 <div className="set-rules__hint">{t("settings.hooksJsonHint")}</div>
6721 </div>
6722 <div className="hooks-json-panel__actions">
6723 <button className="btn btn--small" disabled={busy} onClick={() => void copyHooksJSON()}>{t("settings.hooksJsonCopy")}</button>
6724 <button className="btn btn--small" disabled={busy} onClick={() => void pasteHooksJSON()}>{t("settings.hooksJsonPaste")}</button>
6725 <button className="btn btn--small" disabled={busy || !jsonText.trim()} onClick={() => formatHooksEditorJSON()}>{t("settings.hooksJsonApply")}</button>
6726 </div>
6727 </div>
6728 <textarea
6729 name="hooks-json"
6730 className="mem-textarea hooks-json-panel__textarea"
6731 value={jsonText}
6732 disabled={busy}
6733 spellCheck={false}
6734 onChange={(e) => {
6735 setJsonText(e.target.value);
6736 setJsonMessage(null);
6737 setJsonError(null);
6738 }}
6739 />
6740 {jsonError && <div className="hooks-json-panel__message hooks-json-panel__message--error"><ErrorMessage error={jsonError} /></div>}
6741 {jsonMessage && <div className="hooks-json-panel__message">{jsonMessage}</div>}
6742 </div>
6743 )}
6744 {!view && <div className="empty">{t("settings.loading")}</div>}
6745 <div className="settings-save-bar">
6746 <span role="status">{t(view && jsonText !== formatHooksJSON(view.hooks, view.events) ? "settings.models.unsaved" : "settings.models.saved")}</span>
6747 <button className="btn" disabled={busy || !view} onClick={() => { if (view) { setJsonText(formatHooksJSON(view.hooks, view.events)); setJsonError(null); setJsonMessage(null); } }}>{t("common.cancel")}</button>
6748 <button className="btn btn--primary" disabled={busy || !view || jsonText === formatHooksJSON(view.hooks, view.events)} onClick={() => void save()}>{t("common.save")}</button>
6749 </div>
6750 </SettingsSection>
6751 </>
6752 );
6753 }
6754
6755 function normalizeHooksSettingsView(view: HooksSettingsView, scope: HookScope): HooksSettingsView {
6756 const events = asArray(view?.events).filter(Boolean);
6757 return {
6758 scope: view?.scope === "project" ? "project" : scope,
6759 path: view?.path ?? "",
6760 projectRoot: view?.projectRoot ?? "",
6761 trusted: !!view?.trusted,
6762 events,
6763 hooks: asArray(view?.hooks).map(normalizeHookConfig).filter((h) => h.event),
6764 };
6765 }
6766
6767 function formatHooksJSON(hooks: HookConfigView[], eventOrder: string[]): string {
6768 const grouped: Record<string, Array<Record<string, string | number>>> = {};
6769 const events = new Set(eventOrder);
6770 for (const hook of hooks.map(normalizeHookConfig).filter((h) => h.event)) {
6771 events.add(hook.event);
6772 const entry: Record<string, string | number> = { command: hook.command };
6773 if (hook.match) entry.match = hook.match;
6774 if (hook.description) entry.description = hook.description;
6775 if ((hook.timeout ?? 0) > 0) entry.timeout = hook.timeout ?? 0;
6776 if (hook.cwd) entry.cwd = hook.cwd;
6777 (grouped[hook.event] ||= []).push(entry);
6778 }
6779 const ordered: typeof grouped = {};
6780 for (const event of [...eventOrder, ...Array.from(events).sort()]) {
6781 if (grouped[event]?.length && !ordered[event]) ordered[event] = grouped[event];
6782 }
6783 return JSON.stringify({ hooks: ordered }, null, 2);
6784 }
6785
6786 function parseHooksJSON(raw: string, validEvents: string[], t: ReturnType<typeof useT>): HookConfigView[] {
6787 const trimmed = raw.trim();
6788 if (!trimmed) return [];
6789 let parsed: unknown;
6790 try {
6791 parsed = JSON.parse(trimmed);
6792 } catch (e) {
6793 throw new Error(String((e as Error)?.message ?? e));
6794 }
6795 if (Array.isArray(parsed)) {
6796 return parsed.map((item) => normalizeHookConfig(parseHookArrayItem(item, validEvents, t))).filter((h) => h.event);
6797 }
6798 if (!parsed || typeof parsed !== "object") {
6799 throw new Error(t("settings.hooksJsonExpectedObjectArray"));
6800 }
6801 const obj = parsed as Record<string, unknown>;
6802 const hooksValue = obj.hooks && typeof obj.hooks === "object" && !Array.isArray(obj.hooks) ? obj.hooks : obj;
6803 return flattenHooksMap(hooksValue as Record<string, unknown>, validEvents, t);
6804 }
6805
6806 function parseHookArrayItem(item: unknown, validEvents: string[], t: ReturnType<typeof useT>): HookConfigView {
6807 if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error(t("settings.hooksJsonItemObject"));
6808 const obj = item as Record<string, unknown>;
6809 const event = stringField(obj, "event") || "PreToolUse";
6810 if (validEvents.length > 0 && !validEvents.includes(event)) throw new Error(t("settings.hooksJsonUnknownEvent", { event }));
6811 return {
6812 event,
6813 match: stringField(obj, "match"),
6814 command: stringField(obj, "command"),
6815 description: stringField(obj, "description"),
6816 timeout: numberField(obj, "timeout"),
6817 cwd: stringField(obj, "cwd"),
6818 };
6819 }
6820
6821 function flattenHooksMap(hooks: Record<string, unknown>, validEvents: string[], t: ReturnType<typeof useT>): HookConfigView[] {
6822 const valid = new Set(validEvents);
6823 const out: HookConfigView[] = [];
6824 for (const [event, value] of Object.entries(hooks)) {
6825 if (valid.size > 0 && !valid.has(event)) throw new Error(t("settings.hooksJsonUnknownEvent", { event }));
6826 const items = Array.isArray(value) ? value : [value];
6827 for (const item of items) {
6828 if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error(t("settings.hooksJsonEventItemObject", { event }));
6829 const obj = item as Record<string, unknown>;
6830 out.push(normalizeHookConfig({
6831 event,
6832 match: stringField(obj, "match"),
6833 command: stringField(obj, "command"),
6834 description: stringField(obj, "description"),
6835 timeout: numberField(obj, "timeout"),
6836 cwd: stringField(obj, "cwd"),
6837 }));
6838 }
6839 }
6840 return out.filter((h) => h.event);
6841 }
6842
6843 function stringField(obj: Record<string, unknown>, key: string): string {
6844 const value = obj[key];
6845 return typeof value === "string" ? value : "";
6846 }
6847
6848 function numberField(obj: Record<string, unknown>, key: string): number {
6849 const value = obj[key];
6850 return typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : 0;
6851 }
6852
6853 function normalizeHookConfig(h: HookConfigView): HookConfigView {
6854 return {
6855 event: h.event || "PreToolUse",
6856 match: h.match ?? "",
6857 command: h.command ?? "",
6858 description: h.description ?? "",
6859 timeout: h.timeout && h.timeout > 0 ? Math.floor(h.timeout) : 0,
6860 cwd: h.cwd ?? "",
6861 };
6862 }
6863
6864 function SandboxSection({ s, busy, apply, windows }: SectionProps & { windows: boolean }) {
6865 const t = useT();
6866 const sb = s.sandbox;
6867 // A draft belongs to the snapshot it was edited against. A fresh authoritative
6868 // root wins immediately; a failed save of the same snapshot retains the draft.
6869 const [rootDraft, setRootDraft] = useState<{ base: string; value: string } | null>(null);
6870 const root = rootDraft?.base === sb.workspaceRoot ? rootDraft.value : sb.workspaceRoot;
6871 const rootSaving = useRef(false);
6872 const [saveResult, setSaveResult] = useState<boolean | null>(null);
6873 const effectiveWriteRoots = asArray(sb.effectiveWriteRoots).filter((path) => String(path).trim());
6874 const set = async (next: Partial<typeof sb>) => {
6875 const result = await apply(() => app.SetSandbox(next.bash ?? sb.bash, next.network ?? sb.network, next.workspaceRoot ?? sb.workspaceRoot, next.allowWrite ?? sb.allowWrite, next.shell ?? sb.shell));
6876 setSaveResult(result);
6877 return result;
6878 };
6879 const saveRoot = async () => {
6880 if (busy || rootSaving.current || root === sb.workspaceRoot) return;
6881 rootSaving.current = true;
6882 try {
6883 if (await set({ workspaceRoot: root })) {
6884 setRootDraft(current => current?.base === sb.workspaceRoot && current.value === root ? null : current);
6885 }
6886 }
6887 finally { rootSaving.current = false; }
6888 };
6889 const reloadSession = async () => {
6890 if (await apply(() => app.ReloadSettings())) { setRootDraft(null); setSaveResult(null); }
6891 };
6892
6893 return (
6894 <SettingsSection
6895 className="sandbox-settings"
6896 title={t("settings.sandboxTitle")}
6897 description={t("settings.sandboxSaveScope")}
6898 actions={
6899 <Tooltip label={t("settings.reloadSessionConfigHint")}>
6900 <button type="button" className="btn btn--small" disabled={busy} onClick={() => void reloadSession()}>
6901 <RefreshCw size={14} aria-hidden="true" />
6902 <span>{t("settings.reloadSessionConfig")}</span>
6903 </button>
6904 </Tooltip>
6905 }
6906 >
6907 <ShellInterpreterFields sb={sb} windows={windows} busy={busy} setShell={(prefer) => void apply(() => app.SetShellPreference(prefer))} reloadSession={() => void reloadSession()} />
6908 <SettingsField className="sandbox-network" label={t(windows ? "settings.shellNetworkAccess" : "settings.allowNetwork")}>
6909 {windows ? <div className="sandbox-network__status"><span>{t("settings.shellNetworkUnrestricted")}</span><p className="sandbox-group__hint">{t("settings.shellNetworkUnrestrictedHint")}</p></div> :
6910 <label className="set-check set-check--inline">
6911 <input type="checkbox" checked={sb.network} disabled={busy} onChange={(e) => void set({ network: e.target.checked })} />
6912 {t("settings.allowNetwork")}
6913 </label>}
6914 </SettingsField>
6915 <div className="sandbox-group sandbox-group--files">
6916 <div className="sandbox-group__heading"><h3>{t(windows ? "settings.fileToolWriteScope" : "settings.writeScope")}</h3>
6917 <span className="sandbox-save-status" role="status">{busy ? t("settings.sandboxSaving") : saveResult === false ? t("settings.sandboxSaveFailed") : root !== sb.workspaceRoot ? t("settings.models.unsaved") : saveResult === true ? <><CheckCircle2 size={14} aria-hidden="true" />{t("settings.sandboxSaved")}</> : null}</span>
6918 </div>
6919 <p className="sandbox-group__hint">{t(windows ? "settings.fileToolWriteScopeHint" : "settings.writeScopeHint")}</p>
6920 <SettingsField label={t("settings.workspaceRoot")}>
6921 <div className="sandbox-root-control">
6922 <input
6923 className="mem-input set-grow"
6924 placeholder={t("settings.workspaceDefault")}
6925 aria-label={t("settings.workspaceRoot")}
6926 value={root}
6927 disabled={busy}
6928 onChange={(e) => { setRootDraft({ base: sb.workspaceRoot, value: e.target.value }); setSaveResult(null); }}
6929 onBlur={() => void saveRoot()}
6930 onKeyDown={(e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing) { e.preventDefault(); void saveRoot(); } }}
6931 />
6932 <div className="sandbox-write-roots">
6933 <span>{t("settings.effectiveWriteRoots")}</span>
6934 {effectiveWriteRoots.length === 0 && <span className="mem-empty">{t("settings.noEffectiveWriteRoots")}</span>}
6935 {effectiveWriteRoots.map((path, index) => (
6936 <span className="set-rule set-rule--path" key={`${path}-${index}`}>
6937 <span>{path}</span><CopyButton text={path} showInlineLabel={false} label={t("settings.copyDirectory")} />
6938 </span>
6939 ))}
6940 </div>
6941 </div>
6942 </SettingsField>
6943 <RuleList
6944 list="allow_write"
6945 rules={sb.allowWrite}
6946 busy={busy}
6947 onAdd={(d) => set({ allowWrite: [...sb.allowWrite, d] })}
6948 onRemove={(d) => set({ allowWrite: sb.allowWrite.filter((x) => x !== d) })}
6949 />
6950 </div>
6951 </SettingsSection>
6952 );
6953 }
6954
6955 const MB = 1024 * 1024;
6956 const mb = (n: number) => (n / MB).toFixed(1);
6957
6958 // AboutSection always exposes build, privacy, configuration, changelog, and
6959 // feedback information. Updater controls are an exact stable-build capability.
6960 function AboutSection({
6961 configPath,
6962 shadowedByPath,
6963 checkUpdates,
6964 updaterEnabled,
6965 telemetry,
6966 metrics,
6967 settingsBusy,
6968 applySettings,
6969 }: {
6970 configPath: string;
6971 shadowedByPath?: string;
6972 checkUpdates: boolean;
6973 updaterEnabled: boolean;
6974 telemetry: boolean;
6975 metrics: boolean;
6976 settingsBusy: boolean;
6977 applySettings: (fn: () => Promise<void>) => Promise<boolean>;
6978 }) {
6979 const t = useT();
6980 const { status, check, apply: applyUpdate, openDownload, abandonPending } = useUpdater();
6981 const [version, setVersion] = useState("");
6982 useEffect(() => {
6983 app.Version().then(setVersion).catch(() => {});
6984 }, []);
6985
6986 const updaterBusy =
6987 status.kind === "checking" ||
6988 status.kind === "downloading" ||
6989 status.kind === "verifying" ||
6990 status.kind === "authorizing" ||
6991 status.kind === "installing" ||
6992 status.kind === "relaunching";
6993 const updateStatus =
6994 status.kind === "checking" ? t("updater.checking") :
6995 status.kind === "upToDate" ? t("updater.upToDate") :
6996 status.kind === "available" ? t("updater.available", { v: status.info.latest }) :
6997 status.kind === "downloading" ? t("updater.downloading", {
6998 done: mb(status.received),
6999 total: mb(status.total),
7000 pct: status.total > 0 ? Math.round((status.received / status.total) * 100) : 0,
7001 }) :
7002 status.kind === "verifying" ? t("updater.verifying") :
7003 status.kind === "authorizing" ? t("updater.authorizing") :
7004 status.kind === "installing" ? (
7005 status.info?.requiresElevation || status.info?.installMode === "deb"
7006 ? t("updater.installingPackage")
7007 : t("updater.installing")
7008 ) :
7009 status.kind === "relaunching" || status.kind === "done" ? t("updater.done") :
7010 status.kind === "error" ? "" :
7011 "";
7012 const updateStatusTone =
7013 status.kind === "error" ? "error" :
7014 status.kind === "available" ? "available" :
7015 status.kind === "upToDate" || status.kind === "done" || status.kind === "relaunching" ? "success" :
7016 status.kind === "checking" || updaterBusy ? "busy" :
7017 "neutral";
7018 const updateErrorTitle = status.kind === "error"
7019 ? status.disposition === "recovery"
7020 ? t("updater.recoveryBlocked")
7021 : status.disposition === "manual"
7022 ? t("updater.manualUpdateRequired")
7023 : t("updater.failed", { msg: status.message })
7024 : "";
7025 const updateErrorHint = status.kind === "error"
7026 ? status.disposition === "recovery"
7027 ? t("updater.recoveryHint")
7028 : status.disposition === "manual"
7029 ? t("updater.manualFallbackHint")
7030 : ""
7031 : "";
7032 const downloadIsPrimary = status.kind === "error" && status.disposition !== "retryable";
7033
7034 return (
7035 <SettingsSection>
7036 <StudioDiscoveryCard />
7037 <SettingsField
7038 className="settings-field--wide-copy updates-control"
7039 label={
7040 <div className="updates-control__summary">
7041 <div className="updates-control__version">
7042 {t("updater.currentVersion", { v: version || "…" })}
7043 </div>
7044 {updaterEnabled && (
7045 <div className={`updates-control__status updates-control__status--${updateStatusTone}`} role="status" aria-live="polite">
7046 {updateStatus && (
7047 <>
7048 {updateStatusTone === "success" && <CheckCircle2 size={14} aria-hidden="true" />}
7049 {updateStatusTone === "busy" && <Loader2 className="updates-control__spinner" size={14} aria-hidden="true" />}
7050 <span>{updateStatus}</span>
7051 </>
7052 )}
7053 </div>
7054 )}
7055 </div>
7056 }
7057 >
7058 {updaterEnabled && <div className="updates-control__controls">
7059 <Tooltip label={t("updater.checkButton")}>
7060 <button
7061 className="chip chip--icon"
7062 type="button"
7063 disabled={settingsBusy || updaterBusy}
7064 aria-label={t("updater.checkButton")}
7065 onClick={() => void check()}
7066 >
7067 <RefreshCw className={status.kind === "checking" ? "updates-control__spinner" : undefined} size={14} aria-hidden="true" />
7068 </button>
7069 </Tooltip>
7070 </div>}
7071 </SettingsField>
7072 <SettingsField
7073 className="settings-field--wide-copy"
7074 label={t("updater.buildIdentity")}
7075 hint={t("updater.buildIdentityHint")}
7076 >
7077 <span className="mem-hint">{typeof __BUILD_CHANNEL__ === "string" ? __BUILD_CHANNEL__ : "development"}</span>
7078 </SettingsField>
7079 {updaterEnabled && <div
7080 className="updates-control__hint"
7081 style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: "4px 8px" }}
7082 >
7083 <span>{t("updater.officialReleaseHint")}</span>
7084 <button
7085 className="btn btn--small"
7086 type="button"
7087 onClick={openDownload}
7088 style={{
7089 height: "auto",
7090 minHeight: 0,
7091 padding: 0,
7092 borderColor: "transparent",
7093 background: "transparent",
7094 color: "var(--fg-dim)",
7095 textDecoration: "underline",
7096 textUnderlineOffset: 2,
7097 }}
7098 >
7099 {t("updater.officialDownload")}
7100 <ExternalLink size={13} aria-hidden="true" />
7101 </button>
7102 </div>}
7103 {updaterEnabled && status.kind === "available" && (
7104 <div className="updates-control__action">
7105 <div className="updates-control__action-copy">
7106 {!status.info.canSelfUpdate && <div>{status.info.manualReason || t("updater.macHint")}</div>}
7107 </div>
7108 <button
7109 className="btn btn--primary btn--small"
7110 disabled={settingsBusy || updaterBusy}
7111 onClick={() => applyUpdate(status.info)}
7112 >
7113 {status.info.canSelfUpdate ? t("updater.updateAndRestart") : t("updater.goToDownload")}
7114 </button>
7115 </div>
7116 )}
7117 {updaterEnabled && status.kind === "error" && (
7118 <div
7119 className="banner banner--update banner--error"
7120 role="alert"
7121 style={{ alignItems: "flex-start", flexWrap: "wrap", marginBottom: 12 }}
7122 >
7123 <div style={{ flex: "1 1 360px", minWidth: 0 }}>
7124 <div>{updateErrorTitle}</div>
7125 {updateErrorHint && <div className="banner__hint">{updateErrorHint}</div>}
7126 {status.disposition !== "retryable" && (
7127 <div className="banner__hint" style={{ overflowWrap: "anywhere" }}>
7128 {t("updater.errorDetails", { msg: status.message })}
7129 </div>
7130 )}
7131 </div>
7132 <span className="banner__spacer" />
7133 {status.disposition === "recovery" && (
7134 <button
7135 className="btn btn--small"
7136 type="button"
7137 disabled={settingsBusy || updaterBusy}
7138 onClick={() => void abandonPending()}
7139 >
7140 {t("updater.discardPrevious")}
7141 </button>
7142 )}
7143 {downloadIsPrimary && (
7144 <button className="btn btn--primary btn--small" type="button" onClick={openDownload}>
7145 {t("updater.officialDownload")}
7146 <ExternalLink size={14} aria-hidden="true" />
7147 </button>
7148 )}
7149 <button
7150 className={`btn btn--small${downloadIsPrimary ? "" : " btn--primary"}`}
7151 type="button"
7152 disabled={settingsBusy || updaterBusy}
7153 onClick={() => status.info ? applyUpdate(status.info) : void check()}
7154 >
7155 {t("updater.retry")}
7156 </button>
7157 </div>
7158 )}
7159 <SettingsField
7160 className="settings-field--wide-copy"
7161 label={t("changelog.title")}
7162 hint={t("changelog.subtitle")}
7163 >
7164 <button className="btn btn--small" onClick={() => void openExternal("https://reasonix.io/changelog/")}>
7165 {t("changelog.openWeb")}
7166 <ExternalLink size={14} aria-hidden="true" />
7167 </button>
7168 </SettingsField>
7169 <SettingsField
7170 className="settings-field--wide-copy"
7171 label={t("feedback.title")}
7172 hint={t("feedback.subtitle")}
7173 >
7174 <div className="settings-inline-controls">
7175 <button
7176 className="btn btn--small"
7177 onClick={() => void openExternal("https://github.com/esengine/DeepSeek-Reasonix/issues/new/choose")}
7178 >
7179 {t("feedback.submitIssue")}
7180 <ExternalLink size={14} aria-hidden="true" />
7181 </button>
7182 <button
7183 className="btn btn--small"
7184 onClick={() => void openExternal("https://github.com/esengine/DeepSeek-Reasonix/issues")}
7185 >
7186 {t("feedback.viewIssues")}
7187 <ExternalLink size={14} aria-hidden="true" />
7188 </button>
7189 </div>
7190 </SettingsField>
7191 {updaterEnabled && <details
7192 className="provider-editor-advanced"
7193 style={{
7194 marginTop: 0,
7195 borderRight: 0,
7196 borderBottom: 0,
7197 borderLeft: 0,
7198 borderRadius: 0,
7199 background: "transparent",
7200 }}
7201 >
7202 <summary style={{ padding: "0 2px" }}>
7203 <span className="provider-editor-advanced__title">
7204 <ChevronDown className="provider-editor-advanced__icon" size={16} aria-hidden="true" />
7205 {t("updater.updatePreferences")}
7206 </span>
7207 </summary>
7208 <div className="provider-editor-advanced__body">
7209 <SettingsField
7210 className="settings-field--wide-copy"
7211 label={t("updater.autoCheckLabel")}
7212 hint={t("updater.autoCheckHint")}
7213 >
7214 <ToggleSegment
7215 value={checkUpdates}
7216 disabled={settingsBusy}
7217 onChange={(enabled) => void applySettings(() => app.SetDesktopCheckUpdates(enabled))}
7218 />
7219 </SettingsField>
7220 </div>
7221 </details>}
7222 <details
7223 className="provider-editor-advanced"
7224 style={{
7225 marginTop: 0,
7226 borderRight: 0,
7227 borderBottom: 0,
7228 borderLeft: 0,
7229 borderRadius: 0,
7230 background: "transparent",
7231 }}
7232 >
7233 <summary style={{ padding: "0 2px" }}>
7234 <span className="provider-editor-advanced__title">
7235 <ChevronDown className="provider-editor-advanced__icon" size={16} aria-hidden="true" />
7236 {t("updater.privacyAndConfig")}
7237 </span>
7238 </summary>
7239 <div className="provider-editor-advanced__body">
7240 <SettingsField className="settings-field--wide-copy" label={t("settings.telemetryLabel")} hint={t("settings.telemetryHint")}>
7241 <ToggleSegment value={telemetry} disabled={settingsBusy} onChange={(enabled) => void applySettings(() => app.SetDesktopTelemetry(enabled))} />
7242 </SettingsField>
7243 <SettingsField className="settings-field--wide-copy" label={t("settings.metricsLabel")} hint={t("settings.metricsHint")}>
7244 <ToggleSegment value={metrics} disabled={settingsBusy} onChange={(enabled) => void applySettings(() => app.SetDesktopMetrics(enabled))} />
7245 </SettingsField>
7246 {configPath && (
7247 <Tooltip label={configPath} fill block className="mem-hint settings-config-path">
7248 {t("settings.config", { path: configPath })}
7249 </Tooltip>
7250 )}
7251 {shadowedByPath && (
7252 <Tooltip label={shadowedByPath} fill block className="mem-hint settings-config-path settings-config-path--shadowed">
7253 {t("settings.configShadowed", { path: shadowedByPath })}
7254 </Tooltip>
7255 )}
7256 </div>
7257 </details>
7258 </SettingsSection>
7259 );
7260 }
7261
7261 lines Plain Text