Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsPanels.tsx

1,426 lines50.3 KB

1import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
2import { useQueryClient } from "@tanstack/react-query";
3import { Link } from "@tanstack/react-router";
4import { useCallback, useMemo, useRef, useState } from "react";
5import {
6 defaultInstanceIdForDriver,
7 type DesktopUpdateChannel,
8 PROVIDER_DISPLAY_NAMES,
9 ProviderDriverKind,
10 type ProviderInstanceConfig,
11 type ProviderInstanceId,
12 type ScopedThreadRef,
13} from "@t3tools/contracts";
14import { scopeThreadRef } from "@t3tools/client-runtime";
15import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
16import { createModelSelection } from "@t3tools/shared/model";
17import { Equal } from "effect";
18import { APP_VERSION } from "../../branding";
19import {
20 canCheckForUpdate,
21 getDesktopUpdateButtonTooltip,
22 getDesktopUpdateInstallConfirmationMessage,
23 isDesktopUpdateButtonDisabled,
24 resolveDesktopUpdateButtonAction,
25} from "../../components/desktopUpdate.logic";
26import { ProviderModelPicker } from "../chat/ProviderModelPicker";
27import { TraitsPicker } from "../chat/TraitsPicker";
28import { isElectron } from "../../env";
29import { useTheme } from "../../hooks/useTheme";
30import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
31import { useThreadActions } from "../../hooks/useThreadActions";
32import {
33 setDesktopUpdateStateQueryData,
34 useDesktopUpdateState,
35} from "../../lib/desktopUpdateReactQuery";
36import {
37 getCustomModelOptionsByInstance,
38 resolveAppModelSelectionState,
39} from "../../modelSelection";
40import {
41 deriveProviderInstanceEntries,
42 sortProviderInstanceEntries,
43} from "../../providerInstances";
44import { ensureLocalApi, readLocalApi } from "../../localApi";
45import { useShallow } from "zustand/react/shallow";
46import {
47 selectProjectsAcrossEnvironments,
48 selectThreadShellsAcrossEnvironments,
49 useStore,
50} from "../../store";
51import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
52import { Button } from "../ui/button";
53import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
54import { DraftInput } from "../ui/draft-input";
55import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
56import { Switch } from "../ui/switch";
57import { stackedThreadToast, toastManager } from "../ui/toast";
58import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
59import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
60import {
61 canOneClickUpdateProviderCandidate,
62 collectProviderUpdateCandidates,
63 hasOneClickUpdateProviderCandidate,
64 isProviderUpdateActive,
65 type ProviderUpdateCandidate,
66} from "../ProviderUpdateLaunchNotification.logic";
67import { ProviderInstanceCard } from "./ProviderInstanceCard";
68import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
69import {
70 buildProviderInstanceUpdatePatch,
71 formatDiagnosticsDescription,
72} from "./SettingsPanels.logic";
73import {
74 SettingResetButton,
75 SettingsPageContainer,
76 SettingsRow,
77 SettingsSection,
78 useRelativeTimeTick,
79} from "./settingsLayout";
80import { ProjectFavicon } from "../ProjectFavicon";
81import { useServerObservability, useServerProviders } from "../../rpc/serverState";
82​
83const THEME_OPTIONS = [
84 {
85 value: "system",
86 label: "System",
87 },
88 {
89 value: "light",
90 label: "Light",
91 },
92 {
93 value: "dark",
94 label: "Dark",
95 },
96] as const;
97​
98const TIMESTAMP_FORMAT_LABELS = {
99 locale: "System default",
100 "12-hour": "12-hour",
101 "24-hour": "24-hour",
102} as const;
103​
104const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
105​
106function withoutProviderInstanceKey<V>(
107 record: Readonly<Record<ProviderInstanceId, V>> | undefined,
108 key: ProviderInstanceId,
109): Record<ProviderInstanceId, V> {
110 const next = { ...record } as Record<ProviderInstanceId, V>;
111 delete next[key];
112 return next;
114​
115function withoutProviderInstanceFavorites(
116 favorites: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string }>,
117 instanceId: ProviderInstanceId,
118) {
119 return favorites.filter((favorite) => favorite.provider !== instanceId);
121​
122const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
123 provider: definition.value,
124}));
125​
126function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
127 useRelativeTimeTick();
128 const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null;
129​
130 if (!lastCheckedRelative) {
131 return null;
132 }
133​
134 return (
135 <span className="text-[11px] text-muted-foreground/60">
136 {lastCheckedRelative.suffix ? (
137 <>
138 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
139 {lastCheckedRelative.suffix}
140 </>
141 ) : (
142 <>Checked {lastCheckedRelative.value}</>
143 )}
144 </span>
145 );
147​
148function AboutVersionTitle() {
149 return (
150 <span className="inline-flex items-center gap-2">
151 <span>Version</span>
152 <code className="text-[11px] font-medium text-muted-foreground">{APP_VERSION}</code>
153 </span>
154 );
156​
157function AboutVersionSection() {
158 const queryClient = useQueryClient();
159 const updateStateQuery = useDesktopUpdateState();
160 const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);
161​
162 const updateState = updateStateQuery.data ?? null;
163 const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
164 const selectedUpdateChannel = updateState?.channel ?? "latest";
165​
166 const handleUpdateChannelChange = useCallback(
167 (channel: DesktopUpdateChannel) => {
168 const bridge = window.desktopBridge;
169 if (
170 !bridge ||
171 typeof bridge.setUpdateChannel !== "function" ||
172 channel === selectedUpdateChannel
173 ) {
174 return;
175 }
176​
177 setIsChangingUpdateChannel(true);
178 void bridge
179 .setUpdateChannel(channel)
180 .then((state) => {
181 setDesktopUpdateStateQueryData(queryClient, state);
182 })
183 .catch((error: unknown) => {
184 toastManager.add(
185 stackedThreadToast({
186 type: "error",
187 title: "Could not change update track",
188 description: error instanceof Error ? error.message : "Update track change failed.",
189 }),
190 );
191 })
192 .finally(() => {
193 setIsChangingUpdateChannel(false);
194 });
195 },
196 [queryClient, selectedUpdateChannel],
197 );
198​
199 const handleButtonClick = useCallback(() => {
200 const bridge = window.desktopBridge;
201 if (!bridge) return;
202​
203 const action = updateState ? resolveDesktopUpdateButtonAction(updateState) : "none";
204​
205 if (action === "download") {
206 void bridge
207 .downloadUpdate()
208 .then((result) => {
209 setDesktopUpdateStateQueryData(queryClient, result.state);
210 })
211 .catch((error: unknown) => {
212 toastManager.add(
213 stackedThreadToast({
214 type: "error",
215 title: "Could not download update",
216 description: error instanceof Error ? error.message : "Download failed.",
217 }),
218 );
219 });
220 return;
221 }
222​
223 if (action === "install") {
224 const confirmed = window.confirm(
225 getDesktopUpdateInstallConfirmationMessage(
226 updateState ?? { availableVersion: null, downloadedVersion: null },
227 ),
228 );
229 if (!confirmed) return;
230 void bridge
231 .installUpdate()
232 .then((result) => {
233 setDesktopUpdateStateQueryData(queryClient, result.state);
234 })
235 .catch((error: unknown) => {
236 toastManager.add(
237 stackedThreadToast({
238 type: "error",
239 title: "Could not install update",
240 description: error instanceof Error ? error.message : "Install failed.",
241 }),
242 );
243 });
244 return;
245 }
246​
247 if (typeof bridge.checkForUpdate !== "function") return;
248 void bridge
249 .checkForUpdate()
250 .then((result) => {
251 setDesktopUpdateStateQueryData(queryClient, result.state);
252 if (!result.checked) {
253 toastManager.add(
254 stackedThreadToast({
255 type: "error",
256 title: "Could not check for updates",
257 description:
258 result.state.message ?? "Automatic updates are not available in this build.",
259 }),
260 );
261 }
262 })
263 .catch((error: unknown) => {
264 toastManager.add(
265 stackedThreadToast({
266 type: "error",
267 title: "Could not check for updates",
268 description: error instanceof Error ? error.message : "Update check failed.",
269 }),
270 );
271 });
272 }, [queryClient, updateState]);
273​
274 const action = updateState ? resolveDesktopUpdateButtonAction(updateState) : "none";
275 const buttonTooltip = updateState ? getDesktopUpdateButtonTooltip(updateState) : null;
276 const buttonDisabled =
277 action === "none"
278 ? !canCheckForUpdate(updateState)
279 : isDesktopUpdateButtonDisabled(updateState);
280​
281 const actionLabel: Record<string, string> = { download: "Download", install: "Install" };
282 const statusLabel: Record<string, string> = {
283 checking: "Checking…",
284 downloading: "Downloading…",
285 "up-to-date": "Up to Date",
286 };
287 const buttonLabel =
288 actionLabel[action] ?? statusLabel[updateState?.status ?? ""] ?? "Check for Updates";
289 const description =
290 action === "download" || action === "install"
291 ? "Update available."
292 : "Current version of the application.";
293​
294 return (
295 <>
296 <SettingsRow
297 title={<AboutVersionTitle />}
298 description={description}
299 control={
300 <Tooltip>
301 <TooltipTrigger
302 render={
303 <Button
304 size="xs"
305 variant={action === "install" ? "default" : "outline"}
306 disabled={buttonDisabled}
307 onClick={handleButtonClick}
308 >
309 {buttonLabel}
310 </Button>
311 }
312 />
313 {buttonTooltip ? <TooltipPopup>{buttonTooltip}</TooltipPopup> : null}
314 </Tooltip>
315 }
316 />
317 <SettingsRow
318 title="Update track"
319 description="Stable follows full releases. Nightly follows the nightly desktop channel and can switch back to stable immediately."
320 control={
321 <Select
322 value={selectedUpdateChannel}
323 onValueChange={(value) => {
324 handleUpdateChannelChange(value as DesktopUpdateChannel);
325 }}
326 >
327 <SelectTrigger
328 className="w-full sm:w-40"
329 aria-label="Update track"
330 disabled={!hasDesktopBridge || isChangingUpdateChannel}
331 >
332 <SelectValue>
333 {selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
334 </SelectValue>
335 </SelectTrigger>
336 <SelectPopup align="end" alignItemWithTrigger={false}>
337 <SelectItem hideIndicator value="latest">
338 Stable
339 </SelectItem>
340 <SelectItem hideIndicator value="nightly">
341 Nightly
342 </SelectItem>
343 </SelectPopup>
344 </Select>
345 }
346 />
347 </>
348 );
350​
351export function useSettingsRestore(onRestored?: () => void) {
352 const { theme, setTheme } = useTheme();
353 const settings = useSettings();
354 const { updateSettings } = useUpdateSettings();
355​
356 const isGitWritingModelDirty = !Equal.equals(
357 settings.textGenerationModelSelection ?? null,
358 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
359 );
360​
361 const changedSettingLabels = useMemo(
362 () => [
363 ...(theme !== "system" ? ["Theme"] : []),
364 ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
365 ? ["Time format"]
366 : []),
367 ...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
368 ? ["Visible threads"]
369 : []),
370 ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
371 ? ["Diff line wrapping"]
372 : []),
373 ...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
374 ? ["Diff whitespace changes"]
375 : []),
376 ...(settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar
377 ? ["Auto-open task panel"]
378 : []),
379 ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
380 ? ["Assistant output"]
381 : []),
382 ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
383 ? ["New thread mode"]
384 : []),
385 ...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
386 ? ["Add project base directory"]
387 : []),
388 ...(settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive
389 ? ["Archive confirmation"]
390 : []),
391 ...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
392 ? ["Delete confirmation"]
393 : []),
394 ...(isGitWritingModelDirty ? ["Git writing model"] : []),
395 ],
396 [
397 isGitWritingModelDirty,
398 settings.autoOpenPlanSidebar,
399 settings.confirmThreadArchive,
400 settings.confirmThreadDelete,
401 settings.addProjectBaseDirectory,
402 settings.defaultThreadEnvMode,
403 settings.diffIgnoreWhitespace,
404 settings.diffWordWrap,
405 settings.enableAssistantStreaming,
406 settings.sidebarThreadPreviewCount,
407 settings.timestampFormat,
408 theme,
409 ],
410 );
411​
412 const restoreDefaults = useCallback(async () => {
413 if (changedSettingLabels.length === 0) return;
414 const api = readLocalApi();
415 const confirmed = await (api ?? ensureLocalApi()).dialogs.confirm(
416 ["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join(
417 "\n",
418 ),
419 );
420 if (!confirmed) return;
421​
422 setTheme("system");
423 updateSettings({
424 timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
425 diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
426 diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
427 sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
428 autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
429 enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
430 defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
431 addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
432 confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
433 confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
434 textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
435 });
436 onRestored?.();
437 }, [changedSettingLabels, onRestored, setTheme, updateSettings]);
438​
439 return {
440 changedSettingLabels,
441 restoreDefaults,
442 };
444​
445export function GeneralSettingsPanel() {
446 const { theme, setTheme } = useTheme();
447 const settings = useSettings();
448 const { updateSettings } = useUpdateSettings();
449 const observability = useServerObservability();
450 const serverProviders = useServerProviders();
451 const diagnosticsDescription = formatDiagnosticsDescription({
452 localTracingEnabled: observability?.localTracingEnabled ?? false,
453 otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
454 otlpTracesUrl: observability?.otlpTracesUrl,
455 otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
456 otlpMetricsUrl: observability?.otlpMetricsUrl,
457 });
458​
459 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
460 const textGenInstanceId = textGenerationModelSelection.instanceId;
461 const textGenModel = textGenerationModelSelection.model;
462 const textGenModelOptions = textGenerationModelSelection.options;
463 const gitModelInstanceEntries = sortProviderInstanceEntries(
464 deriveProviderInstanceEntries(serverProviders),
465 );
466 const textGenInstanceEntry = gitModelInstanceEntries.find(
467 (entry) => entry.instanceId === textGenInstanceId,
468 );
469 const textGenProvider: ProviderDriverKind =
470 textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
471 const gitModelOptionsByInstance = getCustomModelOptionsByInstance(
472 settings,
473 serverProviders,
474 textGenInstanceId,
475 textGenModel,
476 );
477 const isGitWritingModelDirty = !Equal.equals(
478 settings.textGenerationModelSelection ?? null,
479 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
480 );
481​
482 return (
483 <SettingsPageContainer>
484 <SettingsSection title="General">
485 <SettingsRow
486 title="Theme"
487 description="Choose how T3 Code looks across the app."
488 resetAction={
489 theme !== "system" ? (
490 <SettingResetButton label="theme" onClick={() => setTheme("system")} />
491 ) : null
492 }
493 control={
494 <Select
495 value={theme}
496 onValueChange={(value) => {
497 if (value === "system" || value === "light" || value === "dark") {
498 setTheme(value);
499 }
500 }}
501 >
502 <SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
503 <SelectValue>
504 {THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
505 </SelectValue>
506 </SelectTrigger>
507 <SelectPopup align="end" alignItemWithTrigger={false}>
508 {THEME_OPTIONS.map((option) => (
509 <SelectItem hideIndicator key={option.value} value={option.value}>
510 {option.label}
511 </SelectItem>
512 ))}
513 </SelectPopup>
514 </Select>
515 }
516 />
517​
518 <SettingsRow
519 title="Time format"
520 description="System default follows your browser or OS clock preference."
521 resetAction={
522 settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
523 <SettingResetButton
524 label="time format"
525 onClick={() =>
526 updateSettings({
527 timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
528 })
529 }
530 />
531 ) : null
532 }
533 control={
534 <Select
535 value={settings.timestampFormat}
536 onValueChange={(value) => {
537 if (value === "locale" || value === "12-hour" || value === "24-hour") {
538 updateSettings({ timestampFormat: value });
539 }
540 }}
541 >
542 <SelectTrigger className="w-full sm:w-40" aria-label="Timestamp format">
543 <SelectValue>{TIMESTAMP_FORMAT_LABELS[settings.timestampFormat]}</SelectValue>
544 </SelectTrigger>
545 <SelectPopup align="end" alignItemWithTrigger={false}>
546 <SelectItem hideIndicator value="locale">
547 {TIMESTAMP_FORMAT_LABELS.locale}
548 </SelectItem>
549 <SelectItem hideIndicator value="12-hour">
550 {TIMESTAMP_FORMAT_LABELS["12-hour"]}
551 </SelectItem>
552 <SelectItem hideIndicator value="24-hour">
553 {TIMESTAMP_FORMAT_LABELS["24-hour"]}
554 </SelectItem>
555 </SelectPopup>
556 </Select>
557 }
558 />
559​
560 <SettingsRow
561 title="Diff line wrapping"
562 description="Set the default wrap state when the diff panel opens."
563 resetAction={
564 settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
565 <SettingResetButton
566 label="diff line wrapping"
567 onClick={() =>
568 updateSettings({
569 diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
570 })
571 }
572 />
573 ) : null
574 }
575 control={
576 <Switch
577 checked={settings.diffWordWrap}
578 onCheckedChange={(checked) => updateSettings({ diffWordWrap: Boolean(checked) })}
579 aria-label="Wrap diff lines by default"
580 />
581 }
582 />
583​
584 <SettingsRow
585 title="Hide whitespace changes"
586 description="Set whether the diff panel ignores whitespace-only edits by default."
587 resetAction={
588 settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace ? (
589 <SettingResetButton
590 label="diff whitespace changes"
591 onClick={() =>
592 updateSettings({
593 diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
594 })
595 }
596 />
597 ) : null
598 }
599 control={
600 <Switch
601 checked={settings.diffIgnoreWhitespace}
602 onCheckedChange={(checked) =>
603 updateSettings({ diffIgnoreWhitespace: Boolean(checked) })
604 }
605 aria-label="Hide whitespace changes by default"
606 />
607 }
608 />
609​
610 <SettingsRow
611 title="Assistant output"
612 description="Show token-by-token output while a response is in progress."
613 resetAction={
614 settings.enableAssistantStreaming !==
615 DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
616 <SettingResetButton
617 label="assistant output"
618 onClick={() =>
619 updateSettings({
620 enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
621 })
622 }
623 />
624 ) : null
625 }
626 control={
627 <Switch
628 checked={settings.enableAssistantStreaming}
629 onCheckedChange={(checked) =>
630 updateSettings({ enableAssistantStreaming: Boolean(checked) })
631 }
632 aria-label="Stream assistant messages"
633 />
634 }
635 />
636​
637 <SettingsRow
638 title="Auto-open task panel"
639 description="Open the right-side plan and task panel automatically when steps appear."
640 resetAction={
641 settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar ? (
642 <SettingResetButton
643 label="auto-open task panel"
644 onClick={() =>
645 updateSettings({
646 autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
647 })
648 }
649 />
650 ) : null
651 }
652 control={
653 <Switch
654 checked={settings.autoOpenPlanSidebar}
655 onCheckedChange={(checked) =>
656 updateSettings({ autoOpenPlanSidebar: Boolean(checked) })
657 }
658 aria-label="Open the task panel automatically"
659 />
660 }
661 />
662​
663 <SettingsRow
664 title="New threads"
665 description="Pick the default workspace mode for newly created draft threads."
666 resetAction={
667 settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (
668 <SettingResetButton
669 label="new threads"
670 onClick={() =>
671 updateSettings({
672 defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
673 })
674 }
675 />
676 ) : null
677 }
678 control={
679 <Select
680 value={settings.defaultThreadEnvMode}
681 onValueChange={(value) => {
682 if (value === "local" || value === "worktree") {
683 updateSettings({ defaultThreadEnvMode: value });
684 }
685 }}
686 >
687 <SelectTrigger className="w-full sm:w-44" aria-label="Default thread mode">
688 <SelectValue>
689 {settings.defaultThreadEnvMode === "worktree" ? "New worktree" : "Local"}
690 </SelectValue>
691 </SelectTrigger>
692 <SelectPopup align="end" alignItemWithTrigger={false}>
693 <SelectItem hideIndicator value="local">
694 Local
695 </SelectItem>
696 <SelectItem hideIndicator value="worktree">
697 New worktree
698 </SelectItem>
699 </SelectPopup>
700 </Select>
701 }
702 />
703​
704 <SettingsRow
705 title="Add project starts in"
706 description='Leave empty to use "~/" when the Add Project browser opens.'
707 resetAction={
708 settings.addProjectBaseDirectory !==
709 DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory ? (
710 <SettingResetButton
711 label="add project base directory"
712 onClick={() =>
713 updateSettings({
714 addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
715 })
716 }
717 />
718 ) : null
719 }
720 control={
721 <DraftInput
722 className="w-full sm:w-72"
723 value={settings.addProjectBaseDirectory}
724 onCommit={(next) => updateSettings({ addProjectBaseDirectory: next })}
725 placeholder="~/"
726 spellCheck={false}
727 aria-label="Add project base directory"
728 />
729 }
730 />
731​
732 <SettingsRow
733 title="Archive confirmation"
734 description="Require a second click on the inline archive action before a thread is archived."
735 resetAction={
736 settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
737 <SettingResetButton
738 label="archive confirmation"
739 onClick={() =>
740 updateSettings({
741 confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
742 })
743 }
744 />
745 ) : null
746 }
747 control={
748 <Switch
749 checked={settings.confirmThreadArchive}
750 onCheckedChange={(checked) =>
751 updateSettings({ confirmThreadArchive: Boolean(checked) })
752 }
753 aria-label="Confirm thread archiving"
754 />
755 }
756 />
757​
758 <SettingsRow
759 title="Delete confirmation"
760 description="Ask before deleting a thread and its chat history."
761 resetAction={
762 settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
763 <SettingResetButton
764 label="delete confirmation"
765 onClick={() =>
766 updateSettings({
767 confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
768 })
769 }
770 />
771 ) : null
772 }
773 control={
774 <Switch
775 checked={settings.confirmThreadDelete}
776 onCheckedChange={(checked) =>
777 updateSettings({ confirmThreadDelete: Boolean(checked) })
778 }
779 aria-label="Confirm thread deletion"
780 />
781 }
782 />
783​
784 <SettingsRow
785 title="Text generation model"
786 description="Configure the model used for generated commit messages, PR titles, and similar Git text."
787 resetAction={
788 isGitWritingModelDirty ? (
789 <SettingResetButton
790 label="text generation model"
791 onClick={() =>
792 updateSettings({
793 textGenerationModelSelection:
794 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
795 })
796 }
797 />
798 ) : null
799 }
800 control={
801 <div className="flex flex-wrap items-center justify-end gap-1.5">
802 <ProviderModelPicker
803 activeInstanceId={textGenInstanceId}
804 model={textGenModel}
805 lockedProvider={null}
806 instanceEntries={gitModelInstanceEntries}
807 modelOptionsByInstance={gitModelOptionsByInstance}
808 triggerVariant="outline"
809 triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
810 onInstanceModelChange={(instanceId, model) => {
811 updateSettings({
812 textGenerationModelSelection: resolveAppModelSelectionState(
813 {
814 ...settings,
815 textGenerationModelSelection: createModelSelection(instanceId, model),
816 },
817 serverProviders,
818 ),
819 });
820 }}
821 />
822 <TraitsPicker
823 provider={textGenProvider}
824 models={
825 // Use the exact instance's models (rather than the
826 // first-kind-match) so a custom text-gen instance like
827 // `codex_personal` gets its own model list, not the
828 // default Codex one.
829 textGenInstanceEntry?.models ?? []
830 }
831 model={textGenModel}
832 prompt=""
833 onPromptChange={() => {}}
834 modelOptions={textGenModelOptions}
835 allowPromptInjectedEffort={false}
836 triggerVariant="outline"
837 triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
838 onModelOptionsChange={(nextOptions) => {
839 updateSettings({
840 textGenerationModelSelection: resolveAppModelSelectionState(
841 {
842 ...settings,
843 textGenerationModelSelection: createModelSelection(
844 textGenInstanceId,
845 textGenModel,
846 nextOptions,
847 ),
848 },
849 serverProviders,
850 ),
851 });
852 }}
853 />
854 </div>
855 }
856 />
857 </SettingsSection>
858​
859 <SettingsSection title="About">
860 {isElectron ? (
861 <AboutVersionSection />
862 ) : (
863 <SettingsRow
864 title={<AboutVersionTitle />}
865 description="Current version of the application."
866 />
867 )}
868 <SettingsRow
869 title="Diagnostics"
870 description={diagnosticsDescription}
871 control={
872 <Button render={<Link to="/settings/diagnostics" />} size="xs" variant="outline">
873 View diagnostics
874 </Button>
875 }
876 />
877 </SettingsSection>
878 </SettingsPageContainer>
879 );
881​
882export function ProviderSettingsPanel() {
883 const settings = useSettings();
884 const { updateSettings } = useUpdateSettings();
885 const serverProviders = useServerProviders();
886 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
887 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
888 const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
889 ReadonlySet<ProviderDriverKind>
890 >(() => new Set());
891 const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
892 const refreshingRef = useRef(false);
893​
894 const providerUpdateCandidates = useMemo(
895 () => collectProviderUpdateCandidates(serverProviders),
896 [serverProviders],
897 );
898 const providerUpdateCandidateByInstanceId = useMemo(
899 () => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
900 [providerUpdateCandidates],
901 );
902 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
903 (providerSettings) =>
904 providerSettings.provider !== "cursor" ||
905 serverProviders.some(
906 (provider) =>
907 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
908 ),
909 );
910 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
911 const textGenInstanceId = textGenerationModelSelection.instanceId;
912 const lastCheckedAt =
913 serverProviders.length > 0
914 ? serverProviders.reduce(
915 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
916 serverProviders[0]!.checkedAt,
917 )
918 : null;
919​
920 const refreshProviders = useCallback(() => {
921 if (refreshingRef.current) return;
922 refreshingRef.current = true;
923 setIsRefreshingProviders(true);
924 void ensureLocalApi()
925 .server.refreshProviders()
926 .catch((error: unknown) => {
927 console.warn("Failed to refresh providers", error);
928 })
929 .finally(() => {
930 refreshingRef.current = false;
931 setIsRefreshingProviders(false);
932 });
933 }, []);
934​
935 const runProviderUpdate = useCallback(async (candidate: ProviderUpdateCandidate) => {
936 let started = false;
937 setUpdatingProviderDrivers((previous) => {
938 if (previous.has(candidate.driver)) {
939 return previous;
940 }
941 started = true;
942 const next = new Set(previous);
943 next.add(candidate.driver);
944 return next;
945 });
946 if (!started) {
947 return;
948 }
949​
950 try {
951 await ensureLocalApi().server.updateProvider({
952 provider: candidate.driver,
953 instanceId: candidate.instanceId,
954 });
955 } catch (error) {
956 toastManager.add(
957 stackedThreadToast({
958 type: "error",
959 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
960 description:
961 error instanceof Error
962 ? error.message
963 : "The provider update command could not be started.",
964 }),
965 );
966 } finally {
967 setUpdatingProviderDrivers((previous) => {
968 if (!previous.has(candidate.driver)) {
969 return previous;
970 }
971 const next = new Set(previous);
972 next.delete(candidate.driver);
973 return next;
974 });
975 }
976 }, []);
977​
978 interface InstanceRow {
979 readonly instanceId: ProviderInstanceId;
980 readonly instance: ProviderInstanceConfig;
981 readonly driver: ProviderDriverKind;
982 readonly isDefault: boolean;
983 readonly isDirty?: boolean;
984 }
985​
986 const instancesByDriver = new Map<
987 ProviderDriverKind,
988 Array<[ProviderInstanceId, ProviderInstanceConfig]>
989 >();
990 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
991 const driver = instance.driver;
992 const list = instancesByDriver.get(driver) ?? [];
993 list.push([rawId as ProviderInstanceId, instance]);
994 instancesByDriver.set(driver, list);
995 }
996​
997 const defaultSlotIdsBySource = new Set<string>(
998 visibleProviderSettings.map((providerSettings) =>
999 String(defaultInstanceIdForDriver(providerSettings.provider)),
1000 ),
1001 );
1002​
1003 const rows: InstanceRow[] = [];
1004 const visibleDriverKinds = new Set<ProviderDriverKind>(
1005 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
1006 );
1007​
1008 for (const providerSettings of visibleProviderSettings) {
1009 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
1010 const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
1011 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
1012 string,
1013 LegacyProviderSettings
1014 >;
1015 const driver = providerSettings.provider;
1016 const defaultInstanceId = defaultInstanceIdForDriver(driver);
1017 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
1018 const legacyConfig = legacyProviders[providerSettings.provider]!;
1019 const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;
1020 const effectiveInstance: ProviderInstanceConfig =
1021 explicitInstance ??
1022 ({
1023 driver,
1024 enabled: legacyConfig.enabled,
1025 config: legacyConfig,
1026 } satisfies ProviderInstanceConfig);
1027 const isDirty =
1028 explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
1029 rows.push({
1030 instanceId: defaultInstanceId,
1031 instance: effectiveInstance,
1032 driver,
1033 isDefault: true,
1034 isDirty,
1035 });
1036 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
1037 if (id === defaultInstanceId) continue;
1038 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
1041 for (const [driver, list] of instancesByDriver) {
1042 if (visibleDriverKinds.has(driver)) continue;
1043 for (const [id, instance] of list) {
1044 rows.push({
1045 instanceId: id,
1046 instance,
1047 driver: instance.driver,
1048 isDefault: defaultSlotIdsBySource.has(String(id)),
1049 });
1052​
1053 const updateProviderInstance = (
1054 row: InstanceRow,
1055 next: ProviderInstanceConfig,
1056 options?: {
1057 readonly textGenerationModelSelection?: Parameters<
1058 typeof buildProviderInstanceUpdatePatch
1059 >[0]["textGenerationModelSelection"];
1060 },
1061 ) => {
1062 updateSettings(
1063 buildProviderInstanceUpdatePatch({
1064 settings,
1065 instanceId: row.instanceId,
1066 instance: next,
1067 driver: row.driver,
1068 isDefault: row.isDefault,
1069 textGenerationModelSelection: options?.textGenerationModelSelection,
1070 }),
1071 );
1072 };
1073​
1074 const deleteProviderInstance = (id: ProviderInstanceId) => {
1075 updateSettings({
1076 providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
1077 providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
1078 favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
1079 });
1080 };
1081​
1082 const updateProviderModelPreferences = (
1083 instanceId: ProviderInstanceId,
1084 next: {
1085 readonly hiddenModels: ReadonlyArray<string>;
1086 readonly modelOrder: ReadonlyArray<string>;
1087 },
1088 ) => {
1089 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
1090 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
1091 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
1092 updateSettings({
1093 providerModelPreferences:
1094 hiddenModels.length === 0 && modelOrder.length === 0
1095 ? rest
1096 : {
1097 ...rest,
1098 [instanceId]: {
1099 hiddenModels,
1100 modelOrder,
1101 },
1102 },
1103 });
1104 };
1105​
1106 const updateProviderFavoriteModels = (
1107 instanceId: ProviderInstanceId,
1108 nextFavoriteModels: ReadonlyArray<string>,
1109 ) => {
1110 const favoriteModels = [
1111 ...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),
1112 ];
1113 updateSettings({
1114 favorites: [
1115 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
1116 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
1117 ],
1118 });
1119 };
1120​
1121 const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
1122 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
1123 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
1124 string,
1125 LegacyProviderSettings | undefined
1126 >;
1127 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
1128 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
1129 if (defaultLegacyProvider === undefined) return;
1130 updateSettings({
1131 providers: {
1132 ...settings.providers,
1133 [driverKind]: defaultLegacyProvider,
1134 } as typeof settings.providers,
1135 providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
1136 providerModelPreferences: withoutProviderInstanceKey(
1137 settings.providerModelPreferences,
1138 defaultInstanceId,
1139 ),
1140 favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),
1141 });
1142 };
1143​
1144 return (
1145 <SettingsPageContainer>
1146 <SettingsSection
1147 title="Providers"
1148 headerAction={
1149 <div className="flex items-center gap-1.5">
1150 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1151 <Tooltip>
1152 <TooltipTrigger
1153 render={
1154 <Button
1155 size="icon-xs"
1156 variant="ghost"
1157 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1158 onClick={() => setIsAddInstanceDialogOpen(true)}
1159 aria-label="Add provider instance"
1161 <PlusIcon className="size-3" />
1162 </Button>
1164 />
1165 <TooltipPopup side="top">Add provider instance</TooltipPopup>
1166 </Tooltip>
1167 <Tooltip>
1168 <TooltipTrigger
1169 render={
1170 <Button
1171 size="icon-xs"
1172 variant="ghost"
1173 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1174 disabled={isRefreshingProviders}
1175 onClick={() => void refreshProviders()}
1176 aria-label="Refresh provider status"
1178 {isRefreshingProviders ? (
1179 <LoaderIcon className="size-3 animate-spin" />
1180 ) : (
1181 <RefreshCwIcon className="size-3" />
1182 )}
1183 </Button>
1185 />
1186 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1187 </Tooltip>
1188 </div>
1191 {rows.map((row) => {
1192 const driverOption = getDriverOption(row.driver);
1193 const liveProvider = serverProviders.find(
1194 (candidate) => candidate.instanceId === row.instanceId,
1195 );
1196 const updateCandidate = liveProvider
1197 ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
1198 : undefined;
1199 const isDriverUpdateRunning =
1200 updateCandidate !== undefined &&
1201 (updatingProviderDrivers.has(updateCandidate.driver) ||
1202 serverProviders.some(
1203 (provider) =>
1204 provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
1205 ));
1206 const showInlineUpdateButton =
1207 updateCandidate !== undefined &&
1208 hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
1209 const canRunInlineUpdate =
1210 updateCandidate !== undefined &&
1211 canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
1212 !updatingProviderDrivers.has(updateCandidate.driver);
1213 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
1214 hiddenModels: [],
1215 modelOrder: [],
1216 };
1217 const favoriteModels = (settings.favorites ?? [])
1218 .filter((favorite) => favorite.provider === row.instanceId)
1219 .map((favorite) => favorite.model);
1220 const resetLabel = driverOption?.label ?? String(row.driver);
1221 const headerAction =
1222 row.isDefault && row.isDirty ? (
1223 <SettingResetButton
1224 label={`${resetLabel} provider settings`}
1225 onClick={() => resetDefaultInstance(row.driver)}
1226 />
1227 ) : null;
1228 return (
1229 <ProviderInstanceCard
1230 key={row.instanceId}
1231 instanceId={row.instanceId}
1232 instance={row.instance}
1233 driverOption={driverOption}
1234 liveProvider={liveProvider}
1235 isExpanded={openInstanceDetails[row.instanceId] ?? false}
1236 onExpandedChange={(open) =>
1237 setOpenInstanceDetails((existing) => ({
1238 ...existing,
1239 [row.instanceId]: open,
1240 }))
1242 onUpdate={(next) => {
1243 const wasEnabled = row.instance.enabled ?? true;
1244 const isDisabling = next.enabled === false && wasEnabled;
1245 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
1246 if (shouldClearTextGen) {
1247 updateProviderInstance(row, next, {
1248 textGenerationModelSelection:
1249 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
1250 });
1251 } else {
1252 updateProviderInstance(row, next);
1254 }}
1255 onDelete={row.isDefault ? undefined : () => deleteProviderInstance(row.instanceId)}
1256 headerAction={headerAction}
1257 hiddenModels={modelPreferences.hiddenModels}
1258 favoriteModels={favoriteModels}
1259 modelOrder={modelPreferences.modelOrder}
1260 onHiddenModelsChange={(hiddenModels) =>
1261 updateProviderModelPreferences(row.instanceId, {
1262 ...modelPreferences,
1263 hiddenModels,
1264 })
1266 onFavoriteModelsChange={(favoriteModels) =>
1267 updateProviderFavoriteModels(row.instanceId, favoriteModels)
1269 onModelOrderChange={(modelOrder) =>
1270 updateProviderModelPreferences(row.instanceId, {
1271 ...modelPreferences,
1272 modelOrder,
1273 })
1275 onRunUpdate={
1276 showInlineUpdateButton && updateCandidate
1277 ? () => {
1278 if (!canRunInlineUpdate) {
1279 return;
1281 void runProviderUpdate(updateCandidate);
1283 : undefined
1285 isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
1286 />
1287 );
1288 })}
1289 </SettingsSection>
1290​
1291 <AddProviderInstanceDialog
1292 open={isAddInstanceDialogOpen}
1293 onOpenChange={setIsAddInstanceDialogOpen}
1294 />
1295 </SettingsPageContainer>
1296 );
1298​
1299export function ArchivedThreadsPanel() {
1300 const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
1301 const threads = useStore(useShallow(selectThreadShellsAcrossEnvironments));
1302 const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
1303 const archivedGroups = useMemo(() => {
1304 return projects
1305 .map((project) => ({
1306 project,
1307 threads: threads
1308 .filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)
1309 .toSorted((left, right) => {
1310 const leftKey = left.archivedAt ?? left.createdAt;
1311 const rightKey = right.archivedAt ?? right.createdAt;
1312 return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);
1313 }),
1314 }))
1315 .filter((group) => group.threads.length > 0);
1316 }, [projects, threads]);
1317​
1318 const handleArchivedThreadContextMenu = useCallback(
1319 async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
1320 const api = readLocalApi();
1321 if (!api) return;
1322 const clicked = await api.contextMenu.show(
1324 { id: "unarchive", label: "Unarchive" },
1325 { id: "delete", label: "Delete", destructive: true },
1326 ],
1327 position,
1328 );
1329​
1330 if (clicked === "unarchive") {
1331 try {
1332 await unarchiveThread(threadRef);
1333 } catch (error) {
1334 toastManager.add(
1335 stackedThreadToast({
1336 type: "error",
1337 title: "Failed to unarchive thread",
1338 description: error instanceof Error ? error.message : "An error occurred.",
1339 }),
1340 );
1342 return;
1344​
1345 if (clicked === "delete") {
1346 await confirmAndDeleteThread(threadRef);
1348 },
1349 [confirmAndDeleteThread, unarchiveThread],
1350 );
1351​
1352 return (
1353 <SettingsPageContainer>
1354 {archivedGroups.length === 0 ? (
1355 <SettingsSection title="Archived threads">
1356 <Empty className="min-h-88">
1357 <EmptyMedia variant="icon">
1358 <ArchiveIcon />
1359 </EmptyMedia>
1360 <EmptyHeader>
1361 <EmptyTitle>No archived threads</EmptyTitle>
1362 <EmptyDescription>Archived threads will appear here.</EmptyDescription>
1363 </EmptyHeader>
1364 </Empty>
1365 </SettingsSection>
1366 ) : (
1367 archivedGroups.map(({ project, threads: projectThreads }) => (
1368 <SettingsSection
1369 key={project.id}
1370 title={project.name}
1371 icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
1373 {projectThreads.map((thread) => (
1374 <div
1375 key={thread.id}
1376 className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
1377 onContextMenu={(event) => {
1378 event.preventDefault();
1379 void handleArchivedThreadContextMenu(
1380 scopeThreadRef(thread.environmentId, thread.id),
1382 x: event.clientX,
1383 y: event.clientY,
1384 },
1385 );
1386 }}
1388 <div className="min-w-0 flex-1">
1389 <h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>
1390 <p className="text-xs text-muted-foreground">
1391 Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}
1392 {" \u00b7 Created "}
1393 {formatRelativeTimeLabel(thread.createdAt)}
1394 </p>
1395 </div>
1396 <Button
1397 type="button"
1398 variant="outline"
1399 size="sm"
1400 className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
1401 onClick={() =>
1402 void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id)).catch(
1403 (error) => {
1404 toastManager.add(
1405 stackedThreadToast({
1406 type: "error",
1407 title: "Failed to unarchive thread",
1408 description:
1409 error instanceof Error ? error.message : "An error occurred.",
1410 }),
1411 );
1412 },
1416 <ArchiveX className="size-3.5" />
1417 <span>Unarchive</span>
1418 </Button>
1419 </div>
1420 ))}
1421 </SettingsSection>
1422 ))
1423 )}
1424 </SettingsPageContainer>
1425 );