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 branch status in the background. Set this to 0 seconds if Git credentials
394 or security keys should only be prompted by explicit Git actions.
395 </p>
396 </div>
397 <div className="flex shrink-0 items-center gap-2">
398 <NumberField
399 value={automaticGitFetchIntervalSeconds}
400 min={0}
401 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
402 size="sm"
403 className="w-32"
404 onValueChange={(value) =>
405 updateSettings(
406 backgroundActivityOverrideSettings(settings.backgroundActivity, {
407 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
408 }),
409 )
410 }
411 >
412 <NumberFieldGroup>
413 <NumberFieldDecrement aria-label="Decrease fetch interval" />
414 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
415 <NumberFieldIncrement aria-label="Increase fetch interval" />
416 </NumberFieldGroup>
417 </NumberField>
418 <span className="text-xs text-muted-foreground">seconds</span>
419 </div>
420 </div>
421 </SettingsSearchTarget>
422 );
423}
424
425function SourceControlSectionSkeleton({
426 title,
427 headerAction,
428}: {
429 readonly title: string;
430 readonly headerAction?: ReactNode;
431}) {
432 return (
433 <SettingsSection title={title} headerAction={headerAction}>
434 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
435 <div key={row} className="rounded-xl px-3 py-3 sm:px-4">
436 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
437 <div className="min-w-0 flex-1 space-y-2">
438 <div className="flex items-center gap-2">
439 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
440 <Skeleton className="size-4.5 rounded-md" />
441 <Skeleton
442 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
443 aria-hidden
444 />
445 </span>
446 <Skeleton className="h-4 w-28 rounded-full" />
447 <Skeleton className="h-5 w-14 rounded-full" />
448 </div>
449 <Skeleton className="h-3 w-full max-w-xs rounded-full" />
450 </div>
451 <div className="flex shrink-0 items-center gap-2">
452 <Skeleton className="size-7 rounded-md" />
453 <Skeleton className="h-5 w-9 rounded-full" />
454 </div>
455 </div>
456 </div>
457 ))}
458 </SettingsSection>
459 );
460}
461
462function EmptySourceControlDiscovery({
463 error,
464 isPending,
465 onScan,
466}: {
467 readonly error: string | null;
468 readonly isPending: boolean;
469 readonly onScan: () => void;
470}) {
471 const hasError = error !== null;
472
473 return (
474 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
475 <Empty className="min-h-88">
476 <EmptyMedia variant="icon">
477 <GitPullRequestIcon />
478 </EmptyMedia>
479 <EmptyHeader>
480 <EmptyTitle>
481 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
482 </EmptyTitle>
483 <EmptyDescription>
484 {hasError
485 ? error
486 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
487 </EmptyDescription>
488 </EmptyHeader>
489 <EmptyContent>
490 <Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>
491 <RefreshCwIcon className={cn("size-3.5", isPending && "animate-spin")} />
492 Scan
493 </Button>
494 </EmptyContent>
495 </Empty>
496 </SettingsSection>
497 );
498}
499
500export function SourceControlSettingsPanel() {
501 const { environments } = useEnvironments();
502 const primaryEnvironment = usePrimaryEnvironment();
503 const fallbackEnvironment =
504 environments.find((environment) => environment.connection.phase === "connected") ??
505 environments[0] ??
506 null;
507 const environmentId =
508 primaryEnvironment?.environmentId ?? fallbackEnvironment?.environmentId ?? null;
509 const isPrimaryEnvironment = environmentId === primaryEnvironment?.environmentId;
510 const discovery = useEnvironmentQuery(
511 environmentId === null
512 ? null
513 : sourceControlEnvironment.discovery({
514 environmentId,
515 input: {},
516 }),
517 );
518 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
519 const hasVersionControlSystems = result.versionControlSystems.length > 0;
520 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
521 const isInitialScanPending = discovery.isPending && discovery.data === null;
522 const handleScan = () => {
523 discovery.refresh();
524 };
525 const scanButton = (
526 <Tooltip>
527 <TooltipTrigger
528 render={
529 <Button
530 size="icon-xs"
531 variant="ghost-muted"
532 onClick={handleScan}
533 disabled={discovery.isPending}
534 aria-label="Rescan server environment"
535 >
536 <RefreshCwIcon className={cn(discovery.isPending && "animate-spin")} />
537 </Button>
538 }
539 />
540 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
541 </Tooltip>
542 );
543
544 return (
545 <SettingsPageContainer>
546 <SharedSettingsMismatchAlert />
547 {isInitialScanPending ? (
548 <>
549 <SourceControlSectionSkeleton title="Version Control" headerAction={scanButton} />
550 <SourceControlSectionSkeleton title="Source Control Providers" />
551 </>
552 ) : hasDiscoveryItems ? (
553 <>
554 {hasVersionControlSystems ? (
555 <SettingsSection
556 id={searchableSetting("source-control").id}
557 title="Version Control"
558 headerAction={scanButton}
559 >
560 {result.versionControlSystems.map((item) => (
561 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
562 {item.kind === "git" && isPrimaryEnvironment ? (
563 <GitFetchIntervalSettings />
564 ) : undefined}
565 </DiscoveryItemRow>
566 ))}
567 </SettingsSection>
568 ) : null}
569
570 {result.sourceControlProviders.length > 0 ? (
571 <SettingsSection
572 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
573 title="Source Control Providers"
574 headerAction={hasVersionControlSystems ? null : scanButton}
575 >
576 {result.sourceControlProviders.map((item) => (
577 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
578 ))}
579 </SettingsSection>
580 ) : null}
581 </>
582 ) : (
583 <EmptySourceControlDiscovery
584 error={discovery.error}
585 isPending={discovery.isPending}
586 onScan={handleScan}
587 />
588 )}
589
590 {/* Its rows are serverScoped: without a primary they render inert with
591 an explanation, which beats disappearing. */}
592 <SourceControlWritingSettingsSection />
593 </SettingsPageContainer>
594 );
595}