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

SourceControlSettings.tsx

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