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-2xs">{item.executable}</code> tool
246 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 text-foreground">{item.label}</span>
298 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
299 {isVcsNotReady(item) ? (
300 <Badge variant="warning" size="sm">
301 Coming Soon
302 </Badge>
303 ) : null}
304 {authStatus?.badge ? (
305 <Badge variant={authStatus.badge} size="sm">
306 {authStatus.label}
307 </Badge>
308 ) : null}
309 </div>
310 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs leading-normal text-muted-foreground/80">
311 {itemSummary({ item, auth, authAccount })}
312 </p>
313 </div>
314 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
315 {hasDetails ? (
316 <Button
317 size="icon-xs"
318 variant="ghost-muted"
319 onClick={() => setIsExpanded((open) => !open)}
320 aria-expanded={isExpanded}
321 aria-label={`Toggle ${item.label} details`}
322 >
323 <ChevronDownIcon
324 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
325 />
326 </Button>
327 ) : null}
328 {!isVcsNotReady(item) ? (
329 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
330 ) : null}
331 </div>
332 </div>
333 </div>
334
335 {hasDetails ? (
336 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
337 <CollapsibleContent>
338 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
339 </CollapsibleContent>
340 </Collapsible>
341 ) : null}
342 </div>
343 );
344}
345
346function GitFetchIntervalSettings() {
347 const settings = useScopedSettings();
348 const updateSettings = useUpdateScopedSettings();
349 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
350 const automaticGitFetchIntervalSeconds = durationToSeconds(
351 resolvedBackgroundActivity.automaticGitFetchInterval,
352 );
353 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
354 getBackgroundActivityPresetSettings(
355 getBackgroundActivityBaseProfile(settings.backgroundActivity),
356 ).automaticGitFetchInterval,
357 );
358 const canResetFetchInterval =
359 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
360 const setting = searchableSetting("git-fetch-interval");
361
362 return (
363 <SettingsSearchTarget id={setting.id} className="grid gap-3">
364 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
365 <div className="min-w-0 space-y-1">
366 <div className="flex min-w-0 items-center gap-1">
367 <span className="text-xs font-medium text-foreground">{setting.title}</span>
368 <PolicyTooltip>
369 This interval is configured for Git only. The shared Background activity policy still
370 decides whether Git refreshes may run when the timer fires. Custom intervals appear as
371 Advanced in General settings.
372 </PolicyTooltip>
373 <span
374 className={cn(
375 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
376 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
377 )}
378 aria-hidden={!canResetFetchInterval}
379 >
380 {canResetFetchInterval ? (
381 <SettingResetButton
382 label="fetch interval"
383 onClick={() =>
384 updateSettings(
385 backgroundActivityOverrideSettings(settings.backgroundActivity, {
386 automaticGitFetchInterval: undefined,
387 }),
388 )
389 }
390 />
391 ) : null}
392 </span>
393 </div>
394 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
395 Refresh remote branches in the background. Set to 0 to avoid automatic Git prompts.
396 </p>
397 </div>
398 <div className="flex shrink-0 items-center gap-2">
399 <NumberField
400 value={automaticGitFetchIntervalSeconds}
401 min={0}
402 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
403 size="sm"
404 className="w-32"
405 onValueChange={(value) =>
406 updateSettings(
407 backgroundActivityOverrideSettings(settings.backgroundActivity, {
408 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
409 }),
410 )
411 }
412 >
413 <NumberFieldGroup>
414 <NumberFieldDecrement aria-label="Decrease fetch interval" />
415 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
416 <NumberFieldIncrement aria-label="Increase fetch interval" />
417 </NumberFieldGroup>
418 </NumberField>
419 <span className="text-xs text-muted-foreground">seconds</span>
420 </div>
421 </div>
422 </SettingsSearchTarget>
423 );
424}
425
426function SourceControlSectionSkeleton({
427 title,
428 headerAction,
429}: {
430 readonly title: string;
431 readonly headerAction?: ReactNode;
432}) {
433 return (
434 <SettingsSection title={title} headerAction={headerAction}>
435 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
436 <div key={row} className="first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4">
437 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
438 <div className="min-w-0 flex-1 space-y-2">
439 <div className="flex items-center gap-2">
440 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
441 <Skeleton className="size-4.5" />
442 <Skeleton
443 shape="pill"
444 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2"
445 aria-hidden
446 />
447 </span>
448 <Skeleton shape="pill" className="h-4 w-28" />
449 <Skeleton shape="pill" className="h-5 w-14" />
450 </div>
451 <Skeleton shape="pill" className="h-3 w-full max-w-xs" />
452 </div>
453 <div className="flex shrink-0 items-center gap-2">
454 <Skeleton className="size-7" />
455 <Skeleton shape="pill" className="h-5 w-9" />
456 </div>
457 </div>
458 </div>
459 ))}
460 </SettingsSection>
461 );
462}
463
464function EmptySourceControlDiscovery({
465 error,
466 isPending,
467 onScan,
468}: {
469 readonly error: string | null;
470 readonly isPending: boolean;
471 readonly onScan: () => void;
472}) {
473 const hasError = error !== null;
474
475 return (
476 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
477 <Empty>
478 <EmptyMedia variant="icon">
479 <PullRequestGlyph.pullRequest />
480 </EmptyMedia>
481 <EmptyHeader>
482 <EmptyTitle>
483 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
484 </EmptyTitle>
485 <EmptyDescription>
486 {hasError
487 ? error
488 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
489 </EmptyDescription>
490 </EmptyHeader>
491 <EmptyContent>
492 <Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>
493 <RefreshIcon size="sm" refreshing={isPending} />
494 Scan
495 </Button>
496 </EmptyContent>
497 </Empty>
498 </SettingsSection>
499 );
500}
501
502export function SourceControlSettingsPanel() {
503 const { scope, environment, connectedEnvironments } = useSettingsScope();
504 // Discovery scans one machine's tools, so it shows the representative
505 // environment (named in the section title when several are selected);
506 // the settings rows above it fan out like everywhere else.
507 const environmentId =
508 environment?.connection.phase === "connected" ? environment.environmentId : null;
509 const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
510 const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
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 hasVersionControlSystems = result.versionControlSystems.length > 0;
521 const hasDiscoveryItems = hasVersionControlSystems || 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-muted"
533 onClick={handleScan}
534 disabled={discovery.isPending}
535 aria-label="Rescan server environment"
536 >
537 <RefreshIcon refreshing={discovery.isPending} />
538 </Button>
539 }
540 />
541 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
542 </Tooltip>
543 );
544
545 return (
546 <SettingsPageContainer>
547 <ProjectDefaultsSettings category="source-control" />
548 {environmentId === null ? (
549 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
550 <p className="px-4 py-3 text-sm text-muted-foreground">
551 Connect an environment to inspect its version control tools and hosting integrations.
552 </p>
553 </SettingsSection>
554 ) : isInitialScanPending ? (
555 <>
556 <SourceControlSectionSkeleton
557 title={`Version Control${environmentSuffix}`}
558 headerAction={scanButton}
559 />
560 <SourceControlSectionSkeleton title="Source Control Providers" />
561 </>
562 ) : hasDiscoveryItems ? (
563 <>
564 {hasVersionControlSystems ? (
565 <SettingsSection
566 id={searchableSetting("source-control").id}
567 title={`Version Control${environmentSuffix}`}
568 headerAction={scanButton}
569 >
570 {result.versionControlSystems.map((item) => (
571 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
572 {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
573 </DiscoveryItemRow>
574 ))}
575 </SettingsSection>
576 ) : null}
577
578 {result.sourceControlProviders.length > 0 ? (
579 <SettingsSection
580 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
581 title={
582 hasVersionControlSystems
583 ? "Source Control Providers"
584 : `Source Control Providers${environmentSuffix}`
585 }
586 headerAction={hasVersionControlSystems ? null : scanButton}
587 >
588 {result.sourceControlProviders.map((item) => (
589 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
590 ))}
591 </SettingsSection>
592 ) : null}
593 </>
594 ) : (
595 <EmptySourceControlDiscovery
596 error={discovery.error}
597 isPending={discovery.isPending}
598 onScan={handleScan}
599 />
600 )}
601
602 <SourceControlWritingSettingsSection />
603 </SettingsPageContainer>
604 );
605}