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

SourceControlSettings.tsx

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