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