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

SourceControlSettings.tsx

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