feat(prs): navigate, merge and rebase GitHub stacks (#10875)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-09 15:50:59 -07:00
1 parent f0401c6290
commit de37964db2
53 files changed
+3106 -466

No files matched your search

@@ -1,4 +1,4 @@
import { EnvironmentId, ProjectId, WS_METHODS } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, WS_METHODS, type PullRequestStack } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Latch from "effect/Latch";
@@ -19,7 +19,10 @@ import * as EnvironmentRegistry from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import type { RpcSession } from "../rpc/session.ts";
import { createPullRequestEnvironmentAtoms } from "./pullRequests.ts";
import {
createPullRequestEnvironmentAtoms,
createPullRequestStackAtomFamily,
} from "./pullRequests.ts";
import { PullRequestDiffLoader } from "./pullRequestDiffHttp.ts";
import { executeAtomQuery } from "./runtime.ts";
@@ -80,7 +83,7 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (client: WsRpcPro
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
Effect.sync(() => registry.dispose()),
);
return { atoms, registry };
return { runtime, atoms, registry };
});
it.effect("keeps concurrent diff file reads on different hosts separate", () =>
@@ -212,3 +215,67 @@ it.effect("refreshes pull request activity after a comment is updated", () =>
}),
),
);
it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
Effect.scoped(
Effect.gen(function* () {
const refreshEvents = yield* PubSub.unbounded<number>();
let state: "closed" | "open" = "closed";
let headSha = "old-head";
const client = {
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
[WS_METHODS.pullRequestsStack]: () =>
Effect.sync(
() =>
({
id: "stack-1",
number: 1,
url: "https://github.com/acme/web/pull/1",
base: "main",
layers: [
{
number: 1,
headBranch: "feature",
headSha,
state,
isDraft: false,
},
],
}) satisfies PullRequestStack,
),
} as unknown as WsRpcProtocolClient;
const { runtime, registry } = yield* makeTestRuntime(client);
const stacks = createPullRequestStackAtomFamily(runtime);
const stack = stacks({
environmentId: TARGET.environmentId,
input: {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 1,
},
});
const unmount = registry.mount(stack);
yield* Effect.addFinalizer(() => Effect.sync(unmount));
yield* Effect.promise(() => executeAtomQuery(registry, stack));
expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
state = "open";
registry.refresh(stack);
expect(
(yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
?.state,
).toBe("open");
const refreshed = Latch.makeUnsafe();
const stop = registry.subscribe(stack, (result) => {
if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
refreshed.openUnsafe();
}
});
yield* Effect.addFinalizer(() => Effect.sync(stop));
headSha = "new-head";
yield* PubSub.publish(refreshEvents, 1);
yield* refreshed.await;
expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
}),
),
);
@@ -63,12 +63,14 @@ 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>,
refreshes = createPullRequestRefreshAtomFamily(runtime),
) {
return createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:stack",
tag: WS_METHODS.pullRequestsStack,
staleTimeMs: 60_000,
idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
});
}
@@ -571,3 +571,79 @@ describe("resolveViewedImageAsset", () => {
expect(resolveViewedImageAsset("https://example.com/logo.png", { threadId })).toBeNull();
});
});
describe("pull request tool presentation", () => {
it.each([
"mcp__t3-code__link_pull_request",
"mcp__t3_code__link_pull_request",
"T3-code · link_pull_request",
"t3code/link_pull_request",
"link_pull_request",
])("recognizes the native linking tool: %s", (label) => {
const entry = { label, tone: "tool" as const, toolLifecycleStatus: "completed" };
expect(resolveWorkEntryToolPresentation(entry)).toMatchObject({
displayName: "Linked a pull request",
icon: "pull-request",
});
expect(toolGroupAction(entry)).toBe("link-pr");
});
it.each([
["inProgress", "Linking PR #42"],
["completed", "Linked PR #42"],
["failed", "Failed to link PR #42"],
["declined", "Declined to link PR #42"],
["stopped", "Stopped linking PR #42"],
])("describes the target and %s status", (toolLifecycleStatus, displayName) => {
expect(
resolveWorkEntryToolPresentation({
label: "MCP tool call",
toolTitle: "Custom title",
toolLifecycleStatus,
toolData: {
server: "t3-code",
tool: "link_pull_request",
arguments: { url: "https://github.com/acme/web/pull/42" },
},
})?.displayName,
).toBe(displayName);
});
it("recognizes unlink targets supplied as repository and number", () => {
expect(
resolveWorkEntryToolPresentation({
label: "MCP tool call",
toolLifecycleStatus: "completed",
toolData: {
toolName: "mcp__t3-code__unlink_pull_request",
rawInput: { repository: "acme/web", number: 42 },
},
}),
).toMatchObject({ displayName: "Unlinked PR #42", icon: "pull-request", action: "unlink-pr" });
});
it("summarizes native PR work separately from ordinary tools and integration metadata", () => {
const link: WorkLogPresentationEntry = {
label: "T3-code · link_pull_request",
tone: "tool",
itemType: "mcp_tool_call",
toolLifecycleStatus: "completed",
toolSource: { key: "t3-code", name: "T3 Code", kind: "integration" },
};
const list: WorkLogPresentationEntry = {
...link,
label: "T3-code · list_thread_pull_requests",
};
expect(summarizeToolGroup([link, link, list])).toBe(
"Linked 2 pull requests and checked linked pull requests",
);
expect(summarizeToolGroup([{ ...link, label: "T3-code · unlink_pull_request" }])).toBe(
"Unlinked 1 pull request",
);
expect(toolGroupSummaryKind([link, link, list])).toBe("pull-request");
expect(summarizeToolGroup([list, list])).toBe("Checked linked pull requests 2 times");
expect(
resolveWorkEntryToolPresentation({ label: "mcp__another-server__link_pull_request" }),
).toBeNull();
});
});
@@ -8,6 +8,7 @@ import {
} from "@t3tools/contracts";
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
export function isWorktreeSetupActivity(kind: string): boolean {
@@ -36,6 +37,9 @@ export interface WorkLogPresentationEntry {
}
export type ToolGroupAction =
| "link-pr"
| "unlink-pr"
| "list-prs"
| "read"
| "edit"
| "command"
@@ -46,6 +50,7 @@ export type ToolGroupAction =
| "update";
export type ToolGroupSummaryKind =
| "pull-request"
| ToolGroupAction
| "dynamic-tool"
| "agent-tool"
@@ -60,6 +65,9 @@ const T3_MCP_TOOL_LABELS: Record<
string,
readonly [action: string, running: string, completed: string, detail: string]
> = {
link_pull_request: ["Link", "Linking", "Linked", "a pull request"],
unlink_pull_request: ["Unlink", "Unlinking", "Unlinked", "a pull request"],
list_thread_pull_requests: ["Check", "Checking", "Checked", "linked pull requests"],
orchestrator_capabilities: ["Get", "Getting", "Got", "orchestration capabilities"],
delegate_task: ["Delegate", "Delegating", "Delegated", "a child task"],
task_status: ["Get", "Getting", "Got", "delegated task status"],
@@ -98,7 +106,17 @@ const T3_MCP_TOOL_LABELS: Record<
preview_recording_stop: ["Stop", "Stopping", "Stopped", "recording the preview browser"],
};
function resolveT3McpToolPresentation(value: string | undefined, status: string | undefined) {
const PR_TOOL_ACTIONS: Readonly<Record<string, ToolGroupAction>> = {
link_pull_request: "link-pr",
unlink_pull_request: "unlink-pr",
list_thread_pull_requests: "list-prs",
};
function resolveT3McpToolPresentation(
value: string | undefined,
status: string | undefined,
data?: unknown,
) {
if (!value) return null;
const name = normalizeCompactToolLabel(value).replace(
/^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,
@@ -120,9 +138,29 @@ function resolveT3McpToolPresentation(value: string | undefined, status: string
? `Stopped ${running.toLowerCase()}`
: running;
const actionKind = Object.hasOwn(PR_TOOL_ACTIONS, name) ? PR_TOOL_ACTIONS[name] : undefined;
const payload = asRecord(data);
const input =
asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
const urlTarget = typeof input?.url === "string" ? parseChangeRequestUrl(input.url) : null;
const number = urlTarget?.number ?? input?.number;
const target =
actionKind !== undefined &&
actionKind !== "list-prs" &&
typeof number === "number" &&
Number.isSafeInteger(number) &&
number > 0
? `PR #${number}`
: detail;
return {
displayName: `${verb} ${detail}`,
icon: name.startsWith("preview_") ? ("browser" as const) : ("t3-code" as const),
displayName: `${verb} ${target}`,
icon:
actionKind !== undefined
? ("pull-request" as const)
: name.startsWith("preview_")
? ("browser" as const)
: ("t3-code" as const),
...(actionKind === undefined ? {} : { action: actionKind }),
};
}
@@ -147,16 +185,16 @@ export function resolveWorkEntryToolPresentation(
"tool" in data &&
typeof data.tool === "string"
) {
return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status);
return resolveT3McpToolPresentation(`${data.server}.${data.tool}`, status, data);
}
if ("toolName" in data && typeof data.toolName === "string") {
return resolveT3McpToolPresentation(data.toolName, status);
return resolveT3McpToolPresentation(data.toolName, status, data);
}
}
return (
resolveT3McpToolPresentation(entry.toolTitle, status) ??
resolveT3McpToolPresentation(entry.label, status)
resolveT3McpToolPresentation(entry.toolTitle, status, data) ??
resolveT3McpToolPresentation(entry.label, status, data)
);
}
@@ -410,7 +448,9 @@ export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupActio
) {
return "update";
}
if (resolveWorkEntryToolPresentation(entry)?.icon === "browser") return "browser";
const presentation = resolveWorkEntryToolPresentation(entry);
if (presentation?.action !== undefined) return presentation.action;
if (presentation?.icon === "browser") return "browser";
if (
entry.requestKind === "file-read" ||
entry.itemType === "image_view" ||
@@ -504,6 +544,14 @@ function toolGroupActionCount(
function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
switch (action) {
case "link-pr":
return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
case "unlink-pr":
return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
case "list-prs":
return count === 1
? "Checked linked pull requests"
: `Checked linked pull requests ${count} times`;
case "read":
return `Read ${count} ${count === 1 ? "file" : "files"}`;
case "edit":
@@ -528,7 +576,7 @@ export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEnt
const sources = new Map<string, ToolActivitySource>();
const groupedEntries = new Map<ToolGroupAction, WorkLogPresentationEntry[]>();
for (const entry of summaryEntries) {
if (entry.toolSource) {
if (entry.toolSource && resolveWorkEntryToolPresentation(entry)?.icon !== "pull-request") {
sources.set(entry.toolSource.key, entry.toolSource);
continue;
}
@@ -601,6 +649,11 @@ export function omitSupersededLifecycleMarkers<T>(
export function toolGroupSummaryKind(
entries: ReadonlyArray<WorkLogPresentationEntry>,
): ToolGroupSummaryKind {
if (
entries.length > 0 &&
entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
)
return "pull-request";
const actions = new Set(entries.map(toolGroupAction));
if (actions.size !== 1) return "mixed";