feat(pull-requests): link multiple pull requests to threads (#10839)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-09 15:50:58 -07:00
1 parent 383cc40f4d
commit afb84898be
172 files changed
+12063 -914

No files matched your search

@@ -44,6 +44,8 @@ export type UnpinThreadInput = CommandInput<"thread.unpin">;
export type ReorderPinnedThreadInput = CommandInput<"thread.pin.reorder">;
export type ReorderActiveThreadInput = CommandInput<"thread.active.reorder">;
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
export type LinkThreadPullRequestInput = CommandInput<"thread.pull-request.link">;
export type UnlinkThreadPullRequestInput = CommandInput<"thread.pull-request.unlink">;
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
export type StartThreadTurnInput = CommandInput<"thread.turn.start">;
@@ -252,6 +254,24 @@ export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => Command
});
});
export const linkThreadPullRequest: (input: LinkThreadPullRequestInput) => CommandEffect =
Effect.fn("EnvironmentCommands.linkThreadPullRequest")(function* (input) {
return yield* dispatch({
...input,
type: "thread.pull-request.link",
commandId: yield* commandId(input),
});
});
export const unlinkThreadPullRequest: (input: UnlinkThreadPullRequestInput) => CommandEffect =
Effect.fn("EnvironmentCommands.unlinkThreadPullRequest")(function* (input) {
return yield* dispatch({
...input,
type: "thread.pull-request.unlink",
commandId: yield* commandId(input),
});
});
export const setThreadRuntimeMode: (input: SetThreadRuntimeModeInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.setThreadRuntimeMode",
)(function* (input) {
@@ -99,6 +99,7 @@ const THREAD_SHELL = {
archivedAt: null,
settledOverride: null,
settledAt: null,
pullRequests: [],
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
@@ -84,6 +84,7 @@ const THREAD = {
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
pullRequests: [],
worktreePath: null,
latestTurn: null,
createdAt: "2026-09-04T00:00:00.000Z",
@@ -41,6 +41,93 @@ function session(client: WsRpcProtocolClient): RpcSession {
};
}
const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (client: WsRpcProtocolClient) {
const connectionState: SupervisorConnectionState = {
...AVAILABLE_CONNECTION_STATE,
desired: true,
network: "online",
phase: "connected",
attempt: 1,
generation: 1,
};
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: yield* SubscriptionRef.make(connectionState),
session: yield* SubscriptionRef.make(Option.some(session(client))),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
run: (_environmentId, effect) =>
Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
runStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
followStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
} as EnvironmentRegistry.EnvironmentRegistry["Service"]);
const runtime = Atom.runtime(
Layer.merge(
Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Layer.succeed(
PullRequestDiffLoader,
PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
),
),
);
const atoms = createPullRequestEnvironmentAtoms(runtime);
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
Effect.sync(() => registry.dispose()),
);
return { atoms, registry };
});
it.effect("keeps concurrent diff file reads on different hosts separate", () =>
Effect.scoped(
Effect.gen(function* () {
const release = yield* Latch.make();
const started = yield* Latch.make();
const calls: string[] = [];
const client = {
[WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
Effect.gen(function* () {
calls.push(input.host);
yield* started.open;
yield* release.await;
return { oldContents: "", newContents: input.host };
}),
} as unknown as WsRpcProtocolClient;
const { atoms, registry } = yield* makeTestRuntime(client);
const input = {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 1,
changeType: "change",
oldPath: "src/app.ts",
newPath: "src/app.ts",
} as const;
const first = atoms.diffFileContents.run(registry, {
environmentId: TARGET.environmentId,
input: { ...input, host: "github.com" },
});
yield* started.await;
const second = atoms.diffFileContents.run(registry, {
environmentId: TARGET.environmentId,
input: { ...input, host: "github.example.com" },
});
yield* release.open;
const results = yield* Effect.promise(() => Promise.all([first, second]));
expect(results).toMatchObject([
{ _tag: "Success", value: { newContents: "github.com" } },
{ _tag: "Success", value: { newContents: "github.example.com" } },
]);
expect(calls).toEqual(["github.com", "github.example.com"]);
}),
),
);
it.effect("refreshes pull request activity after a comment is updated", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -76,46 +163,10 @@ it.effect("refreshes pull request activity after a comment is updated", () =>
commentBody = input.body;
}),
} as unknown as WsRpcProtocolClient;
const connectionState: SupervisorConnectionState = {
...AVAILABLE_CONNECTION_STATE,
desired: true,
network: "online",
phase: "connected",
attempt: 1,
generation: 1,
};
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: yield* SubscriptionRef.make(connectionState),
session: yield* SubscriptionRef.make(Option.some(session(client))),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
run: (_environmentId, effect) =>
Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
runStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
followStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
} as EnvironmentRegistry.EnvironmentRegistry["Service"]);
const runtime = Atom.runtime(
Layer.merge(
Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Layer.succeed(
PullRequestDiffLoader,
PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
),
),
);
const atoms = createPullRequestEnvironmentAtoms(runtime);
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
Effect.sync(() => registry.dispose()),
);
const { atoms, registry } = yield* makeTestRuntime(client);
const reference = {
projectId: ProjectId.make("project-1"),
host: "github.example.com",
repository: "acme/web",
number: 1,
} as const;
@@ -60,6 +60,18 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
});
}
/** The host-native stack a pull request belongs to; null where it is not stacked. */
export function createPullRequestStackAtomFamily<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
) {
return createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:stack",
tag: WS_METHODS.pullRequestsStack,
staleTimeMs: 60_000,
idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
});
}
export function pullRequestDetailToVcsStatus(
detail: PullRequestDetail | PullRequestSummary,
): NonNullable<VcsStatusResult["pr"]> {
@@ -97,6 +109,13 @@ export function createPullRequestEnvironmentAtoms<R, E>(
});
return {
refreshes,
linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:linked-threads",
tag: WS_METHODS.pullRequestsLinkedThreads,
staleTimeMs: 0,
refreshIntervalMs: 10_000,
refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
}),
list: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:list",
tag: WS_METHODS.pullRequestsList,
@@ -159,6 +178,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
JSON.stringify([
environmentId,
input.projectId,
input.host?.toLowerCase() ?? null,
input.repository,
input.number,
input.commit ?? null,
@@ -191,9 +211,14 @@ export function createPullRequestEnvironmentAtoms<R, E>(
tag: WS_METHODS.pullRequestsUpdateComment,
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
onSuccess: ({ environmentId, input: { projectId, repository, number } }, registry) =>
onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
Effect.sync(() =>
registry.refresh(activity({ environmentId, input: { projectId, repository, number } })),
registry.refresh(
activity({
environmentId,
input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
}),
),
),
}),
submitReview: createEnvironmentRpcCommand(runtime, {
@@ -38,6 +38,7 @@ const stubThread = {
archivedAt: null,
settledOverride: null,
settledAt: null,
pullRequests: [],
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
@@ -12,6 +12,7 @@ import {
type CreateThreadInput,
type DeleteThreadInput,
type InterruptThreadTurnInput,
type LinkThreadPullRequestInput,
type RespondToThreadApprovalInput,
type RespondToThreadUserInputInput,
type DismissThreadUserInputInput,
@@ -26,6 +27,7 @@ import {
type StartThreadTurnInput,
type StopThreadSessionInput,
type UnarchiveThreadInput,
type UnlinkThreadPullRequestInput,
type UnpinThreadInput,
type UnsettleThreadInput,
type UnsnoozeThreadInput,
@@ -34,6 +36,7 @@ import {
createThread,
deleteThread,
interruptThreadTurn,
linkThreadPullRequest,
respondToThreadApproval,
respondToThreadUserInput,
dismissThreadUserInput,
@@ -48,6 +51,7 @@ import {
startThreadTurn,
stopThreadSession,
unarchiveThread,
unlinkThreadPullRequest,
unpinThread,
unsettleThread,
unsnoozeThread,
@@ -60,6 +64,7 @@ export type {
CreateThreadInput,
DeleteThreadInput,
InterruptThreadTurnInput,
LinkThreadPullRequestInput,
RespondToThreadApprovalInput,
RespondToThreadUserInputInput,
DismissThreadUserInputInput,
@@ -74,6 +79,7 @@ export type {
StartThreadTurnInput,
StopThreadSessionInput,
UnarchiveThreadInput,
UnlinkThreadPullRequestInput,
UnpinThreadInput,
UnsettleThreadInput,
UnsnoozeThreadInput,
@@ -168,6 +174,18 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
linkPullRequest: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:link-pull-request",
execute: (input: LinkThreadPullRequestInput) => linkThreadPullRequest(input),
scheduler,
concurrency,
}),
unlinkPullRequest: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:unlink-pull-request",
execute: (input: UnlinkThreadPullRequestInput) => unlinkThreadPullRequest(input),
scheduler,
concurrency,
}),
setRuntimeMode: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:set-runtime-mode",
execute: (input: SetThreadRuntimeModeInput) => setThreadRuntimeMode(input),
@@ -37,6 +37,7 @@ const baseThread: OrchestrationThread = {
archivedAt: null,
settledOverride: null,
settledAt: null,
pullRequests: [],
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -406,6 +407,124 @@ describe("applyThreadDetailEvent", () => {
);
});
describe("thread pull request links", () => {
const link = {
host: "github.com",
repository: "pingdotgg/t3code",
number: 42,
url: "https://github.com/pingdotgg/t3code/pull/42",
source: "manual" as const,
linkedAt: "2026-04-01T05:00:00.000Z",
snapshot: null,
stack: null,
};
const key = { host: "github.com", repository: "pingdotgg/t3code", number: 42 };
const linkEvent = (sequence: number) =>
({
...baseEventFields,
sequence,
occurredAt: "2026-04-01T05:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.pull-request-linked",
payload: {
threadId: ThreadId.make("thread-1"),
link,
updatedAt: "2026-04-01T05:00:00.000Z",
},
}) as const;
it("links without inventing a legacy route and replaces by key", () => {
const linked = applyThreadDetailEvent(baseThread, linkEvent(5));
expect(linked.kind).toBe("updated");
if (linked.kind !== "updated") return;
expect(linked.thread.pullRequests).toEqual([link]);
expect(linked.thread.linkedPullRequest).toBeNull();
const relinked = applyThreadDetailEvent(linked.thread, {
...linkEvent(6),
payload: {
threadId: ThreadId.make("thread-1"),
link: { ...link, host: "GitHub.com", source: "agent" },
updatedAt: "2026-04-01T06:00:00.000Z",
},
});
if (relinked.kind !== "updated") throw new Error("expected update");
expect(relinked.thread.pullRequests).toHaveLength(1);
expect(relinked.thread.pullRequests[0]?.source).toBe("agent");
});
it("syncs snapshot and stack onto the matching link only", () => {
const linked = applyThreadDetailEvent(baseThread, linkEvent(5));
if (linked.kind !== "updated") throw new Error("expected update");
const snapshot = {
state: "merged" as const,
title: "Ship it",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-04-02T00:00:00.000Z",
syncedAt: "2026-04-02T00:01:00.000Z",
};
const synced = applyThreadDetailEvent(linked.thread, {
...baseEventFields,
sequence: 6,
occurredAt: "2026-04-02T00:01:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.pull-request-synced",
payload: {
threadId: ThreadId.make("thread-1"),
...key,
snapshot,
stack: null,
updatedAt: "2026-04-02T00:01:00.000Z",
},
});
if (synced.kind !== "updated") throw new Error("expected update");
expect(synced.thread.pullRequests[0]?.snapshot).toEqual(snapshot);
const unknown = applyThreadDetailEvent(synced.thread, {
...baseEventFields,
sequence: 7,
occurredAt: "2026-04-02T00:02:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.pull-request-synced",
payload: {
threadId: ThreadId.make("thread-1"),
...key,
number: 99,
snapshot,
stack: null,
updatedAt: "2026-04-02T00:02:00.000Z",
},
});
expect(unknown.kind).toBe("unchanged");
});
it("unlinks and clears the compat field", () => {
const linked = applyThreadDetailEvent(baseThread, linkEvent(5));
if (linked.kind !== "updated") throw new Error("expected update");
const unlinked = applyThreadDetailEvent(linked.thread, {
...baseEventFields,
sequence: 6,
occurredAt: "2026-04-01T06:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.pull-request-unlinked",
payload: {
threadId: ThreadId.make("thread-1"),
...key,
updatedAt: "2026-04-01T06:00:00.000Z",
},
});
if (unlinked.kind !== "updated") throw new Error("expected update");
expect(unlinked.thread.pullRequests).toEqual([]);
expect(unlinked.thread.linkedPullRequest).toBeNull();
});
});
describe("thread.message-sent", () => {
it("appends a new message", () => {
const result = applyThreadDetailEvent(baseThread, {
@@ -10,8 +10,10 @@ import type {
OrchestrationSession,
OrchestrationThread,
OrchestrationThreadActivity,
ThreadPullRequestLink,
TurnId,
} from "@t3tools/contracts";
import { threadPullRequestKeysEqual } from "@t3tools/shared/threadPullRequests";
import { isImportedAgentSessionMessageId } from "@t3tools/contracts";
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
@@ -20,6 +22,29 @@ export type ThreadDetailReducerResult =
| { readonly kind: "deleted" }
| { readonly kind: "unchanged" };
/** Keep only a legacy route supplied by the server; detail events cannot resolve project hosts. */
function withPullRequests(
thread: OrchestrationThread,
pullRequests: ReadonlyArray<ThreadPullRequestLink>,
updatedAt: string,
): ThreadDetailReducerResult {
return {
kind: "updated",
thread: {
...thread,
pullRequests,
linkedPullRequest:
thread.linkedPullRequest &&
pullRequests.some(
(link) => link.source !== "stack-dismissed" && link.url === thread.linkedPullRequest?.url,
)
? thread.linkedPullRequest
: null,
updatedAt,
},
};
}
const proposedPlanOrder = O.combine<OrchestrationThread["proposedPlans"][number]>(
O.mapInput(O.String, (p) => p.createdAt),
O.mapInput(O.String, (p) => p.id),
@@ -109,6 +134,7 @@ export function applyThreadDetailEvent(
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
pullRequests: [],
messages: [],
proposedPlans: [],
activities: [],
@@ -253,6 +279,40 @@ export function applyThreadDetailEvent(
},
};
case "thread.pull-request-linked": {
const link = event.payload.link;
const others = thread.pullRequests.filter(
(existing) => !threadPullRequestKeysEqual(existing, link),
);
return withPullRequests(thread, [...others, link], event.payload.updatedAt);
}
case "thread.pull-request-unlinked":
return withPullRequests(
thread,
thread.pullRequests.filter(
(existing) => !threadPullRequestKeysEqual(existing, event.payload),
),
event.payload.updatedAt,
);
case "thread.pull-request-synced": {
if (
!thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, event.payload))
) {
return { kind: "unchanged" };
}
return withPullRequests(
thread,
thread.pullRequests.map((existing) =>
threadPullRequestKeysEqual(existing, event.payload)
? { ...existing, snapshot: event.payload.snapshot, stack: event.payload.stack }
: existing,
),
event.payload.updatedAt,
);
}
case "thread.runtime-mode-set":
return {
kind: "updated",
@@ -65,6 +65,7 @@ const THREAD: OrchestrationThread = {
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
pullRequests: [],
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
@@ -104,6 +104,7 @@ const BASE_THREAD: OrchestrationThread = {
archivedAt: null,
settledOverride: null,
settledAt: null,
pullRequests: [],
deletedAt: null,
messages: [RECENT_MESSAGE],
proposedPlans: [],
@@ -75,6 +75,7 @@ const BASE_THREAD: OrchestrationThread = {
archivedAt: null,
settledOverride: null,
settledAt: null,
pullRequests: [],
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -1,7 +1,9 @@
import {
EnvironmentId,
ThreadId,
WS_METHODS,
type GitActionProgressEvent,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
@@ -589,9 +591,10 @@ describe("vcsActionState", () => {
successfulActionId,
);
const failedTransportActionId = createVcsActionTransportId(targetKey, failedActionId);
const rpcInputs = new Array<GitRunStackedActionInput>();
const client = {
[WS_METHODS.gitRunStackedAction]: (input: { readonly actionId: string }) =>
input.actionId === successfulTransportActionId
[WS_METHODS.gitRunStackedAction]: (input: GitRunStackedActionInput) =>
(rpcInputs.push(input), input.actionId === successfulTransportActionId)
? Stream.make(
progress({
kind: "action_finished",
@@ -652,16 +655,22 @@ describe("vcsActionState", () => {
const state = vcsRefsCacheStateAtom({ environmentId });
expect(registry.get(state).revision).toBe(0);
const threadId = ThreadId.make("thread-stacked-action");
const successfulResult = yield* Effect.promise(() =>
manager.runStackedAction(targetKey).run(registry, {
actionId: successfulActionId,
action,
threadId,
}),
);
expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
expect(registry.get(state).revision).toBe(1);
expect(removed).toEqual([`${environmentId}:*`]);
// The server links a created pull request to this thread, so the id must ride along.
expect(rpcInputs).toEqual([
{ actionId: successfulTransportActionId, cwd, action, threadId },
]);
const failedResult = yield* Effect.promise(() =>
manager.runStackedAction(targetKey).run(registry, {
@@ -6,6 +6,7 @@ import {
type GitRunStackedActionInput,
type GitRunStackedActionResult,
GitStackedAction,
type ThreadId,
WS_METHODS,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -76,6 +77,8 @@ export interface RunVcsStackedActionInput {
readonly commitMessage?: string;
readonly featureBranch?: boolean;
readonly filePaths?: ReadonlyArray<string>;
/** The thread the action runs beside; the server links a pull request it creates to it. */
readonly threadId?: ThreadId;
readonly onProgress?: (event: GitActionProgressEvent) => void;
}
@@ -463,6 +466,7 @@ export function createVcsActionManager<R, E>(
...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
...(input.featureBranch ? { featureBranch: true } : {}),
...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
};
return consumeVcsActionProgress(
runStreamInEnvironment(
@@ -0,0 +1,115 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import {
planThreadPullRequestMutation,
threadPullRequestLinkMode,
} from "./threadPullRequestCompatibility.ts";
const reference = {
host: "github.example",
repository: "team/repo",
number: 7,
url: "https://github.example/team/repo/pull/7",
};
const input = {
threadId: ThreadId.make("thread"),
reference,
legacyProjectId: ProjectId.make("exact-checkout"),
linked: true,
};
describe("thread pull request capability negotiation", () => {
it.each([undefined, {}, { threadPullRequests: false, threadPullRequestLinking: false }])(
"does not dispatch when linking is unadvertised: %j",
(capabilities) => {
expect(threadPullRequestLinkMode(capabilities)).toBe("unsupported");
expect(planThreadPullRequestMutation({ ...input, capabilities })).toBeNull();
},
);
it("uses metadata updates for old single-link servers, including unlink", () => {
const capabilities = { threadPullRequestLinking: true };
expect(planThreadPullRequestMutation({ ...input, capabilities })).toEqual({
type: "thread.meta.update",
input: {
threadId: input.threadId,
linkedPullRequest: {
projectId: input.legacyProjectId,
repository: reference.repository,
number: 7,
url: reference.url,
},
},
});
expect(
planThreadPullRequestMutation({
...input,
capabilities,
linked: false,
legacyProjectId: null,
}),
).toEqual({
type: "thread.meta.update",
input: { threadId: input.threadId, linkedPullRequest: null },
});
});
it("uses the checkout's Azure selector only for legacy metadata commands", () => {
const azure = {
...input,
reference: {
host: "dev.azure.com",
repository: "org/project/_git/web",
number: 42,
url: "https://dev.azure.com/org/project/_git/web/pullrequest/42",
},
legacyRepository: "web",
};
expect(
planThreadPullRequestMutation({
...azure,
capabilities: { threadPullRequestLinking: true },
}),
).toMatchObject({
type: "thread.meta.update",
input: { linkedPullRequest: { repository: "web", number: 42 } },
});
expect(
planThreadPullRequestMutation({
...azure,
capabilities: { threadPullRequests: true },
}),
).toMatchObject({
type: "thread.pull-request.link",
input: { repository: "org/project/_git/web", number: 42 },
});
});
it("never sends a same-host route as an exact repository to an old server", () => {
expect(
planThreadPullRequestMutation({
...input,
capabilities: { threadPullRequestLinking: true },
legacyProjectId: null,
}),
).toBeNull();
});
it.each([
{ threadPullRequests: true },
{ threadPullRequests: true, threadPullRequestLinking: true },
])("prefers multi-link commands when available: %j", (capabilities) => {
expect(
planThreadPullRequestMutation({ ...input, capabilities, legacyProjectId: null }),
).toEqual({
type: "thread.pull-request.link",
input: { threadId: input.threadId, ...reference, source: "manual" },
});
expect(planThreadPullRequestMutation({ ...input, capabilities, linked: false })).toEqual({
type: "thread.pull-request.unlink",
input: {
threadId: input.threadId,
host: reference.host,
repository: reference.repository,
number: reference.number,
},
});
});
});
@@ -0,0 +1,75 @@
import type {
ExecutionEnvironmentCapabilities,
ProjectId,
ThreadId,
ThreadPullRequestKey,
} from "@t3tools/contracts";
type LinkingCapabilities = Pick<
ExecutionEnvironmentCapabilities,
"threadPullRequests" | "threadPullRequestLinking"
>;
/** Capability negotiation keeps both single-link and multi-link environments usable. */
export function threadPullRequestLinkMode(capabilities: LinkingCapabilities | null | undefined) {
return capabilities?.threadPullRequests === true
? "multiple"
: capabilities?.threadPullRequestLinking === true
? "single"
: "unsupported";
}
export function planThreadPullRequestMutation({
capabilities,
threadId,
reference,
legacyProjectId,
legacyRepository,
linked,
}: {
capabilities: LinkingCapabilities | null | undefined;
threadId: ThreadId;
reference: ThreadPullRequestKey & { readonly url: string };
/** Older servers need the exact repository checkout; same-host routing is not available. */
legacyProjectId: ProjectId | null;
/** Provider selector for legacy APIs, which omit Azure organization and project paths. */
legacyRepository?: string | undefined;
linked: boolean;
}) {
switch (threadPullRequestLinkMode(capabilities)) {
case "multiple":
return linked
? {
type: "thread.pull-request.link" as const,
input: { threadId, ...reference, source: "manual" as const },
}
: {
type: "thread.pull-request.unlink" as const,
input: {
threadId,
host: reference.host,
repository: reference.repository,
number: reference.number,
},
};
case "single":
if (linked && legacyProjectId === null) return null;
return {
type: "thread.meta.update" as const,
input: {
threadId,
linkedPullRequest:
linked && legacyProjectId !== null
? {
projectId: legacyProjectId,
repository: legacyRepository ?? reference.repository,
number: reference.number,
url: reference.url,
}
: null,
},
};
case "unsupported":
return null;
}
}