refactor(server): resolve title links through source control providers (#11844)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-14 19:57:34 -07:00
1 parent 8b9f6d3d55
commit 08abda9dcf
17 files changed
+414 -113

No files matched your search

@@ -400,3 +400,47 @@ it("reports an update hint instead of unauthenticated when gh predates --json",
/2\.81\.0/,
);
});
for (const kind of ["pull", "issues"]) {
it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: (input) => {
assert.deepStrictEqual(input.args, [
"api",
"--hostname",
"github.com",
"repos/owner/repo/issues/42",
"--jq",
"{title, body}",
]);
assert.strictEqual(input.maxOutputBytes, 32_000);
assert.strictEqual(input.timeoutMs, 3_000);
return Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: JSON.stringify({ title: "Pairing expiry", body: "Preserve remote access" }),
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
},
});
const lookup = provider.resolveLink?.({
cwd: "/unrelated",
url: new URL(`https://github.com/owner/repo/${kind}/42`),
});
assert.ok(lookup);
assert.deepStrictEqual(yield* lookup, {
title: "Pairing expiry",
body: "Preserve remote access",
});
assert.strictEqual(
provider.resolveLink?.({
cwd: "/unrelated",
url: new URL("https://github.com/owner/repo"),
}),
undefined,
);
}),
);
}
@@ -1,3 +1,4 @@
import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -20,6 +21,12 @@ import {
type SourceControlCliDiscoverySpec,
} from "./SourceControlProviderDiscovery.ts";
const decodeLinkSubject = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ title: Schema.String, body: Schema.NullOr(Schema.String) }),
),
);
function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
return {
provider: "github",
@@ -208,8 +215,45 @@ export const make = Effect.gen(function* () {
);
};
const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
input: { readonly cwd: string; readonly url: URL },
endpoint: string,
) {
return yield* github
.execute({
cwd: input.cwd,
args: ["api", "--hostname", input.url.host, endpoint, "--jq", "{title, body}"],
env: { GH_PROMPT_DISABLED: "1" },
timeoutMs: 3_000,
maxOutputBytes: 32_000,
})
.pipe(
Effect.flatMap((result) => decodeLinkSubject(result.stdout)),
Effect.map((subject) => ({ title: subject.title, body: subject.body })),
Effect.mapError(
(cause) =>
new SourceControlProviderError({
provider: "github",
operation: "resolveLink",
cwd: input.cwd,
detail: "The linked subject could not be read.",
cause,
}),
),
);
});
return SourceControlProvider.SourceControlProvider.of({
kind: "github",
resolveLink: (input) => {
// Automatic enrichment must not send ambient CLI credentials to a host from message text.
if (input.url.host !== "github.com") return undefined;
const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
input.url.pathname,
);
if (!match) return undefined;
return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
},
listChangeRequests,
getChangeRequest: (input) =>
github.getPullRequest(input).pipe(
@@ -226,3 +226,48 @@ selfhosted
],
);
});
for (const kind of ["merge_requests", "issues"]) {
it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: (input) => {
assert.deepStrictEqual(input.args, [
"api",
"--hostname",
"gitlab.com",
`projects/group%2Fsubgroup%2Fproject/${kind}/42`,
]);
assert.strictEqual(input.maxOutputBytes, 32_000);
assert.strictEqual(input.timeoutMs, 3_000);
return Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: JSON.stringify({
title: "Pairing expiry",
description: "Preserve remote access",
}),
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
},
});
const lookup = provider.resolveLink?.({
cwd: "/unrelated",
url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
});
assert.ok(lookup);
assert.deepStrictEqual(yield* lookup, {
title: "Pairing expiry",
body: "Preserve remote access",
});
assert.strictEqual(
provider.resolveLink?.({
cwd: "/unrelated",
url: new URL("https://gitlab.com/owner/repo"),
}),
undefined,
);
}),
);
}
@@ -1,3 +1,4 @@
import * as Schema from "effect/Schema";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
@@ -16,6 +17,12 @@ import {
} from "./SourceControlProviderDiscovery.ts";
import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
const decodeLinkSubject = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
),
);
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
return {
provider: "gitlab",
@@ -105,8 +112,47 @@ export const discovery = {
export const make = Effect.gen(function* () {
const gitlab = yield* GitLabCli.GitLabCli;
const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
input: { readonly cwd: string; readonly url: URL },
endpoint: string,
) {
return yield* gitlab
.execute({
cwd: input.cwd,
args: ["api", "--hostname", input.url.host, endpoint],
timeoutMs: 3_000,
maxOutputBytes: 32_000,
})
.pipe(
Effect.flatMap((result) => decodeLinkSubject(result.stdout)),
Effect.map((subject) => ({ title: subject.title, body: subject.description })),
Effect.mapError(
(cause) =>
new SourceControlProviderError({
provider: "gitlab",
operation: "resolveLink",
cwd: input.cwd,
detail: "The linked subject could not be read.",
cause,
}),
),
);
});
return SourceControlProvider.SourceControlProvider.of({
kind: "gitlab",
resolveLink: (input) => {
// Automatic enrichment must not send ambient CLI credentials to a host from message text.
if (input.url.host !== "gitlab.com") return undefined;
const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
input.url.pathname,
);
if (!match) return undefined;
return readLinkSubject(
input,
`projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
);
},
listChangeRequests: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
@@ -10,6 +10,17 @@ import type {
SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
export interface SourceControlLinkSubject {
readonly title: string;
readonly body: string | null;
}
/** Return undefined synchronously for unsupported URLs, without starting a lookup. */
export type ResolveSourceControlLink = (input: {
readonly cwd: string;
readonly url: URL;
}) => Effect.Effect<SourceControlLinkSubject, SourceControlProviderError> | undefined;
export interface SourceControlProviderContext {
readonly provider: SourceControlProviderInfo;
readonly remoteName: string;
@@ -85,6 +96,8 @@ export class SourceControlProvider extends Context.Service<
SourceControlProvider,
{
readonly kind: SourceControlProviderKind;
/** Optional capability for issue and change-request subjects. */
readonly resolveLink?: ResolveSourceControlLink;
readonly listChangeRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
@@ -40,6 +40,8 @@ function makeRegistry(input: {
readonly url: string;
}>;
readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
readonly github?: Partial<GitHubCli.GitHubCli["Service"]>;
readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
}) {
const driver = {
@@ -92,8 +94,8 @@ function makeRegistry(input: {
processLayer,
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(GitHubCli.GitHubCli)(input.github ?? {}),
Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-source-control-registry-test-",
@@ -296,3 +298,50 @@ it.effect("falls back to a non-origin remote when origin is not configured", ()
assert.strictEqual(provider.kind, "azure-devops");
}),
);
it.effect(
"routes linked subjects by URL independently of the checkout and skips unsupported links",
() =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
github: {
execute: () =>
Effect.succeed(processOutput(JSON.stringify({ title: "GitHub issue", body: null }))),
},
gitlab: {
execute: () =>
Effect.succeed(
processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
),
},
});
for (const [url, expected] of [
["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
[
"https://gitlab.com/team/sub/project/-/merge_requests/2",
{ title: "GitLab MR", body: "Nested project" },
],
] as const) {
const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
assert.ok(lookup);
assert.deepStrictEqual(yield* lookup, expected);
}
for (const url of [
"https://example.test/team/project/issues/1",
"https://github.attacker.test/team/project/issues/1",
"https://gitlab.attacker.test/team/project/-/issues/1",
"https://github.com/team/project",
"https://codeberg.org/team/project/issues/1",
"https://bitbucket.org/team/project/pull-requests/1",
"https://dev.azure.com/org/project/_git/repo/pullrequest/1",
"http://github.com/team/project/issues/1",
"https://user:[email protected]/team/project/issues/1",
]) {
assert.strictEqual(
registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
undefined,
);
}
}).pipe(Effect.scoped),
);
@@ -43,6 +43,7 @@ export interface SourceControlProviderHandle {
export class SourceControlProviderRegistry extends Context.Service<
SourceControlProviderRegistry,
{
readonly resolveLink: SourceControlProvider.ResolveSourceControlLink;
readonly get: (
kind: SourceControlProviderKind,
) => Effect.Effect<
@@ -161,6 +162,7 @@ function bindProviderContext(
return SourceControlProvider.SourceControlProvider.of({
kind: provider.kind,
...(provider.resolveLink ? { resolveLink: provider.resolveLink } : {}),
listChangeRequests: (input) =>
provider.listChangeRequests({
...input,
@@ -277,6 +279,13 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
);
return SourceControlProviderRegistry.of({
resolveLink: (input) => {
if (input.url.protocol !== "https:" || input.url.username || input.url.password) {
return undefined;
}
const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;
return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;
},
get,
resolveHandle,
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
@@ -62,6 +62,7 @@ function makeLayer(input: {
const serviceLayer = SourceControlRepositoryService.layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
resolveLink: () => undefined,
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),