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 return (
244 <span>
245 Could not verify {item.label}. {item.installHint}
246 </span>
247 );
248 }
249
250 return <span>Available</span>;
251}
252
253function DiscoveryItemRow({
254 item,
255 children,
256}: {
257 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
258 readonly children?: ReactNode;
259}) {
260 const version = optionLabel(item.version);
261 const enabled = isProviderDiscoveryItem(item)
262 ? item.status === "available" && item.auth.status === "authenticated"
263 : item.status === "available" && item.implemented;
264 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
265 const authStatus = auth ? authPresentation(auth) : null;
266 const authAccount = auth ? optionLabel(auth.account) : null;
267 const [isExpanded, setIsExpanded] = useState(false);
268 const hasDetails = children !== undefined;
269
270 return (
271 <div
272 className={cn(
273 "rounded-xl transition-colors hover:bg-muted/20",
274 isVcsNotReady(item) && "opacity-80",
275 )}
276 >
277 <div className="px-3 py-3 sm:px-4">
278 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
279 <div className="min-w-0 flex-1 space-y-1">
280 <div className="flex min-w-0 flex-wrap items-center gap-2">
281 <SourceControlItemMark item={item} />
282 <span className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
283 {item.label}
284 </span>
285 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
286 {isVcsNotReady(item) ? (
287 <Badge variant="warning" size="sm">
288 Coming Soon
289 </Badge>
290 ) : null}
291 {authStatus?.badge ? (
292 <Badge variant={authStatus.badge} size="sm">
293 {authStatus.label}
294 </Badge>
295 ) : null}
296 </div>
297 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-[13px] leading-[1.45] text-muted-foreground/80">
298 {itemSummary({ item, auth, authAccount })}
299 </p>
300 </div>
301 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
302 {hasDetails ? (
303 <Button
304 size="compact"
305 variant="ghost-muted"
306 onClick={() => setIsExpanded((open) => !open)}
307 aria-expanded={isExpanded}
308 aria-label={`Toggle ${item.label} details`}
309 >
310 <ChevronDownIcon
311 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
312 />
313 </Button>
314 ) : null}
315 {!isVcsNotReady(item) ? (
316 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
317 ) : null}
318 </div>
319 </div>
320 </div>
321
322 {hasDetails ? (
323 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
324 <CollapsibleContent>
325 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
326 </CollapsibleContent>
327 </Collapsible>
328 ) : null}
329 </div>
330 );
331}
332
333function GitFetchIntervalSettings() {
334 const settings = usePrimarySettings();
335 const updateSettings = useUpdatePrimarySettings();
336 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
337 const automaticGitFetchIntervalSeconds = durationToSeconds(
338 resolvedBackgroundActivity.automaticGitFetchInterval,
339 );
340 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
341 getBackgroundActivityPresetSettings(
342 getBackgroundActivityBaseProfile(settings.backgroundActivity),
343 ).automaticGitFetchInterval,
344 );
345 const canResetFetchInterval =
346 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
347
348 return (
349 <div className="grid gap-3">
350 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
351 <div className="min-w-0 space-y-1">
352 <div className="flex min-w-0 items-center gap-1">
353 <span className="text-xs font-medium text-foreground">Fetch interval</span>
354 <PolicyTooltip>
355 This interval is configured for Git only. The shared Background activity policy still
356 decides whether Git refreshes may run when the timer fires. Custom intervals appear as
357 Advanced in General settings.
358 </PolicyTooltip>
359 <span
360 className={cn(
361 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
362 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
363 )}
364 aria-hidden={!canResetFetchInterval}
365 >
366 {canResetFetchInterval ? (
367 <SettingResetButton
368 label="fetch interval"
369 onClick={() =>
370 updateSettings(
371 backgroundActivityOverrideSettings(settings.backgroundActivity, {
372 automaticGitFetchInterval: undefined,
373 }),
374 )
375 }
376 />
377 ) : null}
378 </span>
379 </div>
380 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
381 Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
382 or security keys should only be prompted by explicit Git actions.
383 </p>
384 </div>
385 <div className="flex shrink-0 items-center gap-2">
386 <NumberField
387 value={automaticGitFetchIntervalSeconds}
388 min={0}
389 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
390 size="sm"
391 className="w-32"
392 onValueChange={(value) =>
393 updateSettings(
394 backgroundActivityOverrideSettings(settings.backgroundActivity, {
395 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
396 }),
397 )
398 }
399 >
400 <NumberFieldGroup>
401 <NumberFieldDecrement aria-label="Decrease fetch interval" />
402 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
403 <NumberFieldIncrement aria-label="Increase fetch interval" />
404 </NumberFieldGroup>
405 </NumberField>
406 <span className="text-xs text-muted-foreground">seconds</span>
407 </div>
408 </div>
409 </div>
410 );
411}
412
413function SourceControlSectionSkeleton({
414 title,
415 headerAction,
416}: {
417 readonly title: string;
418 readonly headerAction?: ReactNode;
419}) {
420 return (
421 <SettingsSection title={title} headerAction={headerAction}>
422 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
423 <div key={row} className="rounded-xl px-3 py-3 sm:px-4">
424 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
425 <div className="min-w-0 flex-1 space-y-2">
426 <div className="flex items-center gap-2">
427 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
428 <Skeleton className="size-4.5 rounded-md" />
429 <Skeleton
430 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
431 aria-hidden
432 />
433 </span>
434 <Skeleton className="h-4 w-28 rounded-full" />
435 <Skeleton className="h-5 w-14 rounded-full" />
436 </div>
437 <Skeleton className="h-3 w-full max-w-xs rounded-full" />
438 </div>
439 <div className="flex shrink-0 items-center gap-2">
440 <Skeleton className="size-7 rounded-md" />
441 <Skeleton className="h-5 w-9 rounded-full" />
442 </div>
443 </div>
444 </div>
445 ))}
446 </SettingsSection>
447 );
448}
449
450function EmptySourceControlDiscovery({
451 error,
452 isPending,
453 onScan,
454}: {
455 readonly error: string | null;
456 readonly isPending: boolean;
457 readonly onScan: () => void;
458}) {
459 const hasError = error !== null;
460
461 return (
462 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
463 <Empty className="min-h-88">
464 <EmptyMedia variant="icon">
465 <GitPullRequestIcon />
466 </EmptyMedia>
467 <EmptyHeader>
468 <EmptyTitle>
469 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
470 </EmptyTitle>
471 <EmptyDescription>
472 {hasError
473 ? error
474 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
475 </EmptyDescription>
476 </EmptyHeader>
477 <EmptyContent>
478 <Button
479 size="sm"
480 variant="outline"
481 className="h-8 gap-1.5 px-3 text-xs"
482 onClick={onScan}
483 disabled={isPending}
484 >
485 <RefreshCwIcon className={cn("size-3.5", isPending && "animate-spin")} />
486 Scan
487 </Button>
488 </EmptyContent>
489 </Empty>
490 </SettingsSection>
491 );
492}
493
494export function SourceControlSettingsPanel() {
495 const { environments } = useEnvironments();
496 const primaryEnvironment = usePrimaryEnvironment();
497 const fallbackEnvironment =
498 environments.find((environment) => environment.connection.phase === "connected") ??
499 environments[0] ??
500 null;
501 const environmentId =
502 primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
503 const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
504 const discovery = useEnvironmentQuery(
505 environmentId === null
506 ? null
507 : sourceControlEnvironment.discovery({
508 environmentId,
509 input: {},
510 }),
511 );
512 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
513 const hasVersionControlSystems = result.versionControlSystems.length > 0;
514 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
515 const isInitialScanPending = discovery.isPending && discovery.data === null;
516 const handleScan = () => {
517 discovery.refresh();
518 };
519 const scanButton = (
520 <Tooltip>
521 <TooltipTrigger
522 render={
523 <Button
524 size="icon-micro"
525 variant="ghost-muted"
526 onClick={handleScan}
527 disabled={discovery.isPending}
528 aria-label="Rescan server environment"
529 >
530 <RefreshCwIcon className={cn("size-3", discovery.isPending && "animate-spin")} />
531 </Button>
532 }
533 />
534 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
535 </Tooltip>
536 );
537
538 return (
539 <SettingsPageContainer>
540 {isInitialScanPending ? (
541 <>
542 <SourceControlSectionSkeleton title="Version Control" headerAction={scanButton} />
543 <SourceControlSectionSkeleton title="Source Control Providers" />
544 </>
545 ) : hasDiscoveryItems ? (
546 <>
547 {hasVersionControlSystems ? (
548 <SettingsSection
549 id={searchableSetting("source-control").id}
550 title="Version Control"
551 headerAction={scanButton}
552 >
553 {result.versionControlSystems.map((item) => (
554 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
555 {item.kind === "git" && isPrimaryEnvironment ? (
556 <GitFetchIntervalSettings />
557 ) : undefined}
558 </DiscoveryItemRow>
559 ))}
560 </SettingsSection>
561 ) : null}
562
563 {result.sourceControlProviders.length > 0 ? (
564 <SettingsSection
565 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
566 title="Source Control Providers"
567 headerAction={hasVersionControlSystems ? null : scanButton}
568 >
569 {result.sourceControlProviders.map((item) => (
570 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
571 ))}
572 </SettingsSection>
573 ) : null}
574 </>
575 ) : (
576 <EmptySourceControlDiscovery
577 error={discovery.error}
578 isPending={discovery.isPending}
579 onScan={handleScan}
580 />
581 )}
582
583 {isPrimaryEnvironment ? <SourceControlWritingSettingsSection /> : null}
584 </SettingsPageContainer>
585 );
586}