Open History to see the last commit
1import { ChevronDownIcon, GitPullRequestIcon, InfoIcon, RefreshCwIcon } from "lucide-react";
2import * as Duration from "effect/Duration";
3import * as Option from "effect/Option";
4import { useState, type ReactNode } from "react";
5import type {
6 BackgroundActivitySettings,
7 SourceControlProviderKind,
8 SourceControlDiscoveryResult,
9 SourceControlProviderAuth,
10 SourceControlProviderDiscoveryItem,
11 VcsDriverKind,
12 VcsDiscoveryItem,
13} from "@t3tools/contracts";
14import {
15 getBackgroundActivityBaseProfile,
16 getBackgroundActivityPresetSettings,
17 resolveServerBackgroundActivitySettings,
18} from "@t3tools/shared/backgroundActivitySettings";
19
20import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
21import { cn } from "../../lib/utils";
22import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
23import { useEnvironmentQuery } from "../../state/query";
24import { sourceControlEnvironment } from "../../state/sourceControl";
25import { Badge } from "../ui/badge";
26import { Button } from "../ui/button";
27import { Collapsible, CollapsibleContent } from "../ui/collapsible";
28import {
29 Empty,
30 EmptyContent,
31 EmptyDescription,
32 EmptyHeader,
33 EmptyMedia,
34 EmptyTitle,
35} from "../ui/empty";
36import { Skeleton } from "../ui/skeleton";
37import {
38 NumberField,
39 NumberFieldDecrement,
40 NumberFieldGroup,
41 NumberFieldIncrement,
42 NumberFieldInput,
43} from "../ui/number-field";
44import { Switch } from "../ui/switch";
45import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
46import {
47 AzureDevOpsIcon,
48 BitbucketIcon,
49 GitHubIcon,
50 GitIcon,
51 GitLabIcon,
52 JujutsuIcon,
53 type Icon,
54} from "../Icons";
55import { RedactedSensitiveText } from "./RedactedSensitiveText";
56import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
57import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
58import { searchableSetting } from "./settingsSearch";
59
60const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
61 versionControlSystems: [],
62 sourceControlProviders: [],
63};
64
65const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
66 github: GitHubIcon,
67 gitlab: GitLabIcon,
68 "azure-devops": AzureDevOpsIcon,
69 bitbucket: BitbucketIcon,
70};
71
72const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
73 git: GitIcon,
74 jj: JujutsuIcon,
75};
76
77const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
78const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
79type BackgroundActivityOverridePatch = Partial<{
80 [K in keyof BackgroundActivitySettings["overrides"]]:
81 | BackgroundActivitySettings["overrides"][K]
82 | undefined;
83}>;
84
85function durationToSeconds(duration: Duration.Duration): number {
86 return Math.round(Duration.toMillis(duration) / 1_000);
87}
88
89function normalizeFetchIntervalSeconds(value: number | null): number {
90 if (value === null || !Number.isFinite(value)) {
91 return 0;
92 }
93 return Math.max(0, Math.round(value));
94}
95
96function backgroundActivityOverrideSettings(
97 current: BackgroundActivitySettings,
98 overrides: BackgroundActivityOverridePatch,
99) {
100 const nextOverrides: BackgroundActivityOverridePatch = {
101 ...current.overrides,
102 ...overrides,
103 };
104 for (const [key, value] of Object.entries(nextOverrides)) {
105 if (value === undefined) {
106 delete nextOverrides[key as keyof typeof nextOverrides];
107 }
108 }
109 return {
110 backgroundActivity: {
111 schemaVersion: 1 as const,
112 profile: "custom" as const,
113 baseProfile: getBackgroundActivityBaseProfile(current),
114 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
115 },
116 };
117}
118
119function BackgroundPolicyTooltip({ children }: { readonly children: string }) {
120 return (
121 <Tooltip>
122 <TooltipTrigger
123 render={
124 <button
125 type="button"
126 className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
127 aria-label="Background policy details"
128 >
129 <InfoIcon className="size-3.5" />
130 </button>
131 }
132 />
133 <TooltipPopup side="top" className="max-w-72">
134 {children}
135 </TooltipPopup>
136 </Tooltip>
137 );
138}
139
140function optionLabel(value: Option.Option<string>): string | null {
141 return Option.getOrNull(value);
142}
143
144function isProviderDiscoveryItem(
145 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
146): item is SourceControlProviderDiscoveryItem {
147 return "auth" in item;
148}
149
150function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
151 return !isProviderDiscoveryItem(item) && !item.implemented;
152}
153
154function authPresentation(auth: SourceControlProviderAuth): {
155 readonly label: string;
156 readonly badge: "warning" | null;
157} {
158 if (auth.status === "authenticated") {
159 return { label: "Authenticated", badge: null };
160 }
161 if (auth.status === "unauthenticated") {
162 return { label: "Not authenticated", badge: "warning" };
163 }
164 return { label: "Status unknown", badge: null };
165}
166
167function RedactedAccount(props: { readonly account: string | null }) {
168 return (
169 <RedactedSensitiveText
170 value={props.account}
171 ariaLabel="Toggle source control account visibility"
172 revealTooltip="Click to reveal account"
173 hideTooltip="Click to hide account"
174 />
175 );
176}
177
178function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
179 if (isVcsNotReady(item)) return "bg-muted-foreground/35";
180 if (item.status !== "available") return "bg-warning";
181 if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning";
182 return "bg-success";
183}
184
185function SourceControlItemMark({
186 item,
187}: {
188 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
189}) {
190 const dotClassName = itemStatusDot(item);
191 const Icon = isProviderDiscoveryItem(item)
192 ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
193 : VCS_ICONS[item.kind];
194
195 if (!Icon) {
196 return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
197 }
198
199 return (
200 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
201 <Icon className="size-4.5 text-foreground/80" aria-hidden />
202 <span
203 className={cn(
204 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
205 dotClassName,
206 )}
207 aria-hidden
208 />
209 </span>
210 );
211}
212
213function itemSummary({
214 item,
215 auth,
216 authAccount,
217}: {
218 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
219 readonly auth: SourceControlProviderAuth | null;
220 readonly authAccount: string | null;
221}) {
222 if (isVcsNotReady(item)) {
223 return <span>Support for {item.label} is coming soon.</span>;
224 }
225
226 if (item.status !== "available") {
227 return <span>Not available on this server: {item.installHint}</span>;
228 }
229
230 if (auth) {
231 if (auth.status === "authenticated") {
232 return (
233 <>
234 <span>Authenticated</span>
235 {authAccount ? (
236 <>
237 <span aria-hidden>as</span>
238 <RedactedAccount account={authAccount} />
239 </>
240 ) : null}
241 </>
242 );
243 }
244
245 if (!item.executable) {
246 return <span>Available. {item.installHint}</span>;
247 }
248
249 if (auth.status === "unauthenticated") {
250 return (
251 <span>
252 {item.label} is not authenticated on this server. Sign in or configure credentials using
253 the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
254 tool on the server host to enable change request features.
255 </span>
256 );
257 }
258 return (
259 <span>
260 Could not verify {item.label}. {item.installHint}
261 </span>
262 );
263 }
264
265 return <span>Available</span>;
266}
267
268function DiscoveryItemRow({
269 item,
270 children,
271}: {
272 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
273 readonly children?: ReactNode;
274}) {
275 const version = optionLabel(item.version);
276 const enabled = isProviderDiscoveryItem(item)
277 ? item.status === "available" && item.auth.status === "authenticated"
278 : item.status === "available" && item.implemented;
279 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
280 const authStatus = auth ? authPresentation(auth) : null;
281 const authAccount = auth ? optionLabel(auth.account) : null;
282 const [isExpanded, setIsExpanded] = useState(false);
283 const hasDetails = children !== undefined;
284
285 return (
286 <div
287 className={cn(
288 "rounded-xl transition-colors hover:bg-muted/20",
289 isVcsNotReady(item) && "opacity-80",
290 )}
291 >
292 <div className="px-3 py-3 sm:px-4">
293 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
294 <div className="min-w-0 flex-1 space-y-1">
295 <div className="flex min-w-0 flex-wrap items-center gap-2">
296 <SourceControlItemMark item={item} />
297 <span className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
298 {item.label}
299 </span>
300 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
301 {isVcsNotReady(item) ? (
302 <Badge variant="warning" size="sm">
303 Coming Soon
304 </Badge>
305 ) : null}
306 {authStatus?.badge ? (
307 <Badge variant={authStatus.badge} size="sm">
308 {authStatus.label}
309 </Badge>
310 ) : null}
311 </div>
312 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-[13px] leading-[1.45] text-muted-foreground/80">
313 {itemSummary({ item, auth, authAccount })}
314 </p>
315 </div>
316 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
317 {hasDetails ? (
318 <Button
319 size="sm"
320 variant="ghost"
321 className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
322 onClick={() => setIsExpanded((open) => !open)}
323 aria-expanded={isExpanded}
324 aria-label={`Toggle ${item.label} details`}
325 >
326 <ChevronDownIcon
327 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
328 />
329 </Button>
330 ) : null}
331 {!isVcsNotReady(item) ? (
332 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
333 ) : null}
334 </div>
335 </div>
336 </div>
337
338 {hasDetails ? (
339 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
340 <CollapsibleContent>
341 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
342 </CollapsibleContent>
343 </Collapsible>
344 ) : null}
345 </div>
346 );
347}
348
349function GitFetchIntervalSettings() {
350 const settings = usePrimarySettings();
351 const updateSettings = useUpdatePrimarySettings();
352 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
353 const automaticGitFetchIntervalSeconds = durationToSeconds(
354 resolvedBackgroundActivity.automaticGitFetchInterval,
355 );
356 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
357 getBackgroundActivityPresetSettings(
358 getBackgroundActivityBaseProfile(settings.backgroundActivity),
359 ).automaticGitFetchInterval,
360 );
361 const canResetFetchInterval =
362 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
363
364 return (
365 <div className="grid gap-3">
366 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
367 <div className="min-w-0 space-y-1">
368 <div className="flex min-w-0 items-center gap-1">
369 <span className="text-xs font-medium text-foreground">Fetch interval</span>
370 <BackgroundPolicyTooltip>
371 This interval is configured for Git only. The shared Background activity policy still
372 decides whether Git refreshes may run when the timer fires. Custom intervals appear as
373 Advanced in General settings.
374 </BackgroundPolicyTooltip>
375 <span
376 className={cn(
377 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
378 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
379 )}
380 aria-hidden={!canResetFetchInterval}
381 >
382 {canResetFetchInterval ? (
383 <SettingResetButton
384 label="fetch interval"
385 onClick={() =>
386 updateSettings(
387 backgroundActivityOverrideSettings(settings.backgroundActivity, {
388 automaticGitFetchInterval: undefined,
389 }),
390 )
391 }
392 />
393 ) : null}
394 </span>
395 </div>
396 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
397 Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
398 or security keys should only be prompted by explicit Git actions.
399 </p>
400 </div>
401 <div className="flex shrink-0 items-center gap-2">
402 <NumberField
403 value={automaticGitFetchIntervalSeconds}
404 min={0}
405 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
406 size="sm"
407 className="w-32"
408 onValueChange={(value) =>
409 updateSettings(
410 backgroundActivityOverrideSettings(settings.backgroundActivity, {
411 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
412 }),
413 )
414 }
415 >
416 <NumberFieldGroup>
417 <NumberFieldDecrement aria-label="Decrease fetch interval" />
418 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
419 <NumberFieldIncrement aria-label="Increase fetch interval" />
420 </NumberFieldGroup>
421 </NumberField>
422 <span className="text-xs text-muted-foreground">seconds</span>
423 </div>
424 </div>
425 </div>
426 );
427}
428
429function SourceControlSectionSkeleton({
430 title,
431 headerAction,
432}: {
433 readonly title: string;
434 readonly headerAction?: ReactNode;
435}) {
436 return (
437 <SettingsSection title={title} headerAction={headerAction}>
438 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
439 <div key={row} className="rounded-xl px-3 py-3 sm:px-4">
440 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
441 <div className="min-w-0 flex-1 space-y-2">
442 <div className="flex items-center gap-2">
443 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
444 <Skeleton className="size-4.5 rounded-md" />
445 <Skeleton
446 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
447 aria-hidden
448 />
449 </span>
450 <Skeleton className="h-4 w-28 rounded-full" />
451 <Skeleton className="h-5 w-14 rounded-full" />
452 </div>
453 <Skeleton className="h-3 w-full max-w-xs rounded-full" />
454 </div>
455 <div className="flex shrink-0 items-center gap-2">
456 <Skeleton className="size-7 rounded-md" />
457 <Skeleton className="h-5 w-9 rounded-full" />
458 </div>
459 </div>
460 </div>
461 ))}
462 </SettingsSection>
463 );
464}
465
466function EmptySourceControlDiscovery({
467 error,
468 isPending,
469 onScan,
470}: {
471 readonly error: string | null;
472 readonly isPending: boolean;
473 readonly onScan: () => void;
474}) {
475 const hasError = error !== null;
476
477 return (
478 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
479 <Empty className="min-h-88">
480 <EmptyMedia variant="icon">
481 <GitPullRequestIcon />
482 </EmptyMedia>
483 <EmptyHeader>
484 <EmptyTitle>
485 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
486 </EmptyTitle>
487 <EmptyDescription>
488 {hasError
489 ? error
490 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
491 </EmptyDescription>
492 </EmptyHeader>
493 <EmptyContent>
494 <Button
495 size="sm"
496 variant="outline"
497 className="h-8 gap-1.5 px-3 text-xs"
498 onClick={onScan}
499 disabled={isPending}
500 >
501 <RefreshCwIcon className={cn("size-3.5", isPending && "animate-spin")} />
502 Scan
503 </Button>
504 </EmptyContent>
505 </Empty>
506 </SettingsSection>
507 );
508}
509
510export function SourceControlSettingsPanel() {
511 const { environments } = useEnvironments();
512 const primaryEnvironment = usePrimaryEnvironment();
513 const fallbackEnvironment =
514 environments.find((environment) => environment.connection.phase === "connected") ??
515 environments[0] ??
516 null;
517 const environmentId =
518 primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
519 const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
520 const discovery = useEnvironmentQuery(
521 environmentId === null
522 ? null
523 : sourceControlEnvironment.discovery({
524 environmentId,
525 input: {},
526 }),
527 );
528 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
529 const hasVersionControlSystems = result.versionControlSystems.length > 0;
530 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
531 const isInitialScanPending = discovery.isPending && discovery.data === null;
532 const handleScan = () => {
533 discovery.refresh();
534 };
535 const scanButton = (
536 <Tooltip>
537 <TooltipTrigger
538 render={
539 <Button
540 size="icon-xs"
541 variant="ghost"
542 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
543 onClick={handleScan}
544 disabled={discovery.isPending}
545 aria-label="Rescan server environment"
546 >
547 <RefreshCwIcon className={cn("size-3", discovery.isPending && "animate-spin")} />
548 </Button>
549 }
550 />
551 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
552 </Tooltip>
553 );
554
555 return (
556 <SettingsPageContainer>
557 {isInitialScanPending ? (
558 <>
559 <SourceControlSectionSkeleton title="Version Control" headerAction={scanButton} />
560 <SourceControlSectionSkeleton title="Source Control Providers" />
561 </>
562 ) : hasDiscoveryItems ? (
563 <>
564 {hasVersionControlSystems ? (
565 <SettingsSection
566 id={searchableSetting("source-control").id}
567 title="Version Control"
568 headerAction={scanButton}
569 >
570 {result.versionControlSystems.map((item) => (
571 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
572 {item.kind === "git" && isPrimaryEnvironment ? (
573 <GitFetchIntervalSettings />
574 ) : undefined}
575 </DiscoveryItemRow>
576 ))}
577 </SettingsSection>
578 ) : null}
579
580 {result.sourceControlProviders.length > 0 ? (
581 <SettingsSection
582 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
583 title="Source Control Providers"
584 headerAction={hasVersionControlSystems ? null : scanButton}
585 >
586 {result.sourceControlProviders.map((item) => (
587 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
588 ))}
589 </SettingsSection>
590 ) : null}
591 </>
592 ) : (
593 <EmptySourceControlDiscovery
594 error={discovery.error}
595 isPending={discovery.isPending}
596 onScan={handleScan}
597 />
598 )}
599
600 {isPrimaryEnvironment ? <SourceControlWritingSettingsSection /> : null}
601 </SettingsPageContainer>
602 );
603}