Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlSettings.tsx

656 lines23.0 KB

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 GitCafeIcon,
53 GitHubIcon,
54 GitIcon,
55 GitLabIcon,
56 ForgejoIcon,
57 JujutsuIcon,
58 type Icon,
59} from "../Icons";
60import { BitbucketCredentialsSettings } from "./BitbucketCredentialsSettings";
61import { GitHubAccountSettings } from "./GitHubAccountSettings";
62import { GitHubTokenSettings } from "./GitHubTokenSettings";
63import { RedactedSensitiveText } from "./RedactedSensitiveText";
64import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
65import {
66 PolicyTooltip,
67 SettingResetButton,
68 SettingsPageContainer,
69 SettingsSearchTarget,
70 SettingsSection,
71 useSettingsSearchTargetId,
72} from "./settingsLayout";
73import { searchableSetting } from "./settingsSearch";
74import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
75​
76const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
77 versionControlSystems: [],
78 sourceControlProviders: [],
79};
80​
81const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
82 github: GitHubIcon,
83 gitlab: GitLabIcon,
84 forgejo: ForgejoIcon,
85 "azure-devops": AzureDevOpsIcon,
86 bitbucket: BitbucketIcon,
87 gitcafe: GitCafeIcon,
88};
89​
90const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
91 git: GitIcon,
92 jj: JujutsuIcon,
93};
94​
95const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
96const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
97type BackgroundActivityOverridePatch = Partial<{
98 [K in keyof BackgroundActivitySettings["overrides"]]:
99 | BackgroundActivitySettings["overrides"][K]
100 | undefined;
101}>;
102​
103function durationToSeconds(duration: Duration.Duration): number {
104 return Math.round(Duration.toMillis(duration) / 1_000);
106​
107function normalizeFetchIntervalSeconds(value: number | null): number {
108 if (value === null || !Number.isFinite(value)) {
109 return 0;
110 }
111 return Math.max(0, Math.round(value));
113​
114function backgroundActivityOverrideSettings(
115 current: BackgroundActivitySettings,
116 overrides: BackgroundActivityOverridePatch,
117) {
118 const nextOverrides: BackgroundActivityOverridePatch = {
119 ...current.overrides,
120 ...overrides,
121 };
122 for (const [key, value] of Object.entries(nextOverrides)) {
123 if (value === undefined) {
124 delete nextOverrides[key as keyof typeof nextOverrides];
125 }
126 }
127 return {
128 backgroundActivity: {
129 schemaVersion: 1 as const,
130 profile: "custom" as const,
131 baseProfile: getBackgroundActivityBaseProfile(current),
132 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
133 },
134 };
136​
137function optionLabel(value: Option.Option<string>): string | null {
138 return Option.getOrNull(value);
140​
141function isProviderDiscoveryItem(
142 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
143): item is SourceControlProviderDiscoveryItem {
144 return "auth" in item;
146​
147function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
148 return !isProviderDiscoveryItem(item) && !item.implemented;
150​
151function authPresentation(auth: SourceControlProviderAuth): {
152 readonly label: string;
153 readonly badge: "warning" | null;
154} {
155 if (auth.status === "authenticated") {
156 return { label: "Authenticated", badge: null };
157 }
158 if (auth.status === "unauthenticated") {
159 return { label: "Not authenticated", badge: "warning" };
160 }
161 return { label: "Status unknown", badge: null };
163​
164function RedactedAccount(props: { readonly account: string | null }) {
165 return (
166 <RedactedSensitiveText
167 value={props.account}
168 ariaLabel="Toggle source control account visibility"
169 revealTooltip="Click to reveal account"
170 hideTooltip="Click to hide account"
171 />
172 );
174​
175function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
176 if (isVcsNotReady(item)) return "bg-muted-foreground/35";
177 if (item.status !== "available") return "bg-warning";
178 if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning";
179 return "bg-success";
181​
182function SourceControlItemMark({
183 item,
184}: {
185 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
186}) {
187 const dotClassName = itemStatusDot(item);
188 const Icon = isProviderDiscoveryItem(item)
189 ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
190 : VCS_ICONS[item.kind];
191​
192 if (!Icon) {
193 return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
194 }
195​
196 return (
197 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
198 <Icon className="size-4.5 text-foreground/80" aria-hidden />
199 <span
200 className={cn(
201 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
202 dotClassName,
203 )}
204 aria-hidden
205 />
206 </span>
207 );
209​
210function itemSummary({
211 item,
212 auth,
213 authAccount,
214}: {
215 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
216 readonly auth: SourceControlProviderAuth | null;
217 readonly authAccount: string | null;
218}) {
219 if (isVcsNotReady(item)) {
220 return <span>Support for {item.label} is coming soon.</span>;
221 }
222​
223 if (item.status !== "available") {
224 return <span>Not available on this server: {item.installHint}</span>;
225 }
226​
227 if (auth) {
228 if (auth.status === "authenticated") {
229 // The server names the account its requests use, Settings choice included, and
230 // says when an environment token overrides it.
231 const authDetail = optionLabel(auth.detail);
232 return (
233 <>
234 <span>Authenticated</span>
235 {authAccount ? (
236 <>
237 <span aria-hidden>as</span>
238 <RedactedAccount account={authAccount} />
239 </>
240 ) : null}
241 {authDetail ? <span>· {authDetail}</span> : null}
242 </>
243 );
244 }
245​
246 // API integrations have no CLI to sign in with; an unverified saved credential falls
247 // through to the "could not verify" detail instead of repeating the setup hint.
248 if (!item.executable && auth.status === "unauthenticated") {
249 return <span>Available. {item.installHint}</span>;
250 }
251​
252 // Signed in, but every login is turned off here: the fix is the switch below, not the CLI.
253 if (auth.status === "unauthenticated" && auth.accounts?.some((entry) => entry.authenticated)) {
254 return <span>{optionLabel(auth.detail) ?? `Every ${item.label} host is turned off.`}</span>;
255 }
256​
257 if (auth.status === "unauthenticated") {
258 return (
259 <span>
260 {item.label} is not authenticated on this server. Sign in or configure credentials using
261 the <code className="rounded bg-muted px-1 py-px text-2xs">{item.executable}</code> tool
262 on the server host to enable change request features.
263 </span>
264 );
265 }
266 const authDetail = optionLabel(auth.detail);
267 return (
268 <span>
269 Could not verify {item.label}. {authDetail ?? item.installHint}
270 </span>
271 );
272 }
273​
274 return <span>Available</span>;
276​
277function DiscoveryItemRow({
278 item,
279 children,
280}: {
281 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
282 readonly children?: ReactNode;
283}) {
284 const version = optionLabel(item.version);
285 const enabled = isProviderDiscoveryItem(item)
286 ? item.status === "available" && item.auth.status === "authenticated"
287 : item.status === "available" && item.implemented;
288 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
289 const authStatus = auth ? authPresentation(auth) : null;
290 const authAccount = auth ? optionLabel(auth.account) : null;
291 const [isExpanded, setIsExpanded] = useState(false);
292 const hasDetails = children !== undefined;
293 const searchTargetId = useSettingsSearchTargetId();
294​
295 useEffect(() => {
296 if (
297 (item.kind === "git" && searchTargetId === searchableSetting("git-fetch-interval").id) ||
298 (item.kind === "bitbucket" &&
299 searchTargetId === searchableSetting("bitbucket-credentials").id) ||
300 (item.kind === "github" && searchTargetId === searchableSetting("github-accounts").id)
301 ) {
302 setIsExpanded(true);
303 }
304 }, [item.kind, searchTargetId]);
305​
306 return (
307 <div
308 className={cn(
309 "first:rounded-t-xl last:rounded-b-xl transition-colors hover:bg-muted/20",
310 isVcsNotReady(item) && "opacity-80",
311 )}
312 >
313 <div className="px-3 py-3 sm:px-4">
314 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
315 <div className="min-w-0 flex-1 space-y-1">
316 <div className="flex min-w-0 flex-wrap items-center gap-2">
317 <SourceControlItemMark item={item} />
318 <span className="truncate text-sm font-medium text-foreground">{item.label}</span>
319 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
320 {isVcsNotReady(item) ? (
321 <Badge variant="warning" size="sm">
322 Coming Soon
323 </Badge>
324 ) : null}
325 {authStatus?.badge ? (
326 <Badge variant={authStatus.badge} size="sm">
327 {authStatus.label}
328 </Badge>
329 ) : null}
330 </div>
331 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs leading-normal text-muted-foreground/80">
332 {itemSummary({ item, auth, authAccount })}
333 </p>
334 </div>
335 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
336 {hasDetails ? (
337 <Button
338 size="icon-xs"
339 variant="ghost-muted"
340 onClick={() => setIsExpanded((open) => !open)}
341 aria-expanded={isExpanded}
342 aria-label={`Toggle ${item.label} details`}
343 >
344 <ChevronDownIcon
345 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
346 />
347 </Button>
348 ) : null}
349 {!isVcsNotReady(item) ? (
350 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
351 ) : null}
352 </div>
353 </div>
354 </div>
355​
356 {hasDetails ? (
357 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
358 <CollapsibleContent>
359 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
360 </CollapsibleContent>
361 </Collapsible>
362 ) : null}
363 </div>
364 );
366​
367function GitFetchIntervalSettings() {
368 const settings = useScopedSettings();
369 const updateSettings = useUpdateScopedSettings();
370 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
371 const automaticGitFetchIntervalSeconds = durationToSeconds(
372 resolvedBackgroundActivity.automaticGitFetchInterval,
373 );
374 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
375 getBackgroundActivityPresetSettings(
376 getBackgroundActivityBaseProfile(settings.backgroundActivity),
377 ).automaticGitFetchInterval,
378 );
379 const canResetFetchInterval =
380 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
381 const setting = searchableSetting("git-fetch-interval");
382​
383 return (
384 <SettingsSearchTarget id={setting.id} className="grid gap-3">
385 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
386 <div className="min-w-0 space-y-1">
387 <div className="flex min-w-0 items-center gap-1">
388 <span className="text-xs font-medium text-foreground">{setting.title}</span>
389 <PolicyTooltip>
390 This interval is configured for Git only. The shared Background activity policy still
391 decides whether Git refreshes may run when the timer fires. Custom intervals appear as
392 Advanced in General settings.
393 </PolicyTooltip>
394 <span
395 className={cn(
396 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
397 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
398 )}
399 aria-hidden={!canResetFetchInterval}
400 >
401 {canResetFetchInterval ? (
402 <SettingResetButton
403 label="fetch interval"
404 onClick={() =>
405 updateSettings(
406 backgroundActivityOverrideSettings(settings.backgroundActivity, {
407 automaticGitFetchInterval: undefined,
408 }),
409 )
410 }
411 />
412 ) : null}
413 </span>
414 </div>
415 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
416 Refresh remote branches in the background. Set to 0 to avoid automatic Git prompts.
417 </p>
418 </div>
419 <div className="flex shrink-0 items-center gap-2">
420 <NumberField
421 value={automaticGitFetchIntervalSeconds}
422 min={0}
423 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
424 size="sm"
425 className="w-32"
426 onValueChange={(value) =>
427 updateSettings(
428 backgroundActivityOverrideSettings(settings.backgroundActivity, {
429 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
430 }),
431 )
432 }
433 >
434 <NumberFieldGroup>
435 <NumberFieldDecrement aria-label="Decrease fetch interval" />
436 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
437 <NumberFieldIncrement aria-label="Increase fetch interval" />
438 </NumberFieldGroup>
439 </NumberField>
440 <span className="text-xs text-muted-foreground">seconds</span>
441 </div>
442 </div>
443 </SettingsSearchTarget>
444 );
446​
447function SourceControlSectionSkeleton({
448 title,
449 headerAction,
450}: {
451 readonly title: string;
452 readonly headerAction?: ReactNode;
453}) {
454 return (
455 <SettingsSection title={title} headerAction={headerAction}>
456 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
457 <div key={row} className="first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4">
458 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
459 <div className="min-w-0 flex-1 space-y-2">
460 <div className="flex items-center gap-2">
461 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
462 <Skeleton className="size-4.5" />
463 <Skeleton
464 shape="pill"
465 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2"
466 aria-hidden
467 />
468 </span>
469 <Skeleton shape="pill" className="h-4 w-28" />
470 <Skeleton shape="pill" className="h-5 w-14" />
471 </div>
472 <Skeleton shape="pill" className="h-3 w-full max-w-xs" />
473 </div>
474 <div className="flex shrink-0 items-center gap-2">
475 <Skeleton className="size-7" />
476 <Skeleton shape="pill" className="h-5 w-9" />
477 </div>
478 </div>
479 </div>
480 ))}
481 </SettingsSection>
482 );
484​
485function EmptySourceControlDiscovery({
486 error,
487 isPending,
488 onScan,
489}: {
490 readonly error: string | null;
491 readonly isPending: boolean;
492 readonly onScan: () => void;
493}) {
494 const hasError = error !== null;
495​
496 return (
497 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
498 <Empty>
499 <EmptyMedia variant="icon">
500 <PullRequestGlyph.pullRequest />
501 </EmptyMedia>
502 <EmptyHeader>
503 <EmptyTitle>
504 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
505 </EmptyTitle>
506 <EmptyDescription>
507 {hasError
508 ? error
509 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
510 </EmptyDescription>
511 </EmptyHeader>
512 <EmptyContent>
513 <Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>
514 <RefreshIcon size="sm" refreshing={isPending} />
515 Scan
516 </Button>
517 </EmptyContent>
518 </Empty>
519 </SettingsSection>
520 );
522​
523export function SourceControlSettingsPanel() {
524 const { scope, environment, connectedEnvironments } = useSettingsScope();
525 // Discovery scans one machine's tools, so it shows the representative
526 // environment (named in the section title when several are selected);
527 // the settings rows above it fan out like everywhere else.
528 const environmentId =
529 environment?.connection.phase === "connected" ? environment.environmentId : null;
530 const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
531 const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
532 const discovery = useEnvironmentQuery(
533 environmentId === null
534 ? null
535 : sourceControlEnvironment.discovery({
536 environmentId,
537 input: {},
538 }),
539 );
540 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
541 const hasVersionControlSystems = result.versionControlSystems.length > 0;
542 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
543 const isInitialScanPending = discovery.isPending && discovery.data === null;
544 const handleScan = () => {
545 discovery.refresh();
546 };
547 const scanButton = (
548 <Tooltip>
549 <TooltipTrigger
550 render={
551 <Button
552 size="icon-xs"
553 variant="ghost-muted"
554 onClick={handleScan}
555 disabled={discovery.isPending}
556 aria-label="Rescan server environment"
557 >
558 <RefreshIcon refreshing={discovery.isPending} />
559 </Button>
560 }
561 />
562 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
563 </Tooltip>
564 );
565​
566 return (
567 <SettingsPageContainer>
568 <ProjectDefaultsSettings category="source-control" />
569 {environmentId === null ? (
570 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
571 <p className="px-4 py-3 text-sm text-muted-foreground">
572 Connect an environment to inspect its version control tools and hosting integrations.
573 </p>
574 </SettingsSection>
575 ) : isInitialScanPending ? (
576 <>
577 <SourceControlSectionSkeleton
578 title={`Version Control${environmentSuffix}`}
579 headerAction={scanButton}
580 />
581 <SourceControlSectionSkeleton title="Source Control Providers" />
582 </>
583 ) : hasDiscoveryItems ? (
584 <>
585 {hasVersionControlSystems ? (
586 <SettingsSection
587 id={searchableSetting("source-control").id}
588 title={`Version Control${environmentSuffix}`}
589 headerAction={scanButton}
590 >
591 {result.versionControlSystems.map((item) => (
592 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
593 {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
594 </DiscoveryItemRow>
595 ))}
596 </SettingsSection>
597 ) : null}
598​
599 {result.sourceControlProviders.length > 0 ? (
600 <SettingsSection
601 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
602 title={
603 hasVersionControlSystems
604 ? "Source Control Providers"
605 : `Source Control Providers${environmentSuffix}`
606 }
607 headerAction={hasVersionControlSystems ? null : scanButton}
608 >
609 {result.sourceControlProviders.map((item) => (
610 <DiscoveryItemRow key={`provider:${item.kind}`} item={item}>
611 {item.kind === "bitbucket" ? (
612 <SettingsSearchTarget id={searchableSetting("bitbucket-credentials").id}>
613 <BitbucketCredentialsSettings
614 // Drafts belong to one environment; switching must not carry them over.
615 key={environmentId}
616 environmentId={environmentId}
617 onSaved={handleScan}
618 />
619 </SettingsSearchTarget>
620 ) : item.kind === "github" ? (
621 <SettingsSearchTarget id={searchableSetting("github-accounts").id}>
622 <div className="grid gap-6">
623 {/* Shown even without gh: a saved token is how GitHub works without the CLI. */}
624 <GitHubTokenSettings
625 key={`token-${environmentId}`}
626 environmentId={environmentId}
627 onSaved={handleScan}
628 />
629 {item.status === "available" ? (
630 <GitHubAccountSettings
631 key={environmentId}
632 environmentId={environmentId}
633 auth={item.auth}
634 onSaved={handleScan}
635 />
636 ) : null}
637 </div>
638 </SettingsSearchTarget>
639 ) : undefined}
640 </DiscoveryItemRow>
641 ))}
642 </SettingsSection>
643 ) : null}
644 </>
645 ) : (
646 <EmptySourceControlDiscovery
647 error={discovery.error}
648 isPending={discovery.isPending}
649 onScan={handleScan}
650 />
651 )}
652​
653 <SourceControlWritingSettingsSection />
654 </SettingsPageContainer>
655 );