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