Support gh pr checkout pull request references (#1457)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-03-27 00:08:45 -07:00
1 parent 02989fe600
commit d8a485ea7e
8 files changed
+324 -17

No files matched your search

@@ -6,6 +6,7 @@ import {
resolveBranchSelectionTarget,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
shouldIncludeBranchPickerItem,
} from "./BranchToolbar.logic";
describe("resolveDraftEnvModeAfterBranchChange", () => {
@@ -267,3 +268,38 @@ describe("resolveBranchSelectionTarget", () => {
});
});
});
describe("shouldIncludeBranchPickerItem", () => {
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "__checkout_pull_request__:1359",
normalizedQuery: "gh pr checkout 1359",
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
}),
).toBe(true);
});
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "__create_new_branch__:feature/demo",
normalizedQuery: "feature/demo",
createBranchItemValue: "__create_new_branch__:feature/demo",
checkoutPullRequestItemValue: null,
}),
).toBe(true);
});
it("still filters ordinary branch items by query text", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "main",
normalizedQuery: "gh pr checkout 1359",
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
}),
).toBe(false);
});
});
@@ -123,3 +123,26 @@ export function resolveBranchSelectionTarget(input: {
reuseExistingWorktree: false,
};
}
export function shouldIncludeBranchPickerItem(input: {
itemValue: string;
normalizedQuery: string;
createBranchItemValue: string | null;
checkoutPullRequestItemValue: string | null;
}): boolean {
const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
if (normalizedQuery.length === 0) {
return true;
}
if (createBranchItemValue && itemValue === createBranchItemValue) {
return true;
}
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
return true;
}
return itemValue.toLowerCase().includes(normalizedQuery);
}
@@ -28,6 +28,7 @@ import {
EnvMode,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
shouldIncludeBranchPickerItem,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
@@ -134,11 +135,20 @@ export function BranchToolbarBranchSelector({
() =>
normalizedDeferredBranchQuery.length === 0
? branchPickerItems
: branchPickerItems.filter((itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery);
}),
[branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery],
: branchPickerItems.filter((itemValue) =>
shouldIncludeBranchPickerItem({
itemValue,
normalizedQuery: normalizedDeferredBranchQuery,
createBranchItemValue,
checkoutPullRequestItemValue,
}),
),
[
branchPickerItems,
checkoutPullRequestItemValue,
createBranchItemValue,
normalizedDeferredBranchQuery,
],
);
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
@@ -56,6 +56,7 @@ interface TestFixture {
let fixture: TestFixture;
const wsRequests: WsRequestEnvelope["body"][] = [];
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
@@ -433,6 +434,10 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
}
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const customResult = customWsRpcResolver?.(body);
if (customResult !== undefined) {
return customResult;
}
const tag = body._tag;
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
return fixture.snapshot;
@@ -767,9 +772,11 @@ async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
configureFixture?: (fixture: TestFixture) => void;
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
}): Promise<MountedChatView> {
fixture = buildFixture(options.snapshot);
options.configureFixture?.(fixture);
customWsRpcResolver = options.resolveRpc ?? null;
await setViewport(options.viewport);
await waitForProductionStyles();
@@ -795,6 +802,7 @@ async function mountChatView(options: {
await waitForLayout();
const cleanup = async () => {
customWsRpcResolver = null;
await screen.unmount();
host.remove();
};
@@ -854,6 +862,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
localStorage.clear();
document.body.innerHTML = "";
wsRequests.length = 0;
customWsRpcResolver = null;
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
@@ -869,6 +878,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
afterEach(() => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
@@ -1357,6 +1367,154 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("runs setup scripts after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitResolvePullRequest) {
return {
pullRequest: {
number: 1359,
title: "Add thread archiving and settings navigation",
url: "https://github.com/pingdotgg/t3code/pull/1359",
baseBranch: "main",
headBranch: "archive-settings-overhaul",
state: "open",
},
};
}
if (body._tag === WS_METHODS.gitPreparePullRequestThread) {
return {
pullRequest: {
number: 1359,
title: "Add thread archiving and settings navigation",
url: "https://github.com/pingdotgg/t3code/pull/1359",
baseBranch: "main",
headBranch: "archive-settings-overhaul",
state: "open",
},
branch: "archive-settings-overhaul",
worktreePath: "/repo/worktrees/pr-1359",
};
}
return undefined;
},
});
try {
const branchButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "main",
) as HTMLButtonElement | null,
"Unable to find branch selector button.",
);
branchButton.click();
const branchInput = await waitForElement(
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
"Unable to find branch search input.",
);
branchInput.focus();
await page.getByPlaceholder("Search branches...").fill("1359");
const checkoutItem = await waitForElement(
() =>
Array.from(document.querySelectorAll("span")).find(
(element) => element.textContent?.trim() === "Checkout Pull Request",
) as HTMLSpanElement | null,
"Unable to find checkout pull request option.",
);
checkoutItem.click();
const worktreeButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Worktree",
) as HTMLButtonElement | null,
"Unable to find Worktree button.",
);
worktreeButton.click();
await vi.waitFor(
() => {
const prepareRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.gitPreparePullRequestThread,
);
expect(prepareRequest).toMatchObject({
_tag: WS_METHODS.gitPreparePullRequestThread,
cwd: "/repo/project",
reference: "1359",
mode: "worktree",
});
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: expect.any(String),
cwd: "/repo/worktrees/pr-1359",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
},
});
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const writeRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
);
expect(writeRequest).toMatchObject({
_tag: WS_METHODS.terminalWrite,
threadId: expect.any(String),
data: "bun install\r",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
+63 -4
View File
@@ -239,6 +239,12 @@ interface ChatViewProps {
threadId: ThreadId;
}
interface PendingPullRequestSetupRequest {
threadId: ThreadId;
worktreePath: string;
scriptId: string;
}
export default function ChatView({ threadId }: ChatViewProps) {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
@@ -350,6 +356,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
useState<PendingPullRequestSetupRequest | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -527,14 +535,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
params: { threadId: storedDraftThread.threadId },
});
}
return;
return storedDraftThread.threadId;
}
const activeDraftThread = getDraftThread(threadId);
if (!isServerThread && activeDraftThread?.projectId === activeProject.id) {
setDraftThreadContext(threadId, input);
setProjectDraftThreadId(activeProject.id, threadId, input);
return;
return threadId;
}
clearProjectDraftThreadId(activeProject.id);
@@ -549,6 +557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
to: "/$threadId",
params: { threadId: nextThreadId },
});
return nextThreadId;
},
[
activeProject,
@@ -565,13 +574,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handlePreparedPullRequestThread = useCallback(
async (input: { branch: string; worktreePath: string | null }) => {
await openOrReuseProjectDraftThread({
const targetThreadId = await openOrReuseProjectDraftThread({
branch: input.branch,
worktreePath: input.worktreePath,
envMode: input.worktreePath ? "worktree" : "local",
});
const setupScript =
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
if (targetThreadId && input.worktreePath && setupScript) {
setPendingPullRequestSetupRequest({
threadId: targetThreadId,
worktreePath: input.worktreePath,
scriptId: setupScript.id,
});
} else {
setPendingPullRequestSetupRequest(null);
}
},
[openOrReuseProjectDraftThread],
[activeProject, openOrReuseProjectDraftThread],
);
useEffect(() => {
@@ -1418,6 +1438,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
terminalState.terminalIds,
],
);
useEffect(() => {
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
return;
}
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
return;
}
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
return;
}
const setupScript =
activeProject.scripts.find(
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
) ?? null;
setPendingPullRequestSetupRequest(null);
if (!setupScript) {
return;
}
void runProjectScript(setupScript, {
cwd: pendingPullRequestSetupRequest.worktreePath,
worktreePath: pendingPullRequestSetupRequest.worktreePath,
rememberAsLastInvoked: false,
}).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to run setup script.",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, [
activeProject,
activeThread,
activeThreadId,
pendingPullRequestSetupRequest,
runProjectScript,
]);
const persistProjectScripts = useCallback(
async (input: {
projectId: ProjectId;
@@ -153,9 +153,9 @@ export function PullRequestThreadDialog({
const validationMessage = !referenceDirty
? null
: reference.trim().length === 0
? "Paste a GitHub pull request URL or enter 123 / #123."
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
: parsedReference === null
? "Use a GitHub pull request URL, 123, or #123."
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
: null;
const errorMessage =
validationMessage ??
@@ -191,7 +191,7 @@ export function PullRequestThreadDialog({
<span className="text-xs font-medium text-foreground">Pull request</span>
<Input
ref={referenceInputRef}
placeholder="https://github.com/owner/repo/pull/42 or #42"
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
value={reference}
onChange={(event) => {
setReferenceDirty(true);
+14
View File
@@ -17,6 +17,20 @@ describe("parsePullRequestReference", () => {
expect(parsePullRequestReference("#42")).toBe("#42");
});
it("accepts gh pr checkout commands with raw numbers", () => {
expect(parsePullRequestReference("gh pr checkout 42")).toBe("42");
});
it("accepts gh pr checkout commands with #number references", () => {
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
});
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
expect(
parsePullRequestReference("gh pr checkout https://github.com/pingdotgg/t3code/pull/42"),
).toBe("https://github.com/pingdotgg/t3code/pull/42");
});
it("rejects non-pull-request input", () => {
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
});
+12 -5
View File
@@ -1,6 +1,7 @@
const GITHUB_PULL_REQUEST_URL_PATTERN =
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
export function parsePullRequestReference(input: string): string | null {
const trimmed = input.trim();
@@ -8,14 +9,20 @@ export function parsePullRequestReference(input: string): string | null {
return null;
}
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(trimmed);
if (urlMatch?.[1]) {
return trimmed;
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
if (normalizedInput.length === 0) {
return null;
}
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(trimmed);
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
if (urlMatch?.[1]) {
return normalizedInput;
}
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
if (numberMatch?.[1]) {
return trimmed.startsWith("#") ? trimmed : numberMatch[1];
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
}
return null;