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