Add source control discovery state

This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-05-02 14:23:00 -07:00
1 parent e36a1556a2
commit b133b0dbce
13 files changed
+943 -124

No files matched your search

@@ -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("[email protected]\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("[email protected]"),
detail: Option.none(),
},
{
kind: "bitbucket",
auth: "authenticated",
account: Option.some("bitbucket-user"),
detail: Option.none(),
},
],
);
}).pipe(Effect.provide(testLayer));
@@ -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<string>;
readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth;
};
interface AuthProbeInput {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
}
interface DiscoveryProbeResult<Kind extends string> {
readonly kind: Kind;
readonly label: string;
readonly executable: string;
readonly implemented: boolean;
readonly status: "available" | "missing";
readonly version: Option.Option<string>;
readonly installHint: string;
readonly detail: Option.Option<string>;
}
const VCS_PROBES: ReadonlyArray<VcsProbe> = [
{
kind: "git",
@@ -59,6 +79,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
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<ProviderProbe> = [
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<ProviderProbe> = [
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<ProviderProbe> = [
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<string> {
return Option.none();
}
function authAccount(account: string | undefined): Option.Option<string> {
const trimmed = account?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authHost(host: string | undefined): Option.Option<string> {
const trimmed = host?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authDetail(detail: string | undefined): Option.Option<string> {
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<string> {
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<RegExp>): 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<SourceControlDiscoveryResult>;
}
@@ -122,7 +322,7 @@ export const layer = Layer.effect(
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
input: DiscoveryProbe & { readonly kind: Kind },
) =>
): Effect.Effect<DiscoveryProbeResult<Kind>> =>
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<string>(),
})),
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<string>(),
}) satisfies DiscoveryProbeResult<Kind>,
),
Effect.catch((cause) =>
Effect.succeed({
kind: input.kind,
@@ -156,10 +359,49 @@ export const layer = Layer.effect(
version: Option.none<string>(),
installHint: input.installHint,
detail: detailFromCause(cause),
}),
} satisfies DiscoveryProbeResult<Kind>),
),
);
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<SourceControlProviderDiscoveryItem>
>,
{ concurrency: "unbounded" },
@@ -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 (
<span className="inline-flex min-w-0 items-center gap-1.5">
{props.separator ? <span aria-hidden>·</span> : null}
{props.prefix ? <span className="text-muted-foreground/80">{props.prefix}</span> : null}
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className={cn(
"min-w-0 cursor-pointer rounded-sm font-mono text-[11px] leading-none transition hover:text-foreground",
revealed ? "text-muted-foreground" : "select-none text-muted-foreground blur-[2px]",
)}
onClick={() => setRevealed((value) => !value)}
aria-label={revealed ? "Hide account email" : "Reveal account email"}
>
{revealed ? trimmed : redacted}
</button>
}
/>
<TooltipPopup side="top">
{revealed ? "Click to hide email" : "Click to reveal email"}
</TooltipPopup>
</Tooltip>
<RedactedSensitiveText
value={trimmed}
ariaLabel="Toggle account email visibility"
revealTooltip="Click to reveal email"
hideTooltip="Click to hide email"
/>
</span>
);
}
@@ -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 (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className={cn(
"min-w-0 cursor-pointer rounded-sm font-mono text-[11px] leading-none transition hover:text-foreground",
revealed ? "text-muted-foreground" : "select-none text-muted-foreground blur-[2px]",
props.className,
)}
onClick={() => setRevealed((current) => !current)}
aria-label={props.ariaLabel}
>
{revealed ? value : redacted}
</button>
}
/>
<TooltipPopup side="top">{revealed ? props.hideTooltip : props.revealTooltip}</TooltipPopup>
</Tooltip>
);
}
@@ -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>): 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 (
<RedactedSensitiveText
value={props.account}
ariaLabel="Toggle source control account visibility"
revealTooltip="Click to reveal account"
hideTooltip="Click to hide account"
/>
);
}
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 (
<div
@@ -104,6 +145,11 @@ function DiscoveryItemRow({
Not in this branch
</Badge>
) : null}
{authStatus ? (
<Badge variant={authStatus.badge} size="sm">
{authStatus.label}
</Badge>
) : null}
</div>
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
<span>CLI</span>
@@ -111,6 +157,13 @@ function DiscoveryItemRow({
{item.executable}
</code>
{version ? <span>- {version}</span> : null}
{auth ? (
<>
<span aria-hidden>-</span>
<span>{authSummary(auth)}</span>
{authAccount ? <RedactedAccount account={authAccount} /> : null}
</>
) : null}
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
@@ -138,6 +191,23 @@ function DiscoveryItemRow({
<dd className="min-w-0 font-mono text-foreground">{item.executable}</dd>
<dt className="text-muted-foreground">Version</dt>
<dd className="min-w-0 text-foreground">{version ?? "Not detected"}</dd>
{auth ? (
<>
<dt className="text-muted-foreground">Auth</dt>
<dd className="min-w-0 space-y-1 text-foreground">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<span>{authSummary(auth)}</span>
{authAccount ? <RedactedAccount account={authAccount} /> : null}
{authHost ? (
<span className="text-muted-foreground">on {authHost}</span>
) : null}
</div>
{authDetail ? (
<div className="break-words text-muted-foreground">{authDetail}</div>
) : null}
</dd>
</>
) : null}
<dt className="text-muted-foreground">Install</dt>
<dd className="min-w-0 leading-relaxed text-foreground">{item.installHint}</dd>
<dt className="text-muted-foreground">Build</dt>
@@ -161,49 +231,15 @@ function DiscoveryItemRow({
}
export function SourceControlSettingsPanel() {
const [loadState, setLoadState] = useState<DiscoveryLoadState>({
status: "loading",
result: null,
});
const latestResultRef = useRef<SourceControlDiscoveryResult | null>(null);
const discovery = useSourceControlDiscovery();
const [expanded, setExpanded] = useState<Readonly<Record<string, boolean>>>({});
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}
>
<RefreshCwIcon
className={cn("size-3.5", loadState.status === "loading" && "animate-spin")}
/>
<RefreshCwIcon className={cn("size-3.5", discovery.isPending && "animate-spin")} />
Scan
</Button>
}
@@ -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<SourceControlDiscoveryResult | null> {
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;
}
+2
View File
@@ -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();
+1
View File
@@ -131,6 +131,7 @@
"version": "0.0.0-alpha.1",
"dependencies": {
"@t3tools/contracts": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
+2 -1
View File
@@ -15,7 +15,8 @@
"test": "vitest run"
},
"dependencies": {
"@t3tools/contracts": "workspace:*"
"@t3tools/contracts": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
+1
View File
@@ -1,2 +1,3 @@
export * from "./knownEnvironment.ts";
export * from "./scoped.ts";
export * from "./sourceControlDiscoveryState.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<SourceControlDiscoveryResult>((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,
});
});
@@ -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<SourceControlDiscoveryResult>;
}
/* --- Constants ------------------------------------------------------ */
export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
data: null,
error: null,
isPending: false,
});
const INITIAL_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
data: null,
error: null,
isPending: true,
});
/* --- Atoms ---------------------------------------------------------- */
const knownSourceControlDiscoveryKeys = new Set<string>();
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<string, Promise<SourceControlDiscoveryResult | null>>();
/* -- 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<SourceControlDiscoveryResult | null> {
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,
};
}
+16
View File
@@ -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;