From b133b0dbce1baa418c59bfd8f79fda96b79040c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 2 May 2026 12:48:25 -0700 Subject: [PATCH] Add source control discovery state --- .../SourceControlDiscovery.test.ts | 156 +++++++++- .../sourceControl/SourceControlDiscovery.ts | 272 +++++++++++++++++- .../settings/ProviderInstanceCard.tsx | 52 +--- .../settings/RedactedSensitiveText.tsx | 61 ++++ .../settings/SourceControlSettings.tsx | 146 ++++++---- .../src/lib/sourceControlDiscoveryState.ts | 44 +++ apps/web/src/localApi.ts | 2 + bun.lock | 1 + packages/client-runtime/package.json | 3 +- packages/client-runtime/src/index.ts | 1 + .../src/sourceControlDiscoveryState.test.ts | 107 +++++++ .../src/sourceControlDiscoveryState.ts | 206 +++++++++++++ packages/contracts/src/sourceControl.ts | 16 ++ 13 files changed, 943 insertions(+), 124 deletions(-) create mode 100644 apps/web/src/components/settings/RedactedSensitiveText.tsx create mode 100644 apps/web/src/lib/sourceControlDiscoveryState.ts create mode 100644 packages/client-runtime/src/sourceControlDiscoveryState.test.ts create mode 100644 packages/client-runtime/src/sourceControlDiscoveryState.ts diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts index 217407b278..3146212db4 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts @@ -1,6 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Layer } from "effect"; +import { Effect, Layer, Option } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import { VcsProcessSpawnError } from "@t3tools/contracts"; @@ -8,10 +8,16 @@ import { ServerConfig } from "../config.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { SourceControlDiscovery, layer } from "./SourceControlDiscovery.ts"; -const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({ - exitCode: ChildProcessSpawner.ExitCode(0), +const processOutput = ( + stdout: string, + options?: { + readonly stderr?: string; + readonly exitCode?: ChildProcessSpawner.ExitCode; + }, +): VcsProcess.VcsProcessOutput => ({ + exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0), stdout, - stderr: "", + stderr: options?.stderr ?? "", stdoutTruncated: false, stderrTruncated: false, }); @@ -27,9 +33,20 @@ it.effect("reports implemented tools separately from locally available CLIs", () if (input.command === "git") { return Effect.succeed(processOutput("git version 2.51.0\n")); } - if (input.command === "gh") { + if (input.command === "gh" && input.args[0] === "--version") { return Effect.succeed(processOutput("gh version 2.83.0\n")); } + if (input.command === "gh" && input.args.join(" ") === "auth status") { + return Effect.succeed( + processOutput(`github.com +Logged in to github.com account juliusmarminge (keyring) +- Active account: true +- Git operations protocol: ssh +- Token: gho_************************************ +- Token scopes: 'admin:public_key', 'gist', 'read:org', 'repo' +`), + ); + } return Effect.fail( new VcsProcessSpawnError({ operation: input.operation, @@ -65,12 +82,133 @@ it.effect("reports implemented tools separately from locally available CLIs", () kind: item.kind, implemented: item.implemented, status: item.status, + auth: item.auth.status, + account: item.auth.account, })), [ - { kind: "github", implemented: true, status: "available" }, - { kind: "gitlab", implemented: false, status: "missing" }, - { kind: "azure-devops", implemented: false, status: "missing" }, - { kind: "bitbucket", implemented: false, status: "missing" }, + { + kind: "github", + implemented: true, + status: "available", + auth: "authenticated", + account: Option.some("juliusmarminge"), + }, + { + kind: "gitlab", + implemented: false, + status: "missing", + auth: "unknown", + account: Option.none(), + }, + { + kind: "azure-devops", + implemented: false, + status: "missing", + auth: "unknown", + account: Option.none(), + }, + { + kind: "bitbucket", + implemented: false, + status: "missing", + auth: "unknown", + account: Option.none(), + }, + ], + ); + }).pipe(Effect.provide(testLayer)); +}); + +it.effect("probes provider authentication without exposing token details", () => { + const testLayer = layer.pipe( + Layer.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-auth-discovery-" }), + ), + Layer.provide( + Layer.mock(VcsProcess.VcsProcess)({ + run: (input) => { + if (input.args[0] === "--version") { + return Effect.succeed(processOutput(`${input.command} version test\n`)); + } + if (input.command === "gh" && input.args.join(" ") === "auth status") { + return Effect.succeed( + processOutput(`github.com +Logged in to github.com account octocat (keyring) +- Token: gho_************************************ +- Token scopes: 'repo' +`), + ); + } + if (input.command === "glab" && input.args.join(" ") === "auth status") { + return Effect.succeed( + processOutput(`gitlab.com +Logged in to gitlab.com as gitlab-user +`), + ); + } + if ( + input.command === "az" && + input.args.join(" ") === "account show --query user.name -o tsv" + ) { + return Effect.succeed(processOutput("azure-user@example.com\n")); + } + if (input.command === "bb" && input.args.join(" ") === "auth status") { + return Effect.succeed( + processOutput(`bitbucket.org +Logged in as bitbucket-user +`), + ); + } + return Effect.fail( + new VcsProcessSpawnError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + cause: new Error(`${input.command} not found`), + }), + ); + }, + }), + ), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const discovery = yield* SourceControlDiscovery; + const result = yield* discovery.discover; + + assert.deepStrictEqual( + result.sourceControlProviders.map((item) => ({ + kind: item.kind, + auth: item.auth.status, + account: item.auth.account, + detail: item.auth.detail, + })), + [ + { + kind: "github", + auth: "authenticated", + account: Option.some("octocat"), + detail: Option.none(), + }, + { + kind: "gitlab", + auth: "authenticated", + account: Option.some("gitlab-user"), + detail: Option.none(), + }, + { + kind: "azure-devops", + auth: "authenticated", + account: Option.some("azure-user@example.com"), + detail: Option.none(), + }, + { + kind: "bitbucket", + auth: "authenticated", + account: Option.some("bitbucket-user"), + detail: Option.none(), + }, ], ); }).pipe(Effect.provide(testLayer)); diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.ts b/apps/server/src/sourceControl/SourceControlDiscovery.ts index 375b1aaa42..a3b309995b 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.ts @@ -1,4 +1,5 @@ import { + type SourceControlProviderAuth, type SourceControlDiscoveryResult, type SourceControlProviderDiscoveryItem, type SourceControlProviderKind, @@ -24,8 +25,27 @@ type VcsProbe = DiscoveryProbe & { type ProviderProbe = DiscoveryProbe & { readonly kind: SourceControlProviderKind; + readonly authArgs: ReadonlyArray; + readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth; }; +interface AuthProbeInput { + readonly stdout: string; + readonly stderr: string; + readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"]; +} + +interface DiscoveryProbeResult { + readonly kind: Kind; + readonly label: string; + readonly executable: string; + readonly implemented: boolean; + readonly status: "available" | "missing"; + readonly version: Option.Option; + readonly installHint: string; + readonly detail: Option.Option; +} + const VCS_PROBES: ReadonlyArray = [ { kind: "git", @@ -59,6 +79,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray = [ label: "GitHub", executable: "gh", versionArgs: ["--version"], + authArgs: ["auth", "status"], + parseAuth: parseGitHubAuth, implemented: true, installHint: "Install GitHub CLI with `brew install gh` or from https://cli.github.com/.", }, @@ -67,6 +89,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray = [ label: "GitLab", executable: "glab", versionArgs: ["--version"], + authArgs: ["auth", "status"], + parseAuth: parseGitLabAuth, implemented: false, installHint: "Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.", @@ -76,6 +100,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray = [ label: "Azure DevOps", executable: "az", versionArgs: ["--version"], + authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"], + parseAuth: parseAzureAuth, implemented: false, installHint: "Install Azure CLI with `brew install azure-cli`, then add Azure DevOps support with `az extension add --name azure-devops`.", @@ -85,6 +111,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray = [ label: "Bitbucket", executable: "bb", versionArgs: ["--version"], + authArgs: ["auth", "status"], + parseAuth: parseBitbucketAuth, implemented: false, installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.", }, @@ -105,6 +133,178 @@ function detailFromCause(cause: unknown): Option.Option { return Option.none(); } +function authAccount(account: string | undefined): Option.Option { + const trimmed = account?.trim(); + return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); +} + +function authHost(host: string | undefined): Option.Option { + const trimmed = host?.trim(); + return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); +} + +function authDetail(detail: string | undefined): Option.Option { + const trimmed = detail?.trim(); + return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); +} + +function providerAuth(input: { + readonly status: SourceControlProviderAuth["status"]; + readonly account?: string | undefined; + readonly host?: string | undefined; + readonly detail?: string | undefined; +}): SourceControlProviderAuth { + return { + status: input.status, + account: authAccount(input.account), + host: authHost(input.host), + detail: authDetail(input.detail), + }; +} + +function unknownAuth(detail?: string): SourceControlProviderAuth { + return providerAuth({ status: "unknown", detail }); +} + +function combinedAuthOutput(input: AuthProbeInput): string { + return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n"); +} + +function sanitizedAuthLines(text: string): ReadonlyArray { + return text + .split(/\r?\n/) + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry)); +} + +function firstSafeAuthLine(text: string): string | undefined { + return sanitizedAuthLines(text)[0]; +} + +function parseCliHost(text: string): string | undefined { + return sanitizedAuthLines(text) + .map((line) => line.replace(/^[^a-z0-9]+/iu, "")) + .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line)); +} + +function matchFirst(text: string, patterns: ReadonlyArray): string | undefined { + for (const pattern of patterns) { + const match = pattern.exec(text); + const value = match?.[1]?.trim(); + if (value && value.length > 0) return value; + } + return undefined; +} + +function parseGitHubAuth(input: AuthProbeInput): SourceControlProviderAuth { + const output = combinedAuthOutput(input); + const account = matchFirst(output, [ + /Logged in to .* account\s+([^\s(]+)/iu, + /Logged in to .* as\s+([^\s(]+)/iu, + ]); + const host = parseCliHost(output); + + if (input.exitCode !== 0) { + return providerAuth({ + status: "unauthenticated", + host, + detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.", + }); + } + + if (account) { + return providerAuth({ status: "authenticated", account, host }); + } + + return providerAuth({ + status: "unknown", + host, + detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.", + }); +} + +function parseGitLabAuth(input: AuthProbeInput): SourceControlProviderAuth { + const output = combinedAuthOutput(input); + const account = matchFirst(output, [ + /Logged in to .* as\s+([^\s(]+)/iu, + /Logged in to .* account\s+([^\s(]+)/iu, + /account:\s*([^\s(]+)/iu, + ]); + const host = parseCliHost(output); + + if (input.exitCode !== 0) { + return providerAuth({ + status: "unauthenticated", + host, + detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.", + }); + } + + if (account) { + return providerAuth({ status: "authenticated", account, host }); + } + + return providerAuth({ + status: "unknown", + host, + detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.", + }); +} + +function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth { + const account = input.stdout.trim().split(/\r?\n/)[0]?.trim(); + + if (input.exitCode !== 0) { + return providerAuth({ + status: "unauthenticated", + detail: + firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.", + }); + } + + if (account && account.length > 0) { + return providerAuth({ status: "authenticated", account, host: "dev.azure.com" }); + } + + return providerAuth({ + status: "unknown", + host: "dev.azure.com", + detail: "Azure CLI account status could not be parsed.", + }); +} + +function parseBitbucketAuth(input: AuthProbeInput): SourceControlProviderAuth { + const output = combinedAuthOutput(input); + const account = matchFirst(output, [ + /Logged in to .* as\s+([^\s(]+)/iu, + /Logged in as\s+([^\s(]+)/iu, + /account:\s*([^\s(]+)/iu, + /user:\s*([^\s(]+)/iu, + /username:\s*([^\s(]+)/iu, + ]); + const host = parseCliHost(output) ?? "bitbucket.org"; + + if (input.exitCode !== 0) { + return providerAuth({ + status: "unauthenticated", + host, + detail: + firstSafeAuthLine(output) ?? "Authenticate the Bitbucket CLI before enabling Bitbucket.", + }); + } + + if (account) { + return providerAuth({ status: "authenticated", account, host }); + } + + return providerAuth({ + status: "unknown", + host, + detail: firstSafeAuthLine(output) ?? "Bitbucket CLI auth status could not be parsed.", + }); +} + export interface SourceControlDiscoveryShape { readonly discover: Effect.Effect; } @@ -122,7 +322,7 @@ export const layer = Layer.effect( const probe = ( input: DiscoveryProbe & { readonly kind: Kind }, - ) => + ): Effect.Effect> => process .run({ operation: "source-control.discovery.probe", @@ -134,18 +334,21 @@ export const layer = Layer.effect( truncateOutputAtMaxBytes: true, }) .pipe( - Effect.map((result) => ({ - kind: input.kind, - label: input.label, - executable: input.executable, - implemented: input.implemented, - status: "available" as const, - version: Option.orElse(firstNonEmptyLine(result.stdout), () => - firstNonEmptyLine(result.stderr), - ), - installHint: input.installHint, - detail: Option.none(), - })), + Effect.map( + (result) => + ({ + kind: input.kind, + label: input.label, + executable: input.executable, + implemented: input.implemented, + status: "available" as const, + version: Option.orElse(firstNonEmptyLine(result.stdout), () => + firstNonEmptyLine(result.stderr), + ), + installHint: input.installHint, + detail: Option.none(), + }) satisfies DiscoveryProbeResult, + ), Effect.catch((cause) => Effect.succeed({ kind: input.kind, @@ -156,10 +359,49 @@ export const layer = Layer.effect( version: Option.none(), installHint: input.installHint, detail: detailFromCause(cause), - }), + } satisfies DiscoveryProbeResult), ), ); + const probeProvider = (input: ProviderProbe) => + probe(input).pipe( + Effect.flatMap((item) => { + if (item.status !== "available") { + return Effect.succeed({ + ...item, + auth: unknownAuth("CLI is not installed."), + } satisfies SourceControlProviderDiscoveryItem); + } + + return process + .run({ + operation: "source-control.discovery.auth", + command: input.executable, + args: input.authArgs, + cwd: config.cwd, + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 8_000, + truncateOutputAtMaxBytes: true, + }) + .pipe( + Effect.map( + (result) => + ({ + ...item, + auth: input.parseAuth(result), + }) satisfies SourceControlProviderDiscoveryItem, + ), + Effect.catch((cause) => + Effect.succeed({ + ...item, + auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))), + } satisfies SourceControlProviderDiscoveryItem), + ), + ); + }), + ); + return SourceControlDiscovery.of({ discover: Effect.all({ versionControlSystems: Effect.all( @@ -167,7 +409,7 @@ export const layer = Layer.effect( { concurrency: "unbounded" }, ), sourceControlProviders: Effect.all( - SOURCE_CONTROL_PROVIDER_PROBES.map((entry) => probe(entry)) as ReadonlyArray< + SOURCE_CONTROL_PROVIDER_PROBES.map((entry) => probeProvider(entry)) as ReadonlyArray< Effect.Effect >, { concurrency: "unbounded" }, diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 6d492618f5..236e1db565 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -1,7 +1,7 @@ "use client"; import { ChevronDownIcon, PlusIcon, Trash2Icon, XIcon } from "lucide-react"; -import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { useEffect, useState, type ReactNode } from "react"; import { isProviderDriverKind, type ProviderInstanceConfig, @@ -24,6 +24,7 @@ import type { DriverOption } from "./providerDriverMeta"; import { ProviderSettingsForm } from "./ProviderSettingsForm"; import { ProviderModelsSection } from "./ProviderModelsSection"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { RedactedSensitiveText } from "./RedactedSensitiveText"; import { PROVIDER_STATUS_STYLES, getProviderSummary, @@ -42,8 +43,6 @@ const PROVIDER_ACCENT_SWATCHES = [ const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/; -const REDACTED_EMAIL_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; - let environmentVariableDraftId = 0; const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`; @@ -68,25 +67,6 @@ function makeEnvironmentDraftRow( }; } -function redactedEmailPlaceholder(email: string): string { - let state = 0x811c9dc5; - for (let index = 0; index < email.length; index += 1) { - state ^= email.charCodeAt(index); - state = Math.imul(state, 0x01000193); - } - - const nextChar = () => { - state = Math.imul(state ^ (state >>> 13), 0x85ebca6b); - state = Math.imul(state ^ (state >>> 16), 0xc2b2ae35); - return REDACTED_EMAIL_ALPHABET[Math.abs(state) % REDACTED_EMAIL_ALPHABET.length] ?? "x"; - }; - - return Array.from(email, (char) => { - if (char === "@" || char === "." || char === "-" || char === "_") return char; - return nextChar(); - }).join(""); -} - /** * Read a string[] at `key` from the opaque config blob, filtering out * non-string entries. Used for `customModels`, which is always typed as @@ -146,35 +126,19 @@ function ProviderAuthEmail(props: { readonly prefix?: string; readonly separator?: boolean; }) { - const [revealed, setRevealed] = useState(false); const trimmed = props.email?.trim(); - const redacted = useMemo(() => (trimmed ? redactedEmailPlaceholder(trimmed) : ""), [trimmed]); if (!trimmed) return null; return ( {props.separator ? ยท : null} {props.prefix ? {props.prefix} : null} - - setRevealed((value) => !value)} - aria-label={revealed ? "Hide account email" : "Reveal account email"} - > - {revealed ? trimmed : redacted} - - } - /> - - {revealed ? "Click to hide email" : "Click to reveal email"} - - + ); } diff --git a/apps/web/src/components/settings/RedactedSensitiveText.tsx b/apps/web/src/components/settings/RedactedSensitiveText.tsx new file mode 100644 index 0000000000..95b31b4036 --- /dev/null +++ b/apps/web/src/components/settings/RedactedSensitiveText.tsx @@ -0,0 +1,61 @@ +import { useMemo, useState } from "react"; + +import { cn } from "../../lib/utils"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; + +const REDACTED_TEXT_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"; + +function redactedPlaceholder(value: string): string { + let state = 0x811c9dc5; + for (let index = 0; index < value.length; index += 1) { + state ^= value.charCodeAt(index); + state = Math.imul(state, 0x01000193); + } + + const nextChar = () => { + state = Math.imul(state ^ (state >>> 13), 0x85ebca6b); + state = Math.imul(state ^ (state >>> 16), 0xc2b2ae35); + return REDACTED_TEXT_ALPHABET[Math.abs(state) % REDACTED_TEXT_ALPHABET.length] ?? "x"; + }; + + return Array.from(value, (char) => { + if (char === "@" || char === "." || char === "-" || char === "_") return char; + return nextChar(); + }).join(""); +} + +export function RedactedSensitiveText(props: { + readonly value: string | null | undefined; + readonly ariaLabel: string; + readonly revealTooltip: string; + readonly hideTooltip: string; + readonly className?: string; +}) { + const [revealed, setRevealed] = useState(false); + const value = props.value?.trim(); + const redacted = useMemo(() => (value ? redactedPlaceholder(value) : ""), [value]); + + if (!value) return null; + + return ( + + setRevealed((current) => !current)} + aria-label={props.ariaLabel} + > + {revealed ? value : redacted} + + } + /> + {revealed ? props.hideTooltip : props.revealTooltip} + + ); +} diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsx index 502241711c..96993ab777 100644 --- a/apps/web/src/components/settings/SourceControlSettings.tsx +++ b/apps/web/src/components/settings/SourceControlSettings.tsx @@ -1,30 +1,26 @@ import { ChevronDownIcon, GitBranchIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react"; import { Option } from "effect"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useMemo, useState } from "react"; import type { SourceControlDiscoveryItem, SourceControlDiscoveryResult, + SourceControlProviderAuth, SourceControlProviderDiscoveryItem, VcsDiscoveryItem, } from "@t3tools/contracts"; -import { ensureLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; +import { + refreshSourceControlDiscovery, + useSourceControlDiscovery, +} from "../../lib/sourceControlDiscoveryState"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Collapsible, CollapsibleContent } from "../ui/collapsible"; import { Switch } from "../ui/switch"; +import { RedactedSensitiveText } from "./RedactedSensitiveText"; import { SettingsPageContainer, SettingsSection } from "./settingsLayout"; -type DiscoveryLoadState = - | { readonly status: "loading"; readonly result: SourceControlDiscoveryResult | null } - | { readonly status: "ready"; readonly result: SourceControlDiscoveryResult } - | { - readonly status: "error"; - readonly result: SourceControlDiscoveryResult | null; - readonly message: string; - }; - const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = { versionControlSystems: [], sourceControlProviders: [], @@ -34,6 +30,46 @@ function optionLabel(value: Option.Option): string | null { return Option.getOrNull(value); } +function isProviderDiscoveryItem( + item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem, +): item is SourceControlProviderDiscoveryItem { + return "auth" in item; +} + +function authPresentation(auth: SourceControlProviderAuth): { + readonly label: string; + readonly badge: "success" | "warning" | "outline"; +} { + if (auth.status === "authenticated") { + return { label: "Signed in", badge: "success" }; + } + if (auth.status === "unauthenticated") { + return { label: "Sign in", badge: "warning" }; + } + return { label: "Auth unknown", badge: "outline" }; +} + +function authSummary(auth: SourceControlProviderAuth): string { + if (auth.status === "authenticated") { + return "Authenticated"; + } + if (auth.status === "unauthenticated") { + return "Not authenticated"; + } + return "Auth not checked"; +} + +function RedactedAccount(props: { readonly account: string | null }) { + return ( + + ); +} + function statusPresentation(item: SourceControlDiscoveryItem): { readonly label: string; readonly badge: "success" | "warning" | "outline"; @@ -80,6 +116,11 @@ function DiscoveryItemRow({ const version = optionLabel(item.version); const detail = optionLabel(item.detail); const enabled = item.implemented && item.status === "available"; + const auth = isProviderDiscoveryItem(item) ? item.auth : null; + const authStatus = auth ? authPresentation(auth) : null; + const authAccount = auth ? optionLabel(auth.account) : null; + const authHost = auth ? optionLabel(auth.host) : null; + const authDetail = auth ? optionLabel(auth.detail) : null; return (
) : null} + {authStatus ? ( + + {authStatus.label} + + ) : null}

CLI @@ -111,6 +157,13 @@ function DiscoveryItemRow({ {item.executable} {version ? - {version} : null} + {auth ? ( + <> + - + {authSummary(auth)} + {authAccount ? : null} + + ) : null}

@@ -138,6 +191,23 @@ function DiscoveryItemRow({
{item.executable}
Version
{version ?? "Not detected"}
+ {auth ? ( + <> +
Auth
+
+
+ {authSummary(auth)} + {authAccount ? : null} + {authHost ? ( + on {authHost} + ) : null} +
+ {authDetail ? ( +
{authDetail}
+ ) : null} +
+ + ) : null}
Install
{item.installHint}
Build
@@ -161,49 +231,15 @@ function DiscoveryItemRow({ } export function SourceControlSettingsPanel() { - const [loadState, setLoadState] = useState({ - status: "loading", - result: null, - }); - const latestResultRef = useRef(null); + const discovery = useSourceControlDiscovery(); const [expanded, setExpanded] = useState>>({}); - const refresh = useCallback((options?: { readonly signal?: AbortSignal }) => { - const previous = latestResultRef.current; - setLoadState({ status: "loading", result: previous }); - - ensureLocalApi() - .server.discoverSourceControl() - .then((result) => { - if (!options?.signal?.aborted) { - latestResultRef.current = result; - setLoadState({ status: "ready", result }); - } - }) - .catch((cause: unknown) => { - if (!options?.signal?.aborted) { - setLoadState({ - status: "error", - result: previous, - message: - cause instanceof Error ? cause.message : "Failed to discover source control tools.", - }); - } - }); - }, []); - - useEffect(() => { - const controller = new AbortController(); - refresh({ signal: controller.signal }); - return () => controller.abort(); - }, [refresh]); - - const result = loadState.result ?? EMPTY_DISCOVERY_RESULT; + const result = discovery.data ?? EMPTY_DISCOVERY_RESULT; const statusText = useMemo(() => { - if (loadState.status === "loading") return "Scanning installed tools..."; - if (loadState.status === "error") return loadState.message; + if (discovery.isPending) return "Scanning installed tools..."; + if (discovery.error) return discovery.error; return "Detected source control tools on this system."; - }, [loadState]); + }, [discovery.error, discovery.isPending]); const setItemExpanded = (key: string, value: boolean) => { setExpanded((current) => ({ ...current, [key]: value })); @@ -224,12 +260,12 @@ export function SourceControlSettingsPanel() { size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-xs" - onClick={() => refresh()} - disabled={loadState.status === "loading"} + onClick={() => { + void refreshSourceControlDiscovery(); + }} + disabled={discovery.isPending} > - + Scan } diff --git a/apps/web/src/lib/sourceControlDiscoveryState.ts b/apps/web/src/lib/sourceControlDiscoveryState.ts new file mode 100644 index 0000000000..5189c22a12 --- /dev/null +++ b/apps/web/src/lib/sourceControlDiscoveryState.ts @@ -0,0 +1,44 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM, + EMPTY_SOURCE_CONTROL_DISCOVERY_STATE, + type SourceControlDiscoveryState, + createSourceControlDiscoveryManager, + getSourceControlDiscoveryTargetKey, + sourceControlDiscoveryStateAtom, +} from "@t3tools/client-runtime"; +import type { SourceControlDiscoveryResult } from "@t3tools/contracts"; +import { useEffect } from "react"; + +import { readLocalApi } from "../localApi"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + +const SOURCE_CONTROL_DISCOVERY_TARGET = { key: "primary" } as const; + +export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({ + getRegistry: () => appAtomRegistry, + getClient: () => readLocalApi()?.server ?? null, +}); + +export function refreshSourceControlDiscovery(): Promise { + return sourceControlDiscoveryManager.refresh(SOURCE_CONTROL_DISCOVERY_TARGET); +} + +export function resetSourceControlDiscoveryStateForTests(): void { + sourceControlDiscoveryManager.reset(); +} + +export function useSourceControlDiscovery(): SourceControlDiscoveryState { + const targetKey = getSourceControlDiscoveryTargetKey(SOURCE_CONTROL_DISCOVERY_TARGET); + + useEffect(() => { + void sourceControlDiscoveryManager.refresh(SOURCE_CONTROL_DISCOVERY_TARGET); + }, []); + + const state = useAtomValue( + targetKey !== null + ? sourceControlDiscoveryStateAtom(targetKey) + : EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM, + ); + return targetKey === null ? EMPTY_SOURCE_CONTROL_DISCOVERY_STATE : state; +} diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 983020390a..c872a5f103 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -1,6 +1,7 @@ import type { ContextMenuItem, LocalApi } from "@t3tools/contracts"; import { resetGitStatusStateForTests } from "./lib/gitStatusState"; +import { resetSourceControlDiscoveryStateForTests } from "./lib/sourceControlDiscoveryState"; import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState"; import { resetServerStateForTests } from "./rpc/serverState"; import { resetWsConnectionStateForTests } from "./rpc/wsConnectionState"; @@ -147,6 +148,7 @@ export async function __resetLocalApiForTests() { __resetClientSettingsPersistenceForTests(); await resetEnvironmentServiceForTests(); resetGitStatusStateForTests(); + resetSourceControlDiscoveryStateForTests(); resetRequestLatencyStateForTests(); resetSavedEnvironmentRegistryStoreForTests(); resetSavedEnvironmentRuntimeStoreForTests(); diff --git a/bun.lock b/bun.lock index 79be837791..c7aeb59b76 100644 --- a/bun.lock +++ b/bun.lock @@ -131,6 +131,7 @@ "version": "0.0.0-alpha.1", "dependencies": { "@t3tools/contracts": "workspace:*", + "effect": "catalog:", }, "devDependencies": { "@effect/language-service": "catalog:", diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index bfe2d7828e..fbe97d0dd6 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -15,7 +15,8 @@ "test": "vitest run" }, "dependencies": { - "@t3tools/contracts": "workspace:*" + "@t3tools/contracts": "workspace:*", + "effect": "catalog:" }, "devDependencies": { "@effect/language-service": "catalog:", diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 9ca76328a8..f6f5b82758 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -1,2 +1,3 @@ export * from "./knownEnvironment.ts"; export * from "./scoped.ts"; +export * from "./sourceControlDiscoveryState.ts"; diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts new file mode 100644 index 0000000000..9a988be00a --- /dev/null +++ b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts @@ -0,0 +1,107 @@ +import { assert, beforeEach, it } from "vitest"; +import type { SourceControlDiscoveryResult } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/unstable/reactivity"; + +import { + EMPTY_SOURCE_CONTROL_DISCOVERY_STATE, + createSourceControlDiscoveryManager, +} from "./sourceControlDiscoveryState.ts"; + +const EMPTY_RESULT: SourceControlDiscoveryResult = { + versionControlSystems: [], + sourceControlProviders: [], +}; + +function unresolvedDiscovery() { + throw new Error("Discovery resolver was not initialized."); +} + +let registry = AtomRegistry.make(); + +beforeEach(() => { + registry.dispose(); + registry = AtomRegistry.make(); +}); + +it("stores refreshed discovery data in an atom snapshot", async () => { + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => ({ + discoverSourceControl: async () => EMPTY_RESULT, + }), + }); + + assert.deepStrictEqual(manager.getSnapshot({ key: null }), EMPTY_SOURCE_CONTROL_DISCOVERY_STATE); + + const result = await manager.refresh({ key: "primary" }); + + assert.strictEqual(result, EMPTY_RESULT); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: EMPTY_RESULT, + error: null, + isPending: false, + }); +}); + +it("deduplicates in-flight discovery refreshes by target key", async () => { + let resolveDiscovery: (result: SourceControlDiscoveryResult) => void = unresolvedDiscovery; + let calls = 0; + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => ({ + discoverSourceControl: () => { + calls += 1; + return new Promise((resolve) => { + resolveDiscovery = resolve; + }); + }, + }), + }); + + const first = manager.refresh({ key: "primary" }); + const second = manager.refresh({ key: "primary" }); + + assert.strictEqual(first, second); + assert.strictEqual(calls, 1); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: null, + error: null, + isPending: true, + }); + + resolveDiscovery(EMPTY_RESULT); + await first; + + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: EMPTY_RESULT, + error: null, + isPending: false, + }); +}); + +it("keeps the previous snapshot when refresh fails", async () => { + let shouldFail = false; + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => ({ + discoverSourceControl: async () => { + if (shouldFail) { + throw new Error("probe failed"); + } + return EMPTY_RESULT; + }, + }), + }); + + await manager.refresh({ key: "primary" }); + shouldFail = true; + + const result = await manager.refresh({ key: "primary" }); + + assert.strictEqual(result, EMPTY_RESULT); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: EMPTY_RESULT, + error: "probe failed", + isPending: false, + }); +}); diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.ts b/packages/client-runtime/src/sourceControlDiscoveryState.ts new file mode 100644 index 0000000000..b18d6103b8 --- /dev/null +++ b/packages/client-runtime/src/sourceControlDiscoveryState.ts @@ -0,0 +1,206 @@ +import type { SourceControlDiscoveryResult } from "@t3tools/contracts"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +/* --- Types ---------------------------------------------------------- */ + +export interface SourceControlDiscoveryState { + readonly data: SourceControlDiscoveryResult | null; + readonly error: string | null; + readonly isPending: boolean; +} + +export interface SourceControlDiscoveryTarget { + readonly key: string | null; +} + +export interface SourceControlDiscoveryClient { + readonly discoverSourceControl: () => Promise; +} + +/* --- Constants ------------------------------------------------------ */ + +export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze({ + data: null, + error: null, + isPending: false, +}); + +const INITIAL_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze({ + data: null, + error: null, + isPending: true, +}); + +/* --- Atoms ---------------------------------------------------------- */ + +const knownSourceControlDiscoveryKeys = new Set(); + +export const sourceControlDiscoveryStateAtom = Atom.family((key: string) => { + knownSourceControlDiscoveryKeys.add(key); + return Atom.make(INITIAL_SOURCE_CONTROL_DISCOVERY_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`source-control-discovery:${key}`), + ); +}); + +export const EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM = Atom.make( + EMPTY_SOURCE_CONTROL_DISCOVERY_STATE, +).pipe(Atom.keepAlive, Atom.withLabel("source-control-discovery:null")); + +/* --- Helpers -------------------------------------------------------- */ + +export function getSourceControlDiscoveryTargetKey( + target: SourceControlDiscoveryTarget, +): string | null { + const key = target.key?.trim(); + return key && key.length > 0 ? key : null; +} + +/* --- Refresh manager ------------------------------------------------ */ + +export interface SourceControlDiscoveryManagerConfig { + /** + * Get the atom registry used to read/write source-control discovery snapshots. + */ + readonly getRegistry: () => AtomRegistry.AtomRegistry; + /** + * Resolve the runtime client for a discovery target key. + * + * Web currently uses a single `"primary"` target, but keeping this keyed + * lets mobile or future multi-environment clients provide separate discovery + * clients without changing the state primitive. + */ + readonly getClient: (key: string) => SourceControlDiscoveryClient | null; +} + +export function createSourceControlDiscoveryManager(config: SourceControlDiscoveryManagerConfig) { + const refreshInFlight = new Map>(); + + /* -- Atom helpers -------------------------------------------------- */ + + function setState(targetKey: string, nextState: SourceControlDiscoveryState): void { + config.getRegistry().set(sourceControlDiscoveryStateAtom(targetKey), nextState); + } + + function markPending(targetKey: string): void { + const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey)); + const next: SourceControlDiscoveryState = + current.data === null + ? INITIAL_SOURCE_CONTROL_DISCOVERY_STATE + : { + data: current.data, + error: null, + isPending: true, + }; + + if ( + current.data === next.data && + current.error === next.error && + current.isPending === next.isPending + ) { + return; + } + + setState(targetKey, next); + } + + function setData(targetKey: string, data: SourceControlDiscoveryResult): void { + setState(targetKey, { + data, + error: null, + isPending: false, + }); + } + + function setError(targetKey: string, error: unknown): void { + const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey)); + setState(targetKey, { + data: current.data, + error: error instanceof Error ? error.message : "Failed to discover source control tools.", + isPending: false, + }); + } + + /* -- Public API ---------------------------------------------------- */ + + /** + * Trigger a one-shot source-control discovery RPC for a target. + * + * Calls are deduplicated while a refresh for the same target key is in + * flight. On failure, the previous successful snapshot is kept in `data` + * and the error message is stored separately so UI can keep rendering stale + * discovery results while showing the failure. + * + * @param target The logical runtime target to refresh. + * @param client Optional pre-resolved client, useful in tests. + */ + function refresh( + target: SourceControlDiscoveryTarget, + client?: SourceControlDiscoveryClient, + ): Promise { + const targetKey = getSourceControlDiscoveryTargetKey(target); + if (targetKey === null) { + return Promise.resolve(null); + } + + const existing = refreshInFlight.get(targetKey); + if (existing) { + return existing; + } + + const resolvedClient = client ?? config.getClient(targetKey); + if (!resolvedClient) { + const error = new Error("Source control discovery client is unavailable."); + setError(targetKey, error); + return Promise.resolve(getSnapshot(target).data); + } + + markPending(targetKey); + const promise = resolvedClient.discoverSourceControl().then( + (result) => { + setData(targetKey, result); + return result; + }, + (error: unknown) => { + setError(targetKey, error); + return getSnapshot(target).data; + }, + ); + const tracked = promise.finally(() => refreshInFlight.delete(targetKey)); + refreshInFlight.set(targetKey, tracked); + return tracked; + } + + /** + * Read the current atom snapshot for `target`. + * + * Invalid targets return the inert empty state rather than creating a new + * family atom entry. + */ + function getSnapshot(target: SourceControlDiscoveryTarget): SourceControlDiscoveryState { + const targetKey = getSourceControlDiscoveryTargetKey(target); + if (targetKey === null) { + return EMPTY_SOURCE_CONTROL_DISCOVERY_STATE; + } + + return config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey)); + } + + /** + * Clear in-flight refresh tracking and reset every known discovery atom. + * Primarily used by tests and runtime teardown. + */ + function reset(): void { + refreshInFlight.clear(); + for (const key of knownSourceControlDiscoveryKeys) { + setState(key, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE); + } + knownSourceControlDiscoveryKeys.clear(); + } + + return { + refresh, + getSnapshot, + reset, + }; +} diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.ts index e7b92f52ac..5776e84ff7 100644 --- a/packages/contracts/src/sourceControl.ts +++ b/packages/contracts/src/sourceControl.ts @@ -46,6 +46,21 @@ export type SourceControlRepositoryCloneUrls = typeof SourceControlRepositoryClo export const SourceControlDiscoveryStatus = Schema.Literals(["available", "missing"]); export type SourceControlDiscoveryStatus = typeof SourceControlDiscoveryStatus.Type; +export const SourceControlProviderAuthStatus = Schema.Literals([ + "authenticated", + "unauthenticated", + "unknown", +]); +export type SourceControlProviderAuthStatus = typeof SourceControlProviderAuthStatus.Type; + +export const SourceControlProviderAuth = Schema.Struct({ + status: SourceControlProviderAuthStatus, + account: Schema.Option(TrimmedNonEmptyString), + host: Schema.Option(TrimmedNonEmptyString), + detail: Schema.Option(TrimmedNonEmptyString), +}); +export type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type; + const SourceControlDiscoveryItemFields = { label: TrimmedNonEmptyString, executable: TrimmedNonEmptyString, @@ -71,6 +86,7 @@ export type VcsDiscoveryItem = typeof VcsDiscoveryItem.Type; export const SourceControlProviderDiscoveryItem = Schema.Struct({ kind: SourceControlProviderKind, ...SourceControlDiscoveryItemFields, + auth: SourceControlProviderAuth, }); export type SourceControlProviderDiscoveryItem = typeof SourceControlProviderDiscoveryItem.Type;