Open History to see the last commit
1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { ChevronDownIcon } from "lucide-react";
3import { useAtomValue } from "@effect/atom-react";
4import * as Option from "effect/Option";
5import { useState, type ReactNode } from "react";
6import type {
7 SourceControlDiscoveryResult,
8 SourceControlProviderAuth,
9 SourceControlProviderDiscoveryItem,
10 VcsDriverKind,
11 VcsDiscoveryItem,
12} from "@t3tools/contracts";
13import { useSettingsScope } from "./SettingsScopeContext";
14import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
15import { useLiveRefresh } from "../../hooks/useLiveRefresh";
16import { cn } from "../../lib/utils";
17import { useEnvironmentQuery } from "../../state/query";
18import { serverEnvironment } from "../../state/server";
19import { sourceControlEnvironment } from "../../state/sourceControl";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { Badge } from "../ui/badge";
22import { Button } from "../ui/button";
23import { Collapsible, CollapsibleContent } from "../ui/collapsible";
24import {
25 Empty,
26 EmptyContent,
27 EmptyDescription,
28 EmptyHeader,
29 EmptyMedia,
30 EmptyTitle,
31} from "../ui/empty";
32import { Skeleton } from "../ui/skeleton";
33import { Switch } from "../ui/switch";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35
36import { GitIcon, JujutsuIcon, type Icon } from "../Icons";
37import { SourceControlHostSettings } from "./SourceControlHostSettings";
38import { SourceControlAccountSettings } from "./SourceControlAccountSettings";
39import { SourceControlAppSignInSettings } from "./SourceControlAppSignInSettings";
40import { SourceControlTokenSettings } from "./SourceControlTokenSettings";
41import { RedactedSensitiveText } from "./RedactedSensitiveText";
42import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
43import {
44 SettingsPageContainer,
45 SettingsSearchTarget,
46 SettingsSection,
47 useSettingsSearchTargetId,
48} from "./settingsLayout";
49import { searchableSetting, sourceControlHostSettingsSearchId } from "./settingsSearch";
50import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
51import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects";
52import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
53import { sourceControlIcon } from "~/sourceControlPresentation";
54
55const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
56 versionControlSystems: [],
57 sourceControlProviders: [],
58};
59
60const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
61 git: GitIcon,
62 jj: JujutsuIcon,
63};
64
65const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
66function optionLabel(value: Option.Option<string>): string | null {
67 return Option.getOrNull(value);
68}
69
70function isProviderDiscoveryItem(
71 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
72): item is SourceControlProviderDiscoveryItem {
73 return "auth" in item;
74}
75
76function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
77 return !isProviderDiscoveryItem(item) && !item.implemented;
78}
79
80function authPresentation(auth: SourceControlProviderAuth): {
81 readonly label: string;
82 readonly badge: "secondary" | null;
83} {
84 if (auth.status === "authenticated") {
85 return { label: "Authenticated", badge: null };
86 }
87 if (auth.status === "unauthenticated") {
88 return { label: "Not authenticated", badge: "secondary" };
89 }
90 return { label: "Status unknown", badge: null };
91}
92
93function RedactedAccount(props: { readonly account: string | null }) {
94 return (
95 <RedactedSensitiveText
96 value={props.account}
97 ariaLabel="Toggle source control account visibility"
98 revealTooltip="Click to reveal account"
99 hideTooltip="Click to hide account"
100 />
101 );
102}
103
104function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
105 if (isVcsNotReady(item)) return "bg-muted-foreground/35";
106 if (isProviderDiscoveryItem(item)) {
107 return item.status === "available" && item.auth.status === "authenticated"
108 ? "bg-success"
109 : "bg-muted-foreground/35";
110 }
111 if (item.status !== "available") return "bg-warning";
112 return "bg-success";
113}
114
115function sourceControlItemIcon(
116 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
117): ReactNode {
118 const host = isProviderDiscoveryItem(item) ? sourceControlClients.find(item.kind) : undefined;
119 const Icon = isProviderDiscoveryItem(item)
120 ? host && sourceControlIcon(host)
121 : VCS_ICONS[item.kind];
122 return Icon ? <Icon className="size-4.5 text-foreground/80" aria-hidden /> : null;
123}
124
125function SourceControlItemMark({
126 item,
127}: {
128 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
129}) {
130 const dotClassName = itemStatusDot(item);
131 const icon = sourceControlItemIcon(item);
132
133 if (!icon) {
134 return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
135 }
136
137 return (
138 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
139 {icon}
140 <span
141 className={cn(
142 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
143 dotClassName,
144 )}
145 aria-hidden
146 />
147 </span>
148 );
149}
150
151function itemSummary({
152 item,
153 auth,
154 authAccount,
155}: {
156 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
157 readonly auth: SourceControlProviderAuth | null;
158 readonly authAccount: string | null;
159}) {
160 if (isVcsNotReady(item)) {
161 return <span>Support for {item.label} is coming soon.</span>;
162 }
163
164 if (item.status !== "available") {
165 return <span>Not available on this server: {item.installHint}</span>;
166 }
167
168 if (auth) {
169 if (auth.status === "authenticated") {
170 const authDetail = optionLabel(auth.detail);
171 return (
172 <>
173 <span>Authenticated</span>
174 {authAccount ? (
175 <>
176 <span aria-hidden>as</span>
177 <RedactedAccount account={authAccount} />
178 </>
179 ) : null}
180 {authDetail ? <span>· {authDetail}</span> : null}
181 </>
182 );
183 }
184
185 if (!item.executable && auth.status === "unauthenticated") {
186 return <span>Available. {item.installHint}</span>;
187 }
188
189 if (auth.status === "unauthenticated" && auth.accounts?.some((entry) => entry.authenticated)) {
190 return <span>{optionLabel(auth.detail) ?? `Every ${item.label} host is turned off.`}</span>;
191 }
192
193 if (auth.status === "unauthenticated") {
194 return (
195 <span>
196 {item.label} is not authenticated on this server. Sign in or configure credentials using
197 the <code className="rounded bg-muted px-1 py-px text-2xs">{item.executable}</code> tool
198 on the server host to enable change request features.
199 </span>
200 );
201 }
202 const authDetail = optionLabel(auth.detail);
203 return (
204 <span>
205 Could not verify {item.label}. {authDetail ?? item.installHint}
206 </span>
207 );
208 }
209
210 return <span>Available</span>;
211}
212
213function DiscoveryItemRow({
214 item,
215 offered,
216 children,
217}: {
218 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
219 /** A provider's switch chooses whether the project pickers offer it; a VCS switch only reports. */
220 readonly offered?: {
221 readonly checked: boolean;
222 readonly disabled: boolean;
223 readonly onChange: (checked: boolean) => void;
224 };
225 readonly children?: ReactNode;
226}) {
227 const version = optionLabel(item.version);
228 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
229 const authStatus = auth ? authPresentation(auth) : null;
230 const authAccount = auth ? optionLabel(auth.account) : null;
231 const [isExpanded, setIsExpanded] = useState(false);
232 const hasDetails = children !== undefined;
233 const searchTargetId = useSettingsSearchTargetId();
234 const [seenSearchTargetId, setSeenSearchTargetId] = useState<string | null>(null);
235 const targetsThisRow = searchTargetId === sourceControlHostSettingsSearchId(item.kind);
236 if (targetsThisRow && !isExpanded && seenSearchTargetId !== searchTargetId) {
237 setIsExpanded(true);
238 }
239 if (seenSearchTargetId !== searchTargetId) setSeenSearchTargetId(searchTargetId);
240
241 return (
242 <div
243 className={cn(
244 "first:rounded-t-xl last:rounded-b-xl transition-colors hover:bg-muted/20",
245 isVcsNotReady(item) && "opacity-80",
246 )}
247 >
248 <div className="px-3 py-3 sm:px-4">
249 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
250 <div className="min-w-0 flex-1 space-y-1">
251 <div className="flex min-w-0 flex-wrap items-center gap-2">
252 <SourceControlItemMark item={item} />
253 <span className="truncate text-sm font-medium text-foreground">{item.label}</span>
254 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
255 {isVcsNotReady(item) ? (
256 <Badge variant="warning" size="sm">
257 Coming Soon
258 </Badge>
259 ) : null}
260 {authStatus?.badge ? (
261 <Badge variant={authStatus.badge} size="sm">
262 {authStatus.label}
263 </Badge>
264 ) : null}
265 </div>
266 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs leading-normal text-muted-foreground/80">
267 {itemSummary({ item, auth, authAccount })}
268 </p>
269 </div>
270 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
271 {hasDetails ? (
272 <Button
273 size="icon-xs"
274 variant="ghost-muted"
275 onClick={() => setIsExpanded((open) => !open)}
276 aria-expanded={isExpanded}
277 aria-label={`Toggle ${item.label} details`}
278 >
279 <ChevronDownIcon
280 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
281 />
282 </Button>
283 ) : null}
284 {offered ? (
285 <Tooltip>
286 <TooltipTrigger
287 render={
288 <Switch
289 checked={offered.checked}
290 disabled={offered.disabled}
291 onCheckedChange={offered.onChange}
292 aria-label={`Offer ${item.label} when adding or publishing a project`}
293 />
294 }
295 />
296 <TooltipPopup side="top">Offer when adding or publishing a project</TooltipPopup>
297 </Tooltip>
298 ) : !isVcsNotReady(item) ? (
299 <Switch
300 checked={item.status === "available"}
301 disabled
302 aria-label={`${item.label} availability`}
303 />
304 ) : null}
305 </div>
306 </div>
307 </div>
308
309 {hasDetails ? (
310 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
311 <CollapsibleContent>
312 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
313 </CollapsibleContent>
314 </Collapsible>
315 ) : null}
316 </div>
317 );
318}
319
320function SourceControlSectionSkeleton({
321 title,
322 headerAction,
323}: {
324 readonly title: string;
325 readonly headerAction?: ReactNode;
326}) {
327 return (
328 <SettingsSection title={title} headerAction={headerAction}>
329 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
330 <div key={row} className="first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4">
331 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
332 <div className="min-w-0 flex-1 space-y-2">
333 <div className="flex items-center gap-2">
334 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
335 <Skeleton className="size-4.5" />
336 <Skeleton
337 shape="pill"
338 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2"
339 aria-hidden
340 />
341 </span>
342 <Skeleton shape="pill" className="h-4 w-28" />
343 <Skeleton shape="pill" className="h-5 w-14" />
344 </div>
345 <Skeleton shape="pill" className="h-3 w-full max-w-xs" />
346 </div>
347 <div className="flex shrink-0 items-center gap-2">
348 <Skeleton className="size-7" />
349 <Skeleton shape="pill" className="h-5 w-9" />
350 </div>
351 </div>
352 </div>
353 ))}
354 </SettingsSection>
355 );
356}
357
358function EmptySourceControlDiscovery({
359 error,
360 isPending,
361 onScan,
362}: {
363 readonly error: string | null;
364 readonly isPending: boolean;
365 readonly onScan: () => void;
366}) {
367 const hasError = error !== null;
368
369 return (
370 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
371 <Empty>
372 <EmptyMedia variant="icon">
373 <PullRequestGlyph.pullRequest />
374 </EmptyMedia>
375 <EmptyHeader>
376 <EmptyTitle>
377 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
378 </EmptyTitle>
379 <EmptyDescription>
380 {hasError
381 ? error
382 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
383 </EmptyDescription>
384 </EmptyHeader>
385 <EmptyContent>
386 <Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>
387 <RefreshIcon size="sm" refreshing={isPending} />
388 Scan
389 </Button>
390 </EmptyContent>
391 </Empty>
392 </SettingsSection>
393 );
394}
395
396export function SourceControlSettingsPanel() {
397 const { scope, environment, connectedEnvironments } = useSettingsScope();
398
399 const environmentId =
400 environment?.connection.phase === "connected" ? environment.environmentId : null;
401 const aggregate = scope.environmentIds.length !== 1 && connectedEnvironments.length > 1;
402 const environmentSuffix = aggregate && environment ? ` · ${environment.label}` : "";
403 const discovery = useEnvironmentQuery(
404 environmentId === null
405 ? null
406 : sourceControlEnvironment.discovery({
407 environmentId,
408 input: {},
409 }),
410 );
411 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
412 const hasVersionControlSystems = result.versionControlSystems.length > 0;
413 const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
414 const isInitialScanPending = discovery.isPending && discovery.data === null;
415 const handleScan = () => {
416 discovery.refresh();
417 };
418 // A CLI login on the server host changes nothing the client reads, so returning to the window
419 // asks again. Discovery runs every hosting CLI, too costly for a timer nobody asked for.
420 useLiveRefresh(
421 () => {
422 if (!discovery.isPending) discovery.refresh();
423 },
424 {
425 enabled: environmentId !== null,
426 key: `source-control-discovery:${environmentId}`,
427 intervalMs: null,
428 },
429 );
430 const offeredProviders = environment?.serverConfig?.settings.offeredSourceControlProviders;
431 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
432 label: "save source control providers",
433 });
434 const canUpdateSettings = useAtomValue(
435 serverEnvironment.updateSettings.permissionAtom(environmentId),
436 );
437 const hostSettingsPanel = (item: SourceControlProviderDiscoveryItem) => {
438 const definition = sourceControlClients.find(item.kind);
439 if (!definition?.settings || environmentId === null) return undefined;
440 const { credentials } = definition;
441 if (credentials) {
442 return (
443 <SettingsSearchTarget id={sourceControlHostSettingsSearchId(item.kind)}>
444 <div className="grid gap-6">
445 {credentials.appSignIn && item.appSignIn === true ? (
446 <SourceControlAppSignInSettings
447 key={`sign-in-${environmentId}`}
448 environmentId={environmentId}
449 definition={definition}
450 appSignIn={credentials.appSignIn}
451 account={Option.getOrNull(item.auth.account)}
452 onChanged={handleScan}
453 />
454 ) : null}
455 {credentials.appSignIn && item.appSignIn === true ? (
456 <div className="flex items-center gap-3 text-2xs text-muted-foreground">
457 <span aria-hidden className="h-px flex-1 bg-border" />
458 Or use your own credentials
459 <span aria-hidden className="h-px flex-1 bg-border" />
460 </div>
461 ) : null}
462 <SourceControlTokenSettings
463 key={`token-${environmentId}`}
464 environmentId={environmentId}
465 definition={definition}
466 credentials={credentials}
467 onSaved={handleScan}
468 />
469 {item.status === "available" ? (
470 <SourceControlAccountSettings
471 key={environmentId}
472 environmentId={environmentId}
473 definition={definition}
474 credentials={credentials}
475 auth={item.auth}
476 onSaved={handleScan}
477 />
478 ) : null}
479 </div>
480 </SettingsSearchTarget>
481 );
482 }
483 return (
484 <SettingsSearchTarget id={sourceControlHostSettingsSearchId(item.kind)}>
485 <SourceControlHostSettings
486 key={environmentId}
487 environmentId={environmentId}
488 definition={{ ...definition, settings: definition.settings }}
489 onSaved={handleScan}
490 />
491 </SettingsSearchTarget>
492 );
493 };
494 const scanButton = (
495 <Tooltip>
496 <TooltipTrigger
497 render={
498 <Button
499 size="icon-xs"
500 variant="ghost-muted"
501 onClick={handleScan}
502 disabled={discovery.isPending}
503 aria-label="Rescan server environment"
504 >
505 <RefreshIcon refreshing={discovery.isPending} />
506 </Button>
507 }
508 />
509 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
510 </Tooltip>
511 );
512
513 return (
514 <SettingsPageContainer>
515 <ProjectDefaultsSettings category="source-control" />
516 {environmentId === null ? (
517 <SettingsSection id={searchableSetting("source-control").id} title="Server environment">
518 <p className="px-4 py-3 text-sm text-muted-foreground">
519 Connect an environment to inspect its version control tools and hosting integrations.
520 </p>
521 </SettingsSection>
522 ) : isInitialScanPending ? (
523 <>
524 <SourceControlSectionSkeleton
525 title={`Version Control${environmentSuffix}`}
526 headerAction={scanButton}
527 />
528 <SourceControlSectionSkeleton title="Source control providers" />
529 </>
530 ) : hasDiscoveryItems ? (
531 <>
532 {hasVersionControlSystems ? (
533 <SettingsSection
534 id={searchableSetting("source-control").id}
535 title={`Version Control${environmentSuffix}`}
536 headerAction={scanButton}
537 >
538 {result.versionControlSystems.map((item) => (
539 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item} />
540 ))}
541 </SettingsSection>
542 ) : null}
543
544 {result.sourceControlProviders.length > 0 ? (
545 <SettingsSection
546 id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
547 title={
548 hasVersionControlSystems
549 ? "Source control providers"
550 : `Source control providers${environmentSuffix}`
551 }
552 headerAction={hasVersionControlSystems ? null : scanButton}
553 >
554 {result.sourceControlProviders.map((item) => (
555 <DiscoveryItemRow
556 key={`provider:${item.kind}`}
557 item={item}
558 offered={{
559 checked: isSourceControlProviderOffered(offeredProviders, item.kind),
560 disabled: !canUpdateSettings,
561 onChange: (checked) =>
562 void updateSettings({
563 environmentId,
564 input: {
565 patch: { offeredSourceControlProviders: { [item.kind]: checked } },
566 },
567 }),
568 }}
569 >
570 {hostSettingsPanel(item)}
571 </DiscoveryItemRow>
572 ))}
573 </SettingsSection>
574 ) : null}
575 </>
576 ) : (
577 <EmptySourceControlDiscovery
578 error={discovery.error}
579 isPending={discovery.isPending}
580 onScan={handleScan}
581 />
582 )}
583
584 <SourceControlWritingSettingsSection />
585 </SettingsPageContainer>
586 );
587}