Open History to see the last commit
1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { ChevronDownIcon } from "lucide-react";
3import * as Duration from "effect/Duration";
4import * as Option from "effect/Option";
5import { useEffect, useState, type ReactNode } from "react";
6import type {
7 BackgroundActivitySettings,
8 SourceControlProviderKind,
9 SourceControlDiscoveryResult,
10 SourceControlProviderAuth,
11 SourceControlProviderDiscoveryItem,
12 VcsDriverKind,
13 VcsDiscoveryItem,
14} from "@t3tools/contracts";
15import {
16 getBackgroundActivityBaseProfile,
17 getBackgroundActivityPresetSettings,
18 resolveServerBackgroundActivitySettings,
19} from "@t3tools/shared/backgroundActivitySettings";
20
21import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
22import { useSettingsScope } from "./SettingsScopeContext";
23import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
24import { cn } from "../../lib/utils";
25import { useEnvironmentQuery } from "../../state/query";
26import { sourceControlEnvironment } from "../../state/sourceControl";
27import { Badge } from "../ui/badge";
28import { Button } from "../ui/button";
29import { Collapsible, CollapsibleContent } from "../ui/collapsible";
30import {
31 Empty,
32 EmptyContent,
33 EmptyDescription,
34 EmptyHeader,
35 EmptyMedia,
36 EmptyTitle,
37} from "../ui/empty";
38import { Skeleton } from "../ui/skeleton";
39import {
40 NumberField,
41 NumberFieldDecrement,
42 NumberFieldGroup,
43 NumberFieldIncrement,
44 NumberFieldInput,
45} from "../ui/number-field";
46import { Switch } from "../ui/switch";
47import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
48
49import {
50 AzureDevOpsIcon,
51 BitbucketIcon,
52 GitHubIcon,
53 GitIcon,
54 GitLabIcon,
55 ForgejoIcon,
56 JujutsuIcon,
57 type Icon,
58} from "../Icons";
59import { RedactedSensitiveText } from "./RedactedSensitiveText";
60import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
61import {
62 PolicyTooltip,
63 SettingResetButton,
64 SettingsPageContainer,
65 SettingsSearchTarget,
66 SettingsSection,
67 useSettingsSearchTargetId,
68} from "./settingsLayout";
69import { searchableSetting } from "./settingsSearch";
70import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
71
72const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
73 versionControlSystems: [],
74 sourceControlProviders: [],
75};
76
77const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
78 github: GitHubIcon,
79 gitlab: GitLabIcon,
80 forgejo: ForgejoIcon,
81 "azure-devops": AzureDevOpsIcon,
82 bitbucket: BitbucketIcon,
83};
84
85const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
86 git: GitIcon,
87 jj: JujutsuIcon,
88};
89
90const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
91const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
92type BackgroundActivityOverridePatch = Partial<{
93 [K in keyof BackgroundActivitySettings["overrides"]]:
94 | BackgroundActivitySettings["overrides"][K]
95 | undefined;
96}>;
97
98function durationToSeconds(duration: Duration.Duration): number {
99 return Math.round(Duration.toMillis(duration) / 1_000);
100}
101
102function normalizeFetchIntervalSeconds(value: number | null): number {
103 if (value === null || !Number.isFinite(value)) {
104 return 0;
105 }
106 return Math.max(0, Math.round(value));
107}
108
109function backgroundActivityOverrideSettings(
110 current: BackgroundActivitySettings,
111 overrides: BackgroundActivityOverridePatch,
112) {
113 const nextOverrides: BackgroundActivityOverridePatch = {
114 ...current.overrides,
115 ...overrides,
116 };
117 for (const [key, value] of Object.entries(nextOverrides)) {
118 if (value === undefined) {
119 delete nextOverrides[key as keyof typeof nextOverrides];
120 }
121 }
122 return {
123 backgroundActivity: {
124 schemaVersion: 1 as const,
125 profile: "custom" as const,
126 baseProfile: getBackgroundActivityBaseProfile(current),
127 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
128 },
129 };
130}
131
132function optionLabel(value: Option.Option<string>): string | null {
133 return Option.getOrNull(value);
134}
135
136function isProviderDiscoveryItem(
137 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
138): item is SourceControlProviderDiscoveryItem {
139 return "auth" in item;
140}
141
142function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
143 return !isProviderDiscoveryItem(item) && !item.implemented;
144}
145
146function authPresentation(auth: SourceControlProviderAuth): {
147 readonly label: string;
148 readonly badge: "warning" | null;
149} {
150 if (auth.status === "authenticated") {
151 return { label: "Authenticated", badge: null };
152 }
153 if (auth.status === "unauthenticated") {
154 return { label: "Not authenticated", badge: "warning" };
155 }
156 return { label: "Status unknown", badge: null };
157}
158
159function RedactedAccount(props: { readonly account: string | null }) {
160 return (
161 <RedactedSensitiveText
162 value={props.account}
163 ariaLabel="Toggle source control account visibility"
164 revealTooltip="Click to reveal account"
165 hideTooltip="Click to hide account"
166 />
167 );
168}
169
170function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
171 if (isVcsNotReady(item)) return "bg-muted-foreground/35";
172 if (item.status !== "available") return "bg-warning";
173 if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning";
174 return "bg-success";
175}
176
177function SourceControlItemMark({
178 item,
179}: {
180 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
181}) {
182 const dotClassName = itemStatusDot(item);
183 const Icon = isProviderDiscoveryItem(item)
184 ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
185 : VCS_ICONS[item.kind];
186
187 if (!Icon) {
188 return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
189 }
190
191 return (
192 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
193 <Icon className="size-4.5 text-foreground/80" aria-hidden />
194 <span
195 className={cn(
196 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
197 dotClassName,
198 )}
199 aria-hidden
200 />
201 </span>
202 );
203}
204
205function itemSummary({
206 item,
207 auth,
208 authAccount,
209}: {
210 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
211 readonly auth: SourceControlProviderAuth | null;
212 readonly authAccount: string | null;
213}) {
214 if (isVcsNotReady(item)) {
215 return <span>Support for {item.label} is coming soon.</span>;
216 }
217
218 if (item.status !== "available") {
219 return <span>Not available on this server: {item.installHint}</span>;
220 }
221
222 if (auth) {
223 if (auth.status === "authenticated") {
224 return (
225 <>
226 <span>Authenticated</span>
227 {authAccount ? (
228 <>
229 <span aria-hidden>as</span>
230 <RedactedAccount account={authAccount} />
231 </>
232 ) : null}
233 </>
234 );
235 }
236
237 if (!item.executable) {
238 return <span>Available. {item.installHint}</span>;
239 }
240
241 if (auth.status === "unauthenticated") {
242 return (
243 <span>
244 {item.label} is not authenticated on this server. Sign in or configure credentials using
245 the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
246 tool on the server host to enable change request features.
247 </span>
248 );
249 }
250 const authDetail = optionLabel(auth.detail);
251 return (
252 <span>
253 Could not verify {item.label}. {authDetail ?? item.installHint}
254 </span>
255 );
256 }
257
258 return <span>Available</span>;
259}
260
261function DiscoveryItemRow({
262 item,
263 children,
264}: {
265 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
266 readonly children?: ReactNode;
267}) {
268 const version = optionLabel(item.version);
269 const enabled = isProviderDiscoveryItem(item)
270 ? item.status === "available" && item.auth.status === "authenticated"
271 : item.status === "available" && item.implemented;
272 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
273 const authStatus = auth ? authPresentation(auth) : null;
274 const authAccount = auth ? optionLabel(auth.account) : null;
275 const [isExpanded, setIsExpanded] = useState(false);
276 const hasDetails = children !== undefined;
277 const searchTargetId = useSettingsSearchTargetId();
278
279 useEffect(() => {
280 if (item.kind === "git" && searchTargetId === searchableSetting("git-fetch-interval").id) {
281 setIsExpanded(true);
282 }
283 }, [item.kind, searchTargetId]);
284
285 return (
286 <div
287 className={cn(
288 "first:rounded-t-xl last:rounded-b-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="icon-xs"
320 variant="ghost-muted"
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 = useScopedSettings();
350 const updateSettings = useUpdateScopedSettings();
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 const setting = searchableSetting("git-fetch-interval");
363
364 return (
365 <SettingsSearchTarget id={setting.id} 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">{setting.title}</span>
370 <PolicyTooltip>
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 </PolicyTooltip>
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 branches in the background. Set to 0 to avoid automatic Git prompts.
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 </SettingsSearchTarget>
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="first:rounded-t-xl last:rounded-b-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 id={searchableSetting("source-control").id} title="Server environment">
478 <Empty className="min-h-88">
479 <EmptyMedia variant="icon">
480 <PullRequestGlyph.pullRequest />
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 size="sm" variant="outline" onClick={onScan} disabled={isPending}>
494 <RefreshIcon className="size-3.5" refreshing={isPending} />
495 Scan
496 </Button>
497 </EmptyContent>
498 </Empty>
499 </SettingsSection>
500 );
501}
502
503export function SourceControlSettingsPanel() {
504 const { scope, environment, connectedEnvironments } = useSettingsScope();
505 // Discovery scans one machine's tools, so it shows the representative
506 // environment (named in the section title when several are selected);
507 // the settings rows above it fan out like everywhere else.
508 const environmentId =
509 environment?.connection.phase === "connected" ? environment.environmentId : null;
510 const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
511 const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
512 const discovery = useEnvironmentQuery(
513 environmentId === null
514 ? null
515 : sourceControlEnvironment.discovery({
516 environmentId,
517 input: {},
518 }),
519 );
520 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
521 const hasVersionControlSystems = result.versionControlSystems.length > 0;
522 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
523 const isInitialScanPending = discovery.isPending && discovery.data === null;
524 const handleScan = () => {
525 discovery.refresh();
526 };
527 const scanButton = (
528 <Tooltip>
529 <TooltipTrigger
530 render={
531 <Button
532 size="icon-xs"
533 variant="ghost-muted"
534 onClick={handleScan}
535 disabled={discovery.isPending}
536 aria-label="Rescan server environment"
537 >
538 <RefreshIcon refreshing={discovery.isPending} />
539 </Button>
540 }
541 />
542 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
543 </Tooltip>
544 );
545
546 return (
547 <SettingsPageContainer>
548 <ProjectDefaultsSettings category="source-control" />
549 {environmentId === null ? (
550 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
551 <p className="px-4 py-3 text-sm text-muted-foreground">
552 Connect an environment to inspect its version control tools and hosting integrations.
553 </p>
554 </SettingsSection>
555 ) : isInitialScanPending ? (
556 <>
557 <SourceControlSectionSkeleton
558 title={`Version Control${environmentSuffix}`}
559 headerAction={scanButton}
560 />
561 <SourceControlSectionSkeleton title="Source Control Providers" />
562 </>
563 ) : hasDiscoveryItems ? (
564 <>
565 {hasVersionControlSystems ? (
566 <SettingsSection
567 id={searchableSetting("source-control").id}
568 title={`Version Control${environmentSuffix}`}
569 headerAction={scanButton}
570 >
571 {result.versionControlSystems.map((item) => (
572 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
573 {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
574 </DiscoveryItemRow>
575 ))}
576 </SettingsSection>
577 ) : null}
578
579 {result.sourceControlProviders.length > 0 ? (
580 <SettingsSection
581 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
582 title={
583 hasVersionControlSystems
584 ? "Source Control Providers"
585 : `Source Control Providers${environmentSuffix}`
586 }
587 headerAction={hasVersionControlSystems ? null : scanButton}
588 >
589 {result.sourceControlProviders.map((item) => (
590 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
591 ))}
592 </SettingsSection>
593 ) : null}
594 </>
595 ) : (
596 <EmptySourceControlDiscovery
597 error={discovery.error}
598 isPending={discovery.isPending}
599 onScan={handleScan}
600 />
601 )}
602
603 <SourceControlWritingSettingsSection />
604 </SettingsPageContainer>
605 );
606}