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