@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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