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