@devries-cameron20 / t3code Mirror · read-only / commits / 97f717a23a
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 23, 13:00 UTC

fix(server): Stop re-probing hosting CLIs for unrecognized hosts (#19692)

Co-authored-by: Victor Vogel <263261067+only21mil@users.noreply.github.com> Co-authored-by: Jorrin <43169049+JorrinKievit@users.noreply.github.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Mike Olson committed Oct 15, 2026 at 14:48 UTC 97f717a23a28b22753405e686265ba2295a387ff
7 files changed +404 -68
apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+168 -3
@@ -2,12 +2,23 @@ import { SourceControlProviderKind } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as DateTime from "effect/DateTime";
5 +import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 +import * as Fiber from "effect/Fiber";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 +import * as PlatformError from "effect/PlatformError";
11 +import * as PubSub from "effect/PubSub";
12 import * as Redacted from "effect/Redacted";
13 +import * as Stream from "effect/Stream";
14 +import * as TestClock from "effect/testing/TestClock";
15 import { ChildProcessSpawner } from "effect/process";
10 -import { VcsRepositoryDetectionError } from "@t3tools/contracts";
16 +import {
17 + DEFAULT_SERVER_SETTINGS,
18 + VcsProcessSpawnError,
19 + VcsProcessTimeoutError,
20 + VcsRepositoryDetectionError,
21 +} from "@t3tools/contracts";
22
23 import * as ServerSettings from "../serverSettings.ts";
24 import * as ServerConfig from "../config.ts";
@@ -54,6 +65,8 @@ function makeRegistry(input: {
65 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
66 readonly githubApi?: Partial<GitHubApi.GitHubApi["Service"]>;
67 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
68 + readonly forgejo?: Partial<ForgejoCli.ForgejoCli["Service"]>;
69 + readonly settings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
70 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
71 }) {
72 const driver = {
@@ -118,7 +131,9 @@ function makeRegistry(input: {
131 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
132 Layer.mock(BitbucketApi.BitbucketApi)({}),
133 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
121 - ServerSettings.ServerSettingsService.layerTest(),
134 + input.settings
135 + ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
136 + : ServerSettings.ServerSettingsService.layerTest(),
137 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
138 Layer.mock(GitHubApi.GitHubApi)({
139 // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
@@ -128,7 +143,10 @@ function makeRegistry(input: {
143 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
144 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
145 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
131 - Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
146 + Layer.mock(ForgejoCli.ForgejoCli)({
147 + listLogins: () => Effect.succeed([]),
148 + ...input.forgejo,
149 + }),
150 Layer.mock(GitCafeApi.GitCafeApi)({}),
151 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
152 cliEnv: () => Effect.succeed({}),
@@ -459,3 +477,150 @@ it.effect("skips GitHub discovery for the identity resolver's empty base URL", (
477 assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
478 }),
479 );
480 +
481 +const notFound = (command: string, cwd: string) =>
482 + new VcsProcessSpawnError({
483 + operation: "test",
484 + command,
485 + cwd,
486 + cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
487 + });
488 +
489 +const resolveUnknown = (
490 + registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
491 + repository: string,
492 +) =>
493 + registry.resolveHandle({
494 + cwd: `/${repository}`,
495 + context: {
496 + provider: {
497 + kind: SourceControlProviderKind.make("unknown"),
498 + name: "git.example.internal",
499 + baseUrl: "https://git.example.internal",
500 + },
501 + remoteName: "origin",
502 + remoteUrl: `git@Git.Example.Internal:team/${repository}.git`,
503 + },
504 + });
505 +
506 +it.effect("asks once for every checkout of a server no integration claims", () =>
507 + Effect.gen(function* () {
508 + const asked: Array<string> = [];
509 + const release = yield* Deferred.make<void>();
510 + const registry = yield* makeRegistry({
511 + remotes: [],
512 + process: {
513 + run: ({ command, args, cwd }) => {
514 + asked.push([command, ...args].join(" "));
515 + return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
516 + },
517 + },
518 + githubApi: {
519 + credential: (host) => {
520 + asked.push(`credential ${host}`);
521 + return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
522 + },
523 + },
524 + forgejo: {
525 + listLogins: ({ command = "tea", cwd }) => {
526 + asked.push(command);
527 + const cause = notFound(command, cwd);
528 + return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause }));
529 + },
530 + },
531 + });
532 +
533 + // Three checkouts read while the first probe is still running share it.
534 + const started = yield* Effect.forEach(["a", "b", "c"], () => Deferred.make<void>());
535 + const callers = yield* Effect.forEach(
536 + ["a", "b", "c"],
537 + (repository, index) =>
538 + Deferred.succeed(started[index]!, undefined).pipe(
539 + Effect.andThen(resolveUnknown(registry, repository)),
540 + ),
541 + { concurrency: "unbounded" },
542 + ).pipe(Effect.forkChild);
543 + yield* Effect.forEach(started, Deferred.await);
544 + yield* Deferred.succeed(release, undefined);
545 + const handles = yield* Fiber.join(callers);
546 + yield* resolveUnknown(registry, "d");
547 + assert.deepStrictEqual(
548 + handles.map((handle) => handle.provider.kind),
549 + ["unknown", "unknown", "unknown"],
550 + );
551 + const once = asked.slice();
552 + // glab is asked about the remote's host as the remote spells it.
553 + assert.sameMembers(once, [
554 + "credential git.example.internal",
555 + "glab auth status --hostname Git.Example.Internal",
556 + "fj",
557 + "tea",
558 + ]);
559 +
560 + // A login made in a terminal sends no signal, so the server is asked again later.
561 + yield* TestClock.adjust("5 minutes");
562 + yield* resolveUnknown(registry, "a");
563 + assert.deepStrictEqual(asked, [...once, ...once]);
564 + }),
565 +);
566 +
567 +it.effect("asks again after a check that could not answer", () =>
568 + Effect.gen(function* () {
569 + let asks = 0;
570 + const registry = yield* makeRegistry({
571 + remotes: [],
572 + process: {
573 + run: ({ command, cwd }) => {
574 + asks += 1;
575 + return Effect.fail(
576 + new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
577 + );
578 + },
579 + },
580 + });
581 + yield* resolveUnknown(registry, "a");
582 + yield* resolveUnknown(registry, "b");
583 + assert.strictEqual(asks, 2);
584 + }),
585 +);
586 +
587 +it.effect("asks again once Settings change", () =>
588 + Effect.gen(function* () {
589 + const changes = yield* PubSub.unbounded<typeof DEFAULT_SERVER_SETTINGS>();
590 + const handled = yield* Deferred.make<void>();
591 + let signedIn = false;
592 + const registry = yield* makeRegistry({
593 + remotes: [],
594 + settings: {
595 + subscribeChanges: PubSub.subscribe(changes).pipe(
596 + Effect.map((subscription) =>
597 + // A change is handled once the registry asks for the next one.
598 + Stream.fromSubscription(subscription).pipe(
599 + Stream.flatMap((settings) =>
600 + Stream.concat(
601 + Stream.make(settings),
602 + Stream.fromEffectDrain(Deferred.succeed(handled, undefined)),
603 + ),
604 + ),
605 + ),
606 + ),
607 + ),
608 + },
609 + process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) },
610 + githubApi: {
611 + credential: (host) =>
612 + signedIn
613 + ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
614 + : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
615 + },
616 + });
617 + assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown");
618 + signedIn = true;
619 + assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown");
620 +
621 + // A token saved for the host in Settings.
622 + yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS);
623 + yield* Deferred.await(handled);
624 + assert.strictEqual((yield* resolveUnknown(registry, "c")).provider.kind, "github");
625 + }),
626 +);
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+73 -14
@@ -3,8 +3,11 @@ import * as Cache from "effect/Cache";
3 import * as Context from "effect/Context";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 +import * as Equal from "effect/Equal";
7 import * as Exit from "effect/Exit";
8 +import * as Hash from "effect/Hash";
9 import * as Layer from "effect/Layer";
10 +import * as Stream from "effect/Stream";
11 import {
12 SourceControlProviderError,
13 type SourceControlProviderDiscoveryItem,
@@ -18,14 +21,19 @@ import {
21 probeSourceControlProvider,
22 refineUnknownRemoteProvider,
23 type SourceControlProviderDiscoverySpec,
24 + type UnknownRemoteVerdict,
25 } from "@t3tools/source-control-core/server/discovery";
26 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
27
28 import * as ServerConfig from "../config.ts";
29 +import * as ServerSettings from "../serverSettings.ts";
30 import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
31
32 const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
33 const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
34 +const UNKNOWN_REMOTE_CACHE_CAPACITY = 512;
35 +// Outlasts the one-minute pull request sweep. A login made since is noticed after this.
36 +const UNKNOWN_REMOTE_CACHE_TTL = Duration.minutes(5);
37
38 export interface SourceControlProviderRegistration {
39 readonly kind: SourceControlProviderKind;
@@ -150,6 +158,38 @@ function selectProviderContext(
158 );
159 }
160
161 +/**
162 + * One lookup per server: remotes that differ only in `owner/repo` share a verdict, and callers
163 + * that arrive while it runs wait on it. `cwd` is left out because it only matters when a probe
164 + * fails there, and a failed probe is not kept. Equality ignores `lookup`, so this is not a
165 + * `Data.Class`.
166 + */
167 +class UnknownRemoteLookup {
168 + readonly key: string;
169 + readonly lookup: Effect.Effect<UnknownRemoteVerdict>;
170 +
171 + constructor(
172 + context: SourceControlProvider.SourceControlProviderContext,
173 + lookup: Effect.Effect<UnknownRemoteVerdict>,
174 + ) {
175 + this.lookup = lookup;
176 + this.key = [
177 + context.provider.name,
178 + context.provider.baseUrl,
179 + // Strip a trailing `owner/repo`, never the host after `//`, so one-segment remotes stay apart.
180 + context.remoteUrl.trim().replace(/(?<!\/\/[^/]*)[^/:]+\/[^/:]+\/?$/u, ""),
181 + context.requestedHost ?? "",
182 + ].join("\n");
183 + }
184 +
185 + [Equal.symbol](that: unknown): boolean {
186 + return that instanceof UnknownRemoteLookup && that.key === this.key;
187 + }
188 + [Hash.symbol](): number {
189 + return Hash.string(this.key);
190 + }
191 +}
192 +
193 function bindProviderContext(
194 provider: SourceControlProvider.SourceControlProvider["Service"],
195 context: SourceControlProvider.SourceControlProviderContext | null,
@@ -198,6 +238,7 @@ function bindProviderContext(
238 export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
239 function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
240 const config = yield* ServerConfig.ServerConfig;
241 + const serverSettings = yield* ServerSettings.ServerSettingsService;
242 const { process } = yield* SourceControlHost.SourceControlHost;
243 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
244 const providers = new Map<
@@ -209,6 +250,36 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
250 const get: SourceControlProviderRegistry["Service"]["get"] = (kind) =>
251 Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
252
253 + // "No integration holds this host" is the common verdict and the one worth keeping. A verdict
254 + // reached while some probe failed is handed to the callers waiting on it, then dropped.
255 + const unknownRemoteCache = yield* Cache.makeWith(
256 + (request: UnknownRemoteLookup) => request.lookup,
257 + {
258 + capacity: UNKNOWN_REMOTE_CACHE_CAPACITY,
259 + timeToLive: (exit) =>
260 + Exit.isSuccess(exit) && exit.value.settled ? UNKNOWN_REMOTE_CACHE_TTL : Duration.zero,
261 + },
262 + );
263 + // A token saved or a host toggled in Settings must show on the next read, not after the TTL.
264 + const settingsChanges = yield* serverSettings.subscribeChanges;
265 + yield* Stream.runForEach(settingsChanges, () => Cache.invalidateAll(unknownRemoteCache)).pipe(
266 + Effect.forkScoped,
267 + );
268 +
269 + const refineContext = (
270 + cwd: string,
271 + context: SourceControlProvider.SourceControlProviderContext | null,
272 + ): Effect.Effect<SourceControlProvider.SourceControlProviderContext | null> =>
273 + context === null || context.provider.kind !== "unknown"
274 + ? Effect.succeed(context)
275 + : Cache.get(
276 + unknownRemoteCache,
277 + new UnknownRemoteLookup(
278 + context,
279 + refineUnknownRemoteProvider({ specs: discoverySpecs, process, cwd, context }),
280 + ),
281 + ).pipe(Effect.map(({ provider }) => (provider ? { ...context, provider } : context)));
282 +
283 const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
284 function* (cwd: string) {
285 const handle = yield* vcsRegistry.resolve({ cwd }).pipe(
@@ -235,14 +306,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
306 }),
307 ),
308 );
238 - const context = selectProviderContext(remotes.remotes);
239 -
240 - return yield* refineUnknownRemoteProvider({
241 - specs: discoverySpecs,
242 - process,
243 - cwd,
244 - context,
245 - });
309 + return yield* refineContext(cwd, selectProviderContext(remotes.remotes));
310 },
311 );
312
@@ -258,12 +322,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
322 const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
323 (input.context === undefined
324 ? Cache.get(providerContextCache, input.cwd)
261 - : refineUnknownRemoteProvider({
262 - specs: discoverySpecs,
263 - process,
264 - cwd: input.cwd,
265 - context: input.context,
266 - })
325 + : refineContext(input.cwd, input.context)
326 ).pipe(
327 Effect.map((context) => {
328 const kind = context?.provider.kind ?? SourceControlProviderKind.make("unknown");
packages/source-control-core/src/server/discovery.ts
+94 -44
@@ -4,14 +4,19 @@
4 * @module source-control-core/server/discovery
5 */
6 import * as NodeUtil from "node:util";
7 -import type {
8 - SourceControlProviderAuth,
9 - SourceControlProviderDiscoveryItem,
10 - SourceControlProviderInfo,
11 - SourceControlProviderKind,
7 +import {
8 + VcsProcessSpawnError,
9 + type SourceControlProviderAuth,
10 + type SourceControlProviderDiscoveryItem,
11 + type SourceControlProviderInfo,
12 + type SourceControlProviderKind,
13 } from "@t3tools/contracts";
14 +import type * as Cause from "effect/Cause";
15 import * as Effect from "effect/Effect";
16 import * as Option from "effect/Option";
17 +import * as PlatformError from "effect/PlatformError";
18 +import * as Result from "effect/Result";
19 +import * as Schema from "effect/Schema";
20
21 import type * as SourceControlProvider from "./SourceControlProvider.ts";
22 import type * as SourceControlHost from "./SourceControlHost.ts";
@@ -39,12 +44,15 @@ export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
44 readonly executable: string;
45 readonly versionArgs: ReadonlyArray<string>;
46 readonly authArgs: ReadonlyArray<string>;
42 - readonly remoteRefinementArgs?: ReadonlyArray<string>;
47 + readonly remoteRefinementArgs?: (
48 + context: SourceControlProvider.SourceControlProviderContext,
49 + ) => ReadonlyArray<string>;
50 readonly probeTimeoutMs?: number;
51 readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
52 + /** `null` when the CLI holds nothing for the remote; `undefined` when its output cannot say. */
53 readonly refineUnknownRemote?: (
54 input: SourceControlUnknownRemoteRefinementInput,
47 - ) => SourceControlProviderInfo | null;
55 + ) => SourceControlProviderInfo | null | undefined;
56 };
57
58 export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
@@ -55,10 +63,14 @@ export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
63 export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
64 readonly type: "managed-cli";
65 readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
66 + /**
67 + * `null` when the integration holds nothing for the remote, which includes its CLI not being
68 + * installed. A failure means it could not tell, and the registry does not keep that answer.
69 + */
70 readonly refineUnknownRemote: (input: {
71 readonly cwd: string;
72 readonly context: SourceControlProvider.SourceControlProviderContext;
61 - }) => Effect.Effect<SourceControlProviderInfo | null>;
73 + }) => Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError>;
74 };
75
76 export type SourceControlProviderDiscoverySpec =
@@ -294,47 +306,85 @@ export function probeSourceControlProvider(input: {
306 );
307 }
308
309 +const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
310 +
311 +/**
312 + * A hosting CLI that is not installed claims no remote. The spawner checks the cwd before the
313 + * executable, so only the executable's own ENOENT comes from `ChildProcess`.
314 + */
315 +export function isMissingExecutable(error: unknown): boolean {
316 + return (
317 + isVcsProcessSpawnError(error) &&
318 + PlatformError.isPlatformError(error.cause) &&
319 + error.cause.reason._tag === "NotFound" &&
320 + error.cause.reason.module === "ChildProcess"
321 + );
322 +}
323 +
324 +/** The CLI ran, but its output does not say whether it holds the remote's host. */
325 +class UnknownRemoteUnanswered extends Schema.TaggedError<UnknownRemoteUnanswered>()(
326 + "UnknownRemoteUnanswered",
327 + {},
328 +) {}
329 +
330 +export interface UnknownRemoteVerdict {
331 + readonly provider: SourceControlProviderInfo | null;
332 + /** Every integration answered, so the verdict holds for other checkouts of the same server. */
333 + readonly settled: boolean;
334 +}
335 +
336 +function refineWithSpec(input: {
337 + readonly spec: SourceControlProviderDiscoverySpec;
338 + readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
339 + readonly cwd: string;
340 + readonly context: SourceControlProvider.SourceControlProviderContext;
341 +}): Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError> {
342 + const { spec, context } = input;
343 + if (spec.type === "managed-cli") {
344 + return spec.refineUnknownRemote({ cwd: input.cwd, context });
345 + }
346 + if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
347 + return input.process
348 + .run({
349 + operation: "source-control.discovery.refine-unknown-remote",
350 + command: spec.executable,
351 + args: spec.remoteRefinementArgs?.(context) ?? spec.authArgs,
352 + cwd: input.cwd,
353 + allowNonZeroExit: true,
354 + timeoutMs: probeTimeoutMs(spec),
355 + maxOutputBytes: 8_000,
356 + appendTruncationMarker: true,
357 + })
358 + .pipe(
359 + Effect.catchIf(isMissingExecutable, () => Effect.void),
360 + Effect.flatMap((auth) => {
361 + const provider =
362 + auth === undefined ? null : spec.refineUnknownRemote({ cwd: input.cwd, context, auth });
363 + return provider === undefined
364 + ? Effect.fail(new UnknownRemoteUnanswered())
365 + : Effect.succeed(provider);
366 + }),
367 + );
368 +}
369 +
370 +/** Asks every integration whether it holds the remote's server; the first claim wins. */
371 export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")(
372 function* (input: {
373 readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;
374 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
375 readonly cwd: string;
302 - readonly context: SourceControlProvider.SourceControlProviderContext | null;
303 - }): Effect.fn.Return<SourceControlProvider.SourceControlProviderContext | null> {
304 - if (input.context === null || input.context.provider.kind !== "unknown") {
305 - return input.context;
376 + readonly context: SourceControlProvider.SourceControlProviderContext;
377 + }): Effect.fn.Return<UnknownRemoteVerdict> {
378 + const results = yield* Effect.forEach(input.specs, (spec) =>
379 + refineWithSpec({ ...input, spec }).pipe(Effect.result),
380 + );
381 + // A claim reached after another integration could not answer is not settled: that one might
382 + // have claimed the host first.
383 + let settled = true;
384 + for (const result of results) {
385 + if (Result.isFailure(result)) settled = false;
386 + else if (result.success !== null) return { provider: result.success, settled };
387 }
307 - const context = input.context;
308 -
309 - const providers = yield* Effect.forEach(input.specs, (spec) => {
310 - if (spec.type === "managed-cli") {
311 - return spec.refineUnknownRemote({ cwd: input.cwd, context });
312 - }
313 - if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
314 - return input.process
315 - .run({
316 - operation: "source-control.discovery.refine-unknown-remote",
317 - command: spec.executable,
318 - args: spec.remoteRefinementArgs ?? spec.authArgs,
319 - cwd: input.cwd,
320 - allowNonZeroExit: true,
321 - timeoutMs: probeTimeoutMs(spec),
322 - maxOutputBytes: 8_000,
323 - appendTruncationMarker: true,
324 - })
325 - .pipe(
326 - Effect.map((auth) =>
327 - spec.refineUnknownRemote({
328 - cwd: input.cwd,
329 - context,
330 - auth,
331 - }),
332 - ),
333 - Effect.orElseSucceed(() => null),
334 - );
335 - });
336 - const provider = providers.find((candidate) => candidate !== null);
337 -
338 - return provider ? { ...context, provider } : context;
388 + return { provider: null, settled };
389 },
390 );
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts
+22 -3
@@ -8,6 +8,7 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo
8 import * as ForgejoCli from "./ForgejoCli.ts";
9 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
10 import {
11 + isMissingExecutable,
12 providerAuth,
13 probeSourceControlProvider,
14 type SourceControlCliDiscoverySpec,
@@ -24,7 +25,7 @@ export const discovery = {
25 executable: "tea",
26 versionArgs: ["--version"],
27 authArgs: ["login", "status", "--output", "json"],
27 - remoteRefinementArgs: ["login", "list", "--output", "json"],
28 + remoteRefinementArgs: () => ["login", "list", "--output", "json"],
29 parseAuth: (input) => {
30 const logins = ForgejoCli.parseForgejoLogins(input.stdout);
31 const login = logins.find((entry) => entry.default === "true") ?? logins[0];
@@ -150,13 +151,30 @@ export const makeDiscovery = Effect.gen(function* () {
151 }) {
152 const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);
153 if (!remote) return null;
154 + // Both CLIs claim Forgejo, so one failing does not stop the other from claiming the host.
155 + let failure: ForgejoCli.ForgejoCliError | undefined;
156 for (const command of ["fj", "tea"] as const) {
157 const logins = yield* listLogins({
158 cwd: input.cwd,
159 command,
160 remoteUrl: input.context.remoteUrl,
158 - }).pipe(Effect.orElseSucceed(() => []));
159 - const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);
161 + }).pipe(
162 + // A CLI that is not installed holds no login.
163 + Effect.catchIf(
164 + (error) => isMissingExecutable(error.cause),
165 + () => Effect.succeed([]),
166 + ),
167 + Effect.result,
168 + );
169 + if (Result.isFailure(logins)) {
170 + failure ??= logins.failure;
171 + continue;
172 + }
173 + const login = ForgejoCli.matchForgejoLogin(
174 + logins.success,
175 + remote,
176 + input.context.requestedHost,
177 + );
178 if (login)
179 return {
180 kind: SourceControlProviderKind.make("forgejo"),
@@ -164,6 +182,7 @@ export const makeDiscovery = Effect.gen(function* () {
182 baseUrl: login.url,
183 };
184 }
185 + if (failure) return yield* failure;
186 return null;
187 },
188 ),
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+6 -2
@@ -269,10 +269,14 @@ export const makeDiscovery = Effect.gen(function* () {
269 // Identity resolution also probes providers before a web base URL is known.
270 const url = URL.parse(context.provider.baseUrl);
271 if (!url?.host) return Effect.succeed(null);
272 + // A timeout or keyring failure propagates: the registry does not keep that answer.
273 return api.credential(url.host).pipe(
274 Effect.as(true),
274 - Effect.catchTags({ GitHubHostDisabledError: () => Effect.succeed(true) }),
275 - Effect.orElseSucceed(() => false),
275 + Effect.catchTags({
276 + GitHubCliMissingError: () => Effect.succeed(false),
277 + GitHubHostDisabledError: () => Effect.succeed(true),
278 + GitHubNotSignedInError: () => Effect.succeed(false),
279 + }),
280 Effect.map((known) =>
281 known
282 ? ({
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts
+28
@@ -214,6 +214,34 @@ it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
214 });
215 });
216
217 +it("tells a host glab has no login for apart from output that cannot say", () => {
218 + const refine = (stderr: string) =>
219 + GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
220 + cwd: "/repo",
221 + context: {
222 + provider: {
223 + kind: SourceControlProviderKind.make("unknown"),
224 + name: "git.example.test",
225 + baseUrl: "https://git.example.test",
226 + },
227 + remoteName: "origin",
228 + remoteUrl: "https://git.example.test/group/project.git",
229 + },
230 + auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
231 + });
232 +
233 + // A settled "no" is cached; anything else makes the next read ask glab again.
234 + assert.strictEqual(
235 + refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
236 + null,
237 + );
238 + assert.strictEqual(
239 + refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
240 + null,
241 + );
242 + assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
243 +});
244 +
245 it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
246 assert.deepStrictEqual(
247 parseGitLabAuthStatusHosts(`localhost:8080
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts
+13 -2
@@ -80,14 +80,19 @@ function parseGitLabAuth(input: SourceControlAuthProbeInput) {
80 });
81 }
82
83 +// What glab prints when it holds no login for the host, across its 1.x releases.
84 +const GITLAB_HOST_NOT_LOGGED_IN_PATTERN =
85 + /\bnot (?:been )?authenticated with glab\b|\bno gitlab instances? ha(?:s|ve) been authenticated\b/iu;
86 +
87 function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
88 const host = input.context.provider.name.toLowerCase();
85 - const authenticated = parseGitLabAuthStatusHosts(combinedAuthOutput(input.auth)).some(
89 + const output = combinedAuthOutput(input.auth);
90 + const authenticated = parseGitLabAuthStatusHosts(output).some(
91 (entry) => entry.account !== null && entry.host === host,
92 );
93
94 if (!authenticated) {
90 - return null;
95 + return GITLAB_HOST_NOT_LOGGED_IN_PATTERN.test(output) ? null : undefined;
96 }
97
98 return {
@@ -104,6 +109,12 @@ export const discovery = {
109 executable: "glab",
110 versionArgs: ["--version"],
111 authArgs: ["auth", "status"],
112 + // glab matches its configured hosts by exact name, so ask with the remote's own spelling.
113 + remoteRefinementArgs: ({ provider, remoteUrl }) => {
114 + const at = remoteUrl.toLowerCase().indexOf(provider.name.toLowerCase());
115 + const host = at < 0 ? provider.name : remoteUrl.slice(at, at + provider.name.length);
116 + return ["auth", "status", "--hostname", host];
117 + },
118 parseAuth: parseGitLabAuth,
119 refineUnknownRemote: refineUnknownGitLabRemote,
120 installHint: