feat(pull-requests): link multiple pull requests to threads #10839
Mergedjuliusmarmingemerged 12 commits into
main fromrefs/pull/10839/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge changed the title
- apps/server/src/git/linkCreatedPullRequest.ts lines 88 to 88OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +68,21 @@68+> =>69+ Effect.gen(function* () {70+ const engine = yield* OrchestrationEngine.OrchestrationEngineService;71+ const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;72+ const thread = yield* snapshots.getThreadShellById(input.threadId);73+ if (Option.isNone(thread)) return;74+ const project = Option.getOrUndefined(75+ yield* snapshots.getProjectShellById(thread.value.projectId),76+ );77+ const key = createdPullRequestKey(input.result, project);78+ if (key === null) return;79+ const commandId = yield* input.commandId;80+ yield* engine81+ .dispatch({82+ type: "thread.pull-request.link",83+ commandId,84+ threadId: input.threadId,85+ ...key,86+ source: "created",87+ })88+ .pipe(Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.void));apps/server/src/persistence/Services/ProjectionThreadPullRequests.ts lines 60 to 83OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ ) => Effect.Effect<void, ProjectionRepositoryError>;64+ readonly listByThreadId: (65+ input: ListProjectionThreadPullRequestsInput,66+ ) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequest>, ProjectionRepositoryError>;67+ readonly listByPullRequest: (68+ input: ListProjectionThreadPullRequestsByPullRequestInput,69+ ) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequest>, ProjectionRepositoryError>;70+ readonly delete: (71+ input: DeleteProjectionThreadPullRequestInput,72+ ) => Effect.Effect<void, ProjectionRepositoryError>;73+ readonly deleteByThreadId: (74+ input: DeleteProjectionThreadPullRequestsInput,75+ ) => Effect.Effect<void, ProjectionRepositoryError>;76+ readonly deleteByThreadIdAndSource: (77+ input: DeleteProjectionThreadPullRequestsBySourceInput,78+ ) => Effect.Effect<void, ProjectionRepositoryError>;79+}80+81+export class ProjectionThreadPullRequestRepository extends Context.Service<82+ ProjectionThreadPullRequestRepository,83+ ProjectionThreadPullRequestRepositoryShapeapps/server/src/mcp/toolkits/pullRequests/handlers.ts lines 208 to 208OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +188,21 @@188+ link_pull_request: (input) =>189+ Effect.gen(function* () {190+ const thread = yield* requireThread("link");191+ const project = yield* projectOf(thread, "link");192+ const target = yield* resolveTarget(input, project);193+ const alreadyLinked = yield* engine194+ .dispatch({195+ type: "thread.pull-request.link",196+ commandId: yield* commandId("mcp-pr-link", thread.id),197+ threadId: thread.id,198+ host: target.host,199+ repository: target.repository,200+ number: target.number,201+ url: target.url,202+ source: "agent",203+ })204+ .pipe(205+ Effect.as(false),206+ // The decider rejects a second link of the same PR; for the agent that is207+ // the outcome it asked for, not an error.208+ Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.succeed(true)),apps/server/src/mcp/toolkits/pullRequests/handlers.ts lines 229 to 229OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +209,21 @@209+ Effect.catchCause(dispatchFailure("link")),210+ );211+ return { ...target, alreadyLinked };212+ }),213+ unlink_pull_request: (input) =>214+ Effect.gen(function* () {215+ const thread = yield* requireThread("unlink");216+ const project = yield* projectOf(thread, "unlink");217+ const target = yield* resolveTarget(input, project);218+ const wasLinked = yield* engine219+ .dispatch({220+ type: "thread.pull-request.unlink",221+ commandId: yield* commandId("mcp-pr-unlink", thread.id),222+ threadId: thread.id,223+ host: target.host,224+ repository: target.repository,225+ number: target.number,226+ })227+ .pipe(228+ Effect.as(true),229+ Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.succeed(false)),apps/server/src/mcp/toolkits/pullRequests/tools.ts lines 74 to 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+) {60+ override get message(): string {61+ return this.detail;62+ }63+}64+65+export class PullRequestThreadNotFoundError extends Schema.TaggedError<PullRequestThreadNotFoundError>()(66+ "PullRequestThreadNotFoundError",67+ { threadId: Schema.String },68+) {69+ override get message(): string {70+ return `Thread ${this.threadId} was not found.`;71+ }72+}73+74+export class PullRequestLinkFailedError extends Schema.TaggedError<PullRequestLinkFailedError>()(75+ "PullRequestLinkFailedError",76+ { operation: Schema.Literals(["link", "unlink", "list"]), detail: Schema.String },77+) {78+ override get message(): string {79+ return `Could not ${this.operation} the pull request: ${this.detail}`;
- apps/web/src/components/pullRequest/LinkBranchPullRequestButton.tsx line 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";8+9+/** Adopts a branch discovery as a durable link, even after the thread changes branches. */10+export function LinkBranchPullRequestButton({11+ threadRef,12+ url,13+}: {14+ threadRef: ScopedThreadRef;15+ url: string;16+}) {17+ const linking = usePullRequestLinking(threadRef.environmentId);18+ const [pending, setPending] = useState(false);19+ if (!linking.canLink(url)) return null;20+ return (21+ <Tooltip>22+ <TooltipTrigger23+ render={24+ <Button25+ size="icon-xs"26+ variant="ghost"27+ className="size-4 shrink-0 text-muted-foreground"apps/web/src/components/pullRequest/PullRequestStackMap.tsx line 69OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +49,21 @@49+ className={cn(50+ "inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-0 font-mono tabular-nums",51+ isCurrent52+ ? "border-foreground/40 bg-accent text-foreground"53+ : "border-border/70 hover:bg-accent/60",54+ )}55+ >56+ <presentation.Icon aria-hidden className={cn("size-3", presentation.toneClassName)} />#57+ {layer.number}58+ </span>59+ );60+ return (61+ <span key={layer.number} className="inline-flex shrink-0 items-center gap-1">62+ <span aria-hidden className="text-muted-foreground/50">63+ →64+ </span>65+ <Tooltip>66+ <TooltipTrigger67+ render={68+ onSelect && !isCurrent ? (69+ <button type="button" onClick={() => onSelect(layer.number)} />apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx line 1432OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1393,3 +1425,8 @@13931425 >13941426 {detail && statePresentation ? (13951427 <>1428+ {onBack ? (1429+ <Tooltip>1430+ <TooltipTrigger1431+ render={1432+ <button
- apps/web/src/components/Sidebar.tsx line 1517OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1461,2 +1498,20 @@1498+ cn(1499+ // Sidebar chrome follows the interface font; tabular digits keep the number from1500+ // reflowing as PR states stream in. A border rather than text-decoration, so the line1501+ // runs under the glyph as well as the number.1502+ "inline-flex shrink-0 cursor-pointer items-center gap-0.5 border-b border-transparent text-xs tabular-nums hover:border-current",1503+ variant === "slim" && variantAction === "unsettle"1504+ ? props.isActive1505+ ? "text-secondary-label"1506+ : cn("text-secondary-label transition-colors", settledPrHoverColorClass(state))1507+ : colorClass,1508+ );1509+ const handlePrStackClick = useCallback(() => {1510+ useRightPanelStore.getState().open(threadRef, "pull-requests");1511+ if (!props.isActive) onThreadActivate(threadRef);1512+ }, [onThreadActivate, props.isActive, threadRef]);14611513 const prBadge =1462- prStatus && pr ? (1514+ prBadgeShape?.kind === "stack" ? (1515+ // A stack is one thing with N layers; naming one of them would misrepresent it, so the1516+ // badge counts layers and opens the thread's pull-requests surface.1517+ <button
- apps/server/src/orchestration/Layers/ProjectionPipeline.ts lines 37 to 37OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -32,3 +34,4 @@3234 type ProjectionThreadProposedPlan,3335 ProjectionThreadProposedPlanRepository,3436 } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";37+import { ProjectionThreadPullRequestRepository } from "../../persistence/Services/ProjectionThreadPullRequests.ts";
- apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts line 61OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -54,3 +58,4 @@5458 import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";5559 import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";5660 import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";61+import { ProjectionThreadPullRequest } from "../../persistence/Services/ProjectionThreadPullRequests.ts";
- apps/server/src/mcp/toolkits/pullRequests/tools.ts lines 55 to 58OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+ description:39+ "Repository path below the host, for example owner/repo. Required with number when url is omitted.",40+ }),41+ ),42+ number: Schema.optional(43+ PositiveInt.annotate({44+ description: "Pull request number. Required with repository when url is omitted.",45+ }),46+ ),47+ host: Schema.optional(48+ TrimmedNonEmptyString.annotate({49+ description:50+ "Host the repository lives on, for example github.com. Defaults to the host of this thread's project.",51+ }),52+ ),53+});54+export type PullRequestTargetInput = typeof PullRequestTargetInput.Type;55+56+export class PullRequestTargetError extends Schema.TaggedError<PullRequestTargetError>()(57+ "PullRequestTargetError",58+ { detail: Schema.String },
- apps/server/src/persistence/Layers/ProjectionThreadPullRequests.ts lines 27 to 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+import * as SqlClient from "effect/unstable/sql/SqlClient";8+import * as SqlSchema from "effect/unstable/sql/SqlSchema";9+10+import { toPersistenceSqlError } from "../Errors.ts";11+import {12+ DeleteProjectionThreadPullRequestInput,13+ DeleteProjectionThreadPullRequestsBySourceInput,14+ DeleteProjectionThreadPullRequestsInput,15+ ListProjectionThreadPullRequestsByPullRequestInput,16+ ListProjectionThreadPullRequestsInput,17+ ProjectionThreadPullRequest,18+} from "../Services/ProjectionThreadPullRequests.ts";19+20+const ProjectionThreadPullRequestDbRow = ProjectionThreadPullRequest.mapFields(21+ Struct.assign({22+ snapshot: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestSnapshot)),23+ stack: Schema.NullOr(Schema.fromJsonString(ThreadPullRequestStack)),24+ }),25+);26+27+const makeProjectionThreadPullRequestRepository = Effect.gen(function* () {
- apps/server/src/orchestration/decider.ts lines 906 to 910OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -876,3 +898,13 @@876898 command,877899 threadId: command.threadId,878900 });901+ // Old clients only see the derived single link. Unlink that request through902+ // the same command path as modern clients, including stack dismissal, while903+ // retaining other links they cannot see. Historical metadata events still replay unchanged.904+ const currentPullRequest = resolveThreadCurrentPullRequestLink(thread.pullRequests);905+ if (command.linkedPullRequest === null && currentPullRequest !== null) {906+ const { linkedPullRequest: _linkedPullRequest, ...metadata } = command;907+ return yield* decideCommandSequence({908+ readModel,909+ commands: [910+ metadata,apps/server/src/orchestration/Layers/ProjectionPipeline.ts lines 883 to 888Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -822,0 +882,21 @@882+ });883+ yield* projectionThreadRepository.upsert({884+ ...existingRow.value,885+ updatedAt: event.payload.updatedAt,886+ });887+ return;888+ }889+890+ case "thread.pull-request-unlinked": {891+ const existingRow = yield* projectionThreadRepository.getById({892+ threadId: event.payload.threadId,893+ });894+ if (Option.isNone(existingRow)) {895+ return;896+ }897+ yield* projectionThreadPullRequestRepository.delete({898+ threadId: event.payload.threadId,899+ host: event.payload.host,900+ repository: event.payload.repository,901+ number: event.payload.number,902+ });apps/server/src/orchestration/projector.ts lines 179 to 180Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -103,0 +154,21 @@154+ linked: ThreadLinkedPullRequest,155+): string {156+ const canonicalHost = project?.repositoryIdentity?.canonicalKey.split("/")[0];157+ if (canonicalHost) return canonicalHost.toLowerCase();158+ try {159+ return new URL(linked.url).hostname.toLowerCase();160+ } catch {161+ return "unknown";162+ }163+}164+165+function legacyLinkToPullRequests(166+ thread: Pick<OrchestrationThread, "pullRequests">,167+ project: OrchestrationProject | undefined,168+ linked: ThreadLinkedPullRequest | null,169+ linkedAt: string,170+): ReadonlyArray<ThreadPullRequestLink> {171+ // The legacy field held one user-chosen link, so null clears exactly the172+ // manual ones and leaves created/agent/stack links alone.173+ const withoutManual = thread.pullRequests.filter((entry) => entry.source !== "manual");174+ if (linked === null) return withoutManual;apps/server/src/pullRequest/linkedThreads.ts lines 18 to 19Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,15 @@1+import {2+ PullRequestLinkedThreadsResult,3+ PullRequestOperationError,4+ type ThreadPullRequestKey,5+} from "@t3tools/contracts";6+import * as Effect from "effect/Effect";7+import * as Schema from "effect/Schema";8+import * as SqlClient from "effect/unstable/sql/SqlClient";9+10+export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreads")(11+ function* (key: ThreadPullRequestKey) {12+ const sql = yield* SqlClient.SqlClient;13+ const threads = yield* sql`14+ SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,15+ t.archived_at AS "archivedAt"apps/server/src/pullRequest/PullRequestService.ts lines 649 to 652Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -647,4 +642,7 @@647642 if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);648643 else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot);649644 }650- const key = listCursorKey(host, repository);645+ const key = listCursorKey(646+ host,647+ kind === "azure-devops" ? identity.canonicalKey : repository,648+ );apps/web/src/components/RightPanelTabs.tsx lines 775 to 780OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -703 +760,21 @@760+ const threads = useThreadShells();761+ const project = projects.find(762+ (entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId,763+ );764+ const identity = project?.repositoryIdentity;765+ const host =766+ surface.host ??767+ (identity?.provider768+ ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)769+ : null);770+ const configs = useServerConfigs();771+ const capabilities =703772 resolvedEnvironmentId === null773+ ? undefined774+ : configs.get(resolvedEnvironmentId)?.environment.capabilities;775+ const linked =776+ capabilities?.threadPullRequests === true777+ ? resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)778+ : undefined;779+ const detail = useEnvironmentQuery(780+ resolvedEnvironmentId === null || capabilities?.pullRequests !== true || linked !== undefined
- @@ -0,0 +35,21 @@35+ ) {36+ return null;37+ }38+ return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;39+}40+41+function EnabledPullRequestThreadLinks({42+ environmentId,43+ reference,44+ url,45+ threadRef,46+ display,47+ onPickerOpenChange,48+}: PullRequestThreadLinksProps) {49+ const parsed = parseChangeRequestUrl(url);50+ const currentThreadRef = threadRef?.environmentId === environmentId ? threadRef : null;51+ const thread = useThreadShell(currentThreadRef);52+ const linking = usePullRequestLinking(environmentId);53+ const linkedHere = linking.isLinked(thread, url);54+ const relations = useEnvironmentQuery(55+ linking.mode === "multiple" && display !== "menu-item"
juliusmarminge merged thisafb8489
juliusmarminge closed this
Sign in to join this conversation.








Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
e16b8b0· PR result:09ae095· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.