Open History to see the last commit
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 { GitHubAccountSettings } from "./GitHubAccountSettings";
51import { GitHubTokenSettings } from "./GitHubTokenSettings";
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);
87}
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));
94}
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 };
117}
118
119function optionLabel(value: Option.Option<string>): string | null {
120 return Option.getOrNull(value);
121}
122
123function isProviderDiscoveryItem(
124 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
125): item is SourceControlProviderDiscoveryItem {
126 return "auth" in item;
127}
128
129function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
130 return !isProviderDiscoveryItem(item) && !item.implemented;
131}
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 };
144}
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 );
155}
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";
162}
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;
172}
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 );
198}
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>;
260}
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 (item.kind === "github" && searchTargetId === searchableSetting("github-accounts").id);
285 if (targetsThisRow && !isExpanded && seenSearchTargetId !== searchTargetId) {
286 setIsExpanded(true);
287 }
288 if (seenSearchTargetId !== searchTargetId) setSeenSearchTargetId(searchTargetId);
289
290 return (
291 <div
292 className={cn(
293 "first:rounded-t-xl last:rounded-b-xl transition-colors hover:bg-muted/20",
294 isVcsNotReady(item) && "opacity-80",
295 )}
296 >
297 <div className="px-3 py-3 sm:px-4">
298 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
299 <div className="min-w-0 flex-1 space-y-1">
300 <div className="flex min-w-0 flex-wrap items-center gap-2">
301 <SourceControlItemMark item={item} />
302 <span className="truncate text-sm font-medium text-foreground">{item.label}</span>
303 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
304 {isVcsNotReady(item) ? (
305 <Badge variant="warning" size="sm">
306 Coming Soon
307 </Badge>
308 ) : null}
309 {authStatus?.badge ? (
310 <Badge variant={authStatus.badge} size="sm">
311 {authStatus.label}
312 </Badge>
313 ) : null}
314 </div>
315 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs leading-normal text-muted-foreground/80">
316 {itemSummary({ item, auth, authAccount })}
317 </p>
318 </div>
319 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
320 {hasDetails ? (
321 <Button
322 size="icon-xs"
323 variant="ghost-muted"
324 onClick={() => setIsExpanded((open) => !open)}
325 aria-expanded={isExpanded}
326 aria-label={`Toggle ${item.label} details`}
327 >
328 <ChevronDownIcon
329 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
330 />
331 </Button>
332 ) : null}
333 {!isVcsNotReady(item) ? (
334 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
335 ) : null}
336 </div>
337 </div>
338 </div>
339
340 {hasDetails ? (
341 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
342 <CollapsibleContent>
343 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
344 </CollapsibleContent>
345 </Collapsible>
346 ) : null}
347 </div>
348 );
349}
350
351function GitFetchIntervalSettings() {
352 const settings = useScopedSettings();
353 const updateSettings = useUpdateScopedSettings();
354 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
355 const automaticGitFetchIntervalSeconds = durationToSeconds(
356 resolvedBackgroundActivity.automaticGitFetchInterval,
357 );
358 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
359 getBackgroundActivityPresetSettings(
360 getBackgroundActivityBaseProfile(settings.backgroundActivity),
361 ).automaticGitFetchInterval,
362 );
363 const canResetFetchInterval =
364 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
365 const setting = searchableSetting("git-fetch-interval");
366
367 return (
368 <SettingsSearchTarget id={setting.id} className="grid gap-3">
369 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
370 <div className="min-w-0 space-y-1">
371 <div className="flex min-w-0 items-center gap-1">
372 <span className="text-xs font-medium text-foreground">{setting.title}</span>
373 <PolicyTooltip>
374 This interval is configured for Git only. The shared Background activity policy still
375 decides whether Git refreshes may run when the timer fires. Custom intervals appear as
376 Advanced in General settings.
377 </PolicyTooltip>
378 <span
379 className={cn(
380 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
381 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
382 )}
383 aria-hidden={!canResetFetchInterval}
384 >
385 {canResetFetchInterval ? (
386 <SettingResetButton
387 label="fetch interval"
388 onClick={() =>
389 updateSettings(
390 backgroundActivityOverrideSettings(settings.backgroundActivity, {
391 automaticGitFetchInterval: undefined,
392 }),
393 )
394 }
395 />
396 ) : null}
397 </span>
398 </div>
399 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
400 Refresh remote branches in the background. Set to 0 to avoid automatic Git prompts.
401 </p>
402 </div>
403 <div className="flex shrink-0 items-center gap-2">
404 <NumberField
405 value={automaticGitFetchIntervalSeconds}
406 min={0}
407 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
408 size="sm"
409 className="w-32"
410 onValueChange={(value) =>
411 updateSettings(
412 backgroundActivityOverrideSettings(settings.backgroundActivity, {
413 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
414 }),
415 )
416 }
417 >
418 <NumberFieldGroup>
419 <NumberFieldDecrement aria-label="Decrease fetch interval" />
420 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
421 <NumberFieldIncrement aria-label="Increase fetch interval" />
422 </NumberFieldGroup>
423 </NumberField>
424 <span className="text-xs text-muted-foreground">seconds</span>
425 </div>
426 </div>
427 </SettingsSearchTarget>
428 );
429}
430
431function SourceControlSectionSkeleton({
432 title,
433 headerAction,
434}: {
435 readonly title: string;
436 readonly headerAction?: ReactNode;
437}) {
438 return (
439 <SettingsSection title={title} headerAction={headerAction}>
440 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
441 <div key={row} className="first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4">
442 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
443 <div className="min-w-0 flex-1 space-y-2">
444 <div className="flex items-center gap-2">
445 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
446 <Skeleton className="size-4.5" />
447 <Skeleton
448 shape="pill"
449 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2"
450 aria-hidden
451 />
452 </span>
453 <Skeleton shape="pill" className="h-4 w-28" />
454 <Skeleton shape="pill" className="h-5 w-14" />
455 </div>
456 <Skeleton shape="pill" className="h-3 w-full max-w-xs" />
457 </div>
458 <div className="flex shrink-0 items-center gap-2">
459 <Skeleton className="size-7" />
460 <Skeleton shape="pill" className="h-5 w-9" />
461 </div>
462 </div>
463 </div>
464 ))}
465 </SettingsSection>
466 );
467}
468
469function EmptySourceControlDiscovery({
470 error,
471 isPending,
472 onScan,
473}: {
474 readonly error: string | null;
475 readonly isPending: boolean;
476 readonly onScan: () => void;
477}) {
478 const hasError = error !== null;
479
480 return (
481 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
482 <Empty>
483 <EmptyMedia variant="icon">
484 <PullRequestGlyph.pullRequest />
485 </EmptyMedia>
486 <EmptyHeader>
487 <EmptyTitle>
488 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
489 </EmptyTitle>
490 <EmptyDescription>
491 {hasError
492 ? error
493 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
494 </EmptyDescription>
495 </EmptyHeader>
496 <EmptyContent>
497 <Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>
498 <RefreshIcon size="sm" refreshing={isPending} />
499 Scan
500 </Button>
501 </EmptyContent>
502 </Empty>
503 </SettingsSection>
504 );
505}
506
507export function SourceControlSettingsPanel() {
508 const { scope, environment, connectedEnvironments } = useSettingsScope();
509
510 const environmentId =
511 environment?.connection.phase === "connected" ? environment.environmentId : null;
512 const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
513 const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
514 const discovery = useEnvironmentQuery(
515 environmentId === null
516 ? null
517 : sourceControlEnvironment.discovery({
518 environmentId,
519 input: {},
520 }),
521 );
522 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
523 const hasVersionControlSystems = result.versionControlSystems.length > 0;
524 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
525 const isInitialScanPending = discovery.isPending && discovery.data === null;
526 const handleScan = () => {
527 discovery.refresh();
528 };
529 const hostSettingsPanel = (kind: string) => {
530 const definition = sourceControlClients.find(kind);
531 if (!definition?.settings || environmentId === null) return undefined;
532 return (
533 <SettingsSearchTarget id={sourceControlHostSettingsSearchId(kind)}>
534 <SourceControlHostSettings
535 // Drafts belong to one environment; switching must not carry them over.
536 key={environmentId}
537 environmentId={environmentId}
538 definition={{ ...definition, settings: definition.settings }}
539 onSaved={handleScan}
540 />
541 </SettingsSearchTarget>
542 );
543 };
544 const scanButton = (
545 <Tooltip>
546 <TooltipTrigger
547 render={
548 <Button
549 size="icon-xs"
550 variant="ghost-muted"
551 onClick={handleScan}
552 disabled={discovery.isPending}
553 aria-label="Rescan server environment"
554 >
555 <RefreshIcon refreshing={discovery.isPending} />
556 </Button>
557 }
558 />
559 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
560 </Tooltip>
561 );
562
563 return (
564 <SettingsPageContainer>
565 <ProjectDefaultsSettings category="source-control" />
566 {environmentId === null ? (
567 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
568 <p className="px-4 py-3 text-sm text-muted-foreground">
569 Connect an environment to inspect its version control tools and hosting integrations.
570 </p>
571 </SettingsSection>
572 ) : isInitialScanPending ? (
573 <>
574 <SourceControlSectionSkeleton
575 title={`Version Control${environmentSuffix}`}
576 headerAction={scanButton}
577 />
578 <SourceControlSectionSkeleton title="Source Control Providers" />
579 </>
580 ) : hasDiscoveryItems ? (
581 <>
582 {hasVersionControlSystems ? (
583 <SettingsSection
584 id={searchableSetting("source-control").id}
585 title={`Version Control${environmentSuffix}`}
586 headerAction={scanButton}
587 >
588 {result.versionControlSystems.map((item) => (
589 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
590 {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
591 </DiscoveryItemRow>
592 ))}
593 </SettingsSection>
594 ) : null}
595
596 {result.sourceControlProviders.length > 0 ? (
597 <SettingsSection
598 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
599 title={
600 hasVersionControlSystems
601 ? "Source Control Providers"
602 : `Source Control Providers${environmentSuffix}`
603 }
604 headerAction={hasVersionControlSystems ? null : scanButton}
605 >
606 {result.sourceControlProviders.map((item) => (
607 <DiscoveryItemRow key={`provider:${item.kind}`} item={item}>
608 {item.kind === "github" ? (
609 <SettingsSearchTarget id={searchableSetting("github-accounts").id}>
610 <div className="grid gap-6">
611 {}
612 <GitHubTokenSettings
613 key={`token-${environmentId}`}
614 environmentId={environmentId}
615 onSaved={handleScan}
616 />
617 {item.status === "available" ? (
618 <GitHubAccountSettings
619 key={environmentId}
620 environmentId={environmentId}
621 auth={item.auth}
622 onSaved={handleScan}
623 />
624 ) : null}
625 </div>
626 </SettingsSearchTarget>
627 ) : (
628 hostSettingsPanel(item.kind)
629 )}
630 </DiscoveryItemRow>
631 ))}
632 </SettingsSection>
633 ) : null}
634 </>
635 ) : (
636 <EmptySourceControlDiscovery
637 error={discovery.error}
638 isPending={discovery.isPending}
639 onScan={handleScan}
640 />
641 )}
642
643 <SourceControlWritingSettingsSection />
644 </SettingsPageContainer>
645 );
646}