From 21e270c2cffc3b11950eb2c6452aef62d4dac800 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Sat, 7 Nov 2026 15:31:31 -0800 Subject: [PATCH 1/7] fix(web): seed checkout task before preparation completes --- .../pullRequest/PullRequestDetailPanel.tsx | 118 ++------- .../runPullRequestCheckoutHandoff.test.ts | 140 +++++++++++ .../pullRequest/usePullRequestActions.ts | 232 +++++++++++------- 3 files changed, 312 insertions(+), 178 deletions(-) create mode 100644 apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index a4ce4ae7431e..e3e61e160439 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -9,10 +9,7 @@ import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pu import { useAtomValue } from "@effect/atom-react"; import { usePullRequestStack } from "~/state/usePullRequestStack"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, @@ -56,10 +53,10 @@ import { isCommandPaletteOpen } from "~/commandPaletteBus"; import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings"; import { primaryServerKeybindingsAtom } from "~/state/server"; import { + runPullRequestCheckoutHandoff, usePullRequestDefaultMergeMethodResolver, writeHandoffToComposer, } from "./usePullRequestActions"; -import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast"; import { usePreparePullRequestThreadAction } from "~/state/sourceControlActions"; import { cn } from "~/lib/utils"; import { readLocalApi } from "~/localApi"; @@ -137,7 +134,6 @@ import { pullRequestFindingKey, pullRequestHandoffLabels, PULL_REQUEST_MERGE_METHOD_LABELS, - checkoutFailureDescription, readableFailure, resolvePullRequestReferenceHost, resolvePullRequestPrimaryControl, @@ -971,99 +967,37 @@ export function PullRequestDetailPanel({ return; } setHandoff(kind); - const toastId = toastManager.add({ - type: "loading", - title: `Preparing the ${terminology.singular} checkout...`, - }); const projectRef = scopeProjectRef( actingEnvironmentId, acting?.projectId ?? handoffSummary.projectId, ); - // Checkout setup requires the thread to exist first. - const opened = await newThread(projectRef).then( - (session) => session, - () => null, - ); - if (opened === null) { - setHandoff(null); - toastManager.update(toastId, { - type: "error", - title: "Could not open a thread for the checkout", - description: "Try again from the project, or open a thread first.", - }); - return; - } - const prepared = await prepareThread.run({ - reference: handoffSummary.url, + await runPullRequestCheckoutHandoff({ + terminology, mode, - threadId: opened.threadId, - }); - if (prepared._tag === "Failure") { - setHandoff(null); - toastManager.update(toastId, { - type: "error", - title: `Could not prepare the ${terminology.singular} checkout`, - description: checkoutFailureDescription( - isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared), + task, + clearHandoff: () => setHandoff(null), + // Checkout setup requires the thread to exist first. + openThread: () => + newThread(projectRef).then( + (session) => session, + () => null, + ), + prepare: (threadId) => + prepareThread.run({ + reference: handoffSummary.url, + mode, + threadId, + }), + pointThread: (prepared) => + newThread(projectRef, { + branch: prepared.branch, + worktreePath: prepared.worktreePath, + envMode: prepared.worktreePath === null ? "local" : "worktree", + }).then( + (session) => session !== null, + () => false, ), - }); - return; - } - const pointed = await newThread(projectRef, { - branch: prepared.value.branch, - worktreePath: prepared.value.worktreePath, - envMode: prepared.value.worktreePath === null ? "local" : "worktree", - }).then( - (session) => session, - () => null, - ); - if (pointed === null) { - setHandoff(null); - // Sending after failed rebinding would use the previous checkout. - toastManager.update(toastId, { - type: "error", - title: "Checked out, but the thread stayed where it was", - description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, - }); - return; - } - // The draft carries the pull request until its first send makes it a thread, which links it. - useComposerDraftStore.getState().setDraftThreadContext(pointed.draftId, { - checkoutPullRequest: { - url: prepared.value.pullRequest.url, - branch: prepared.value.branch, - }, }); - setHandoff(null); - if (task === null) { - toastManager.update( - toastId, - prepared.value.isOnPullRequestHead - ? { - type: "success", - title: mode === "local" ? "Checked out here" : "Checked out", - description: - mode === "local" - ? `This repository is on the ${terminology.singular}'s branch, with a thread open on it.` - : `The ${terminology.singular} is in its own worktree, with a thread open on it.`, - } - : offHeadPullRequestCheckoutToast(terminology), - ); - return; - } - // The task goes on the checkout draft: if the user typed into `opened` while the - // checkout ran, that is no longer the draft the user is looking at. - await openThreadWithTask(projectRef, task, pointed); - toastManager.update( - toastId, - prepared.value.isOnPullRequestHead - ? { - type: "success", - title: "Checkout ready", - description: "The task is in the composer. Read it over, then send.", - } - : offHeadPullRequestCheckoutToast(terminology), - ); }; const askAboutPullRequest = () => { diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts new file mode 100644 index 000000000000..109ab9e21de2 --- /dev/null +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -0,0 +1,140 @@ +import { AsyncResult } from "effect/reactivity"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; +import { expect, it, vi } from "vite-plus/test"; + +import type { PullRequestCheckoutPrepared } from "./usePullRequestActions"; + +const state = vi.hoisted(() => ({ + toastId: "checkout-toast", + add: vi.fn<(options: unknown) => string>(() => "checkout-toast"), + update: vi.fn(), + setPrompt: vi.fn(), + setReviewComments: vi.fn(), + getComposerDraft: vi.fn(() => ({ prompt: "", reviewComments: [] })), +})); + +vi.mock("../ui/toast", () => ({ + toastManager: { + add: state.add, + update: state.update, + }, +})); + +vi.mock("~/composerDraftStore", () => ({ + useComposerDraftStore: { + getState: () => ({ + getComposerDraft: state.getComposerDraft, + setPrompt: state.setPrompt, + setReviewComments: state.setReviewComments, + }), + }, +})); + +import { runPullRequestCheckoutHandoff } from "./usePullRequestActions"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +const terminology = sourceControlClients.get(undefined).changeRequest; + +type PreparedResult = AtomCommandResult; + +function reset() { + state.add.mockClear().mockReturnValue(state.toastId); + state.update.mockClear(); + state.setPrompt.mockClear(); + state.setReviewComments.mockClear(); + state.getComposerDraft.mockReturnValue({ prompt: "", reviewComments: [] }); +} + +it("puts the task in the composer before checkout finishes", async () => { + reset(); + const prepare = deferred(); + const clearHandoff = vi.fn(); + const pointThread = vi.fn(async () => true); + const pending = runPullRequestCheckoutHandoff({ + terminology, + mode: "worktree", + task: { prompt: "Fix the failing check" }, + clearHandoff, + openThread: async () => ({ draftId: "draft-1" as never, threadId: "thread-1" as never }), + prepare: () => prepare.promise, + pointThread, + }); + + await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); + expect(state.setPrompt).toHaveBeenCalledWith("draft-1", "Fix the failing check"); + expect(pointThread).not.toHaveBeenCalled(); + expect(state.add.mock.calls[0]?.[0]).toMatchObject({ + type: "loading", + actionProps: { children: "Cancel" }, + }); + + prepare.resolve( + AsyncResult.success({ + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }), + ); + await pending; + expect(pointThread).toHaveBeenCalledWith({ + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }); + expect(clearHandoff).toHaveBeenCalled(); + expect(state.update).toHaveBeenCalledWith( + state.toastId, + expect.objectContaining({ + type: "success", + title: "Checkout ready", + }), + ); +}); + +it("cancels preparation and keeps the prompt without pointing the thread", async () => { + reset(); + const prepare = deferred(); + const clearHandoff = vi.fn(); + const pointThread = vi.fn(async () => true); + const pending = runPullRequestCheckoutHandoff({ + terminology, + mode: "worktree", + task: { prompt: "Fix the failing check" }, + clearHandoff, + openThread: async () => ({ draftId: "draft-1" as never, threadId: "thread-1" as never }), + prepare: () => prepare.promise, + pointThread, + }); + + await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); + const toast = state.add.mock.calls[0]?.[0] as + | { actionProps?: { onClick?: () => void } } + | undefined; + toast?.actionProps?.onClick?.(); + expect(clearHandoff).toHaveBeenCalled(); + expect(state.update).toHaveBeenCalledWith( + state.toastId, + expect.objectContaining({ + type: "info", + title: "Cancelled checkout preparation", + }), + ); + + prepare.resolve( + AsyncResult.success({ + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }), + ); + await pending; + expect(pointThread).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 2cc81c488536..8bfb8092ec0a 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -3,6 +3,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { isAtomCommandInterrupted, squashAtomCommandFailure, + type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, @@ -13,6 +14,7 @@ import type { PullRequestRef, PullRequestSummary, ScopedThreadRef, + ThreadId, } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { @@ -258,6 +260,126 @@ export function writeHandoffToComposer( store.setReviewComments(target, next.reviewComments); } +export type PullRequestCheckoutPrepared = { + readonly branch: string; + readonly worktreePath: string | null; + readonly isOnPullRequestHead: boolean; +}; + +/** + * Opens a thread, puts any task in its composer before checkout finishes, then prepares the + * branch. Cancel skips applying the checkout; the prompt stays in the composer. + */ +export async function runPullRequestCheckoutHandoff(input: { + readonly terminology: ChangeRequestTerminology; + readonly mode: "worktree" | "local"; + readonly task: PullRequestThreadTask | null; + readonly openThread: () => Promise<{ draftId: DraftId; threadId: ThreadId } | null>; + readonly prepare: ( + threadId: ThreadId, + ) => Promise>; + readonly pointThread: (prepared: PullRequestCheckoutPrepared) => Promise; + readonly clearHandoff: () => void; +}): Promise { + // Explicit timeouts survive toast updates and would pin the result after loading. + let cancelled = false; + const toastId = toastManager.add({ + type: "loading", + title: `Preparing the ${input.terminology.singular} checkout...`, + timeout: 0, + actionProps: { + children: "Cancel", + onClick: () => { + if (cancelled) return; + cancelled = true; + input.clearHandoff(); + toastManager.update(toastId, { + type: "info", + title: "Cancelled checkout preparation", + description: + input.task === null + ? "The thread is still open." + : "The prompt is still in the composer.", + timeout: 8_000, + actionProps: undefined, + }); + }, + }, + data: { hideCopyButton: true }, + }); + + const opened = await input.openThread(); + if (cancelled) return; + if (opened === null) { + input.clearHandoff(); + toastManager.update(toastId, { + type: "error", + title: "Could not open a thread for the checkout", + description: "Try again from the project, or open a thread first.", + }); + return; + } + + // Seed the composer before checkout finishes so a long prepare still shows the task. + if (input.task !== null) { + writeHandoffToComposer(opened.draftId, input.task); + } + + const prepared = await input.prepare(opened.threadId); + if (cancelled) return; + if (prepared._tag === "Failure") { + input.clearHandoff(); + toastManager.update(toastId, { + type: "error", + title: `Could not prepare the ${input.terminology.singular} checkout`, + description: checkoutFailureDescription( + isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared), + ), + }); + return; + } + + const pointed = await input.pointThread(prepared.value); + if (cancelled) return; + if (!pointed) { + input.clearHandoff(); + toastManager.update(toastId, { + type: "error", + title: "Checked out, but the thread stayed where it was", + description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, + }); + return; + } + + input.clearHandoff(); + if (input.task === null) { + toastManager.update( + toastId, + prepared.value.isOnPullRequestHead + ? { + type: "success", + title: input.mode === "local" ? "Checked out here" : "Checked out", + description: + input.mode === "local" + ? `This repository is on the ${input.terminology.singular}'s branch, with a thread open on it.` + : `The ${input.terminology.singular} is in its own worktree, with a thread open on it.`, + } + : offHeadPullRequestCheckoutToast(input.terminology), + ); + return; + } + toastManager.update( + toastId, + prepared.value.isOnPullRequestHead + ? { + type: "success", + title: "Checkout ready", + description: "The task is in the composer. Read it over, then send.", + } + : offHeadPullRequestCheckoutToast(input.terminology), + ); +} + export type PullRequestHandoffDetail = Pick< PullRequestDetail, "projectId" | "workspaceRoot" | "url" @@ -332,96 +454,34 @@ export function usePullRequestHandoffs({ ) => { if (!detail || handoff !== null) return; setHandoff(kind); - // Explicit timeouts survive toast updates and would pin the result after loading. - const toastId = toastManager.add({ - type: "loading", - title: `Preparing the ${terminology.singular} checkout...`, - }); const projectRef = scopeProjectRef(environmentId, detail.projectId); - // Checkout setup requires the thread to exist first. - const opened = await newThread(projectRef).then( - (session) => session, - () => null, - ); - if (opened === null) { - setHandoff(null); - toastManager.update(toastId, { - type: "error", - title: "Could not open a thread for the checkout", - description: "Try again from the project, or open a thread first.", - }); - return; - } - const prepared = await prepareThread.run({ - reference: detail.url, + await runPullRequestCheckoutHandoff({ + terminology, mode, - threadId: opened.threadId, - }); - if (prepared._tag === "Failure") { - setHandoff(null); - toastManager.update(toastId, { - type: "error", - title: `Could not prepare the ${terminology.singular} checkout`, - description: checkoutFailureDescription( - isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared), + task, + clearHandoff: () => setHandoff(null), + // Checkout setup requires the thread to exist first. + openThread: () => + newThread(projectRef).then( + (session) => session, + () => null, + ), + prepare: (threadId) => + prepareThread.run({ + reference: detail.url, + mode, + threadId, + }), + pointThread: (prepared) => + newThread(projectRef, { + branch: prepared.branch, + worktreePath: prepared.worktreePath, + envMode: prepared.worktreePath === null ? "local" : "worktree", + }).then( + (session) => session !== null, + () => false, ), - }); - return; - } - const pointed = await newThread(projectRef, { - branch: prepared.value.branch, - worktreePath: prepared.value.worktreePath, - envMode: prepared.value.worktreePath === null ? "local" : "worktree", - }).then( - (session) => session, - () => null, - ); - if (pointed === null) { - setHandoff(null); - toastManager.update(toastId, { - type: "error", - title: "Checked out, but the thread stayed where it was", - description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, - }); - return; - } - // The draft carries the pull request until its first send makes it a thread, which links it. - useComposerDraftStore.getState().setDraftThreadContext(pointed.draftId, { - checkoutPullRequest: { - url: prepared.value.pullRequest.url, - branch: prepared.value.branch, - }, }); - setHandoff(null); - if (task === null) { - toastManager.update( - toastId, - prepared.value.isOnPullRequestHead - ? { - type: "success", - title: mode === "local" ? "Checked out here" : "Checked out", - description: - mode === "local" - ? `This repository is on the ${terminology.singular}'s branch, with a thread open on it.` - : `The ${terminology.singular} is in its own worktree, with a thread open on it.`, - } - : offHeadPullRequestCheckoutToast(terminology), - ); - return; - } - // The task goes on the checkout draft: if the user typed into `opened` while the - // checkout ran, that is no longer the draft the user is looking at. - await openThreadWithTask(projectRef, task, pointed); - toastManager.update( - toastId, - prepared.value.isOnPullRequestHead - ? { - type: "success", - title: "Checkout ready", - description: "The task is in the composer. Read it over, then send.", - } - : offHeadPullRequestCheckoutToast(terminology), - ); }; return { handoff, startAsk, startHandoff }; From 556eaaf2a11d45905860228114f8f29555f49766 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Sun, 8 Nov 2026 09:13:53 -0800 Subject: [PATCH 2/7] fix(web): keep checkout handoff prompt on the opened draft Seed the task even if Cancel lands during open, rebind that draft to the prepared checkout instead of opening a second empty one, and clear Cancel plus restore a finite timeout on every terminal toast. --- .../pullRequest/PullRequestDetailPanel.tsx | 12 ++-- .../runPullRequestCheckoutHandoff.test.ts | 65 +++++++++++++---- .../pullRequest/usePullRequestActions.ts | 72 ++++++++++++------- 3 files changed, 107 insertions(+), 42 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index e3e61e160439..6a8c06f7b4ef 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -988,15 +988,15 @@ export function PullRequestDetailPanel({ mode, threadId, }), - pointThread: (prepared) => - newThread(projectRef, { + // Rebind the opened draft: newThread would open a second empty draft once the prompt is seeded. + pointThread: async (prepared, opened) => { + useComposerDraftStore.getState().setDraftThreadContext(opened.draftId, { branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", - }).then( - (session) => session !== null, - () => false, - ), + }); + return true; + }, }); }; diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 109ab9e21de2..8a532486dffc 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -45,6 +45,8 @@ const terminology = sourceControlClients.get(undefined).changeRequest; type PreparedResult = AtomCommandResult; +const opened = { draftId: "draft-1" as never, threadId: "thread-1" as never }; + function reset() { state.add.mockClear().mockReturnValue(state.toastId); state.update.mockClear(); @@ -53,6 +55,13 @@ function reset() { state.getComposerDraft.mockReturnValue({ prompt: "", reviewComments: [] }); } +function cancelFromToast() { + const toast = state.add.mock.calls[0]?.[0] as + | { actionProps?: { onClick?: () => void } } + | undefined; + toast?.actionProps?.onClick?.(); +} + it("puts the task in the composer before checkout finishes", async () => { reset(); const prepare = deferred(); @@ -63,7 +72,7 @@ it("puts the task in the composer before checkout finishes", async () => { mode: "worktree", task: { prompt: "Fix the failing check" }, clearHandoff, - openThread: async () => ({ draftId: "draft-1" as never, threadId: "thread-1" as never }), + openThread: async () => opened, prepare: () => prepare.promise, pointThread, }); @@ -84,17 +93,22 @@ it("puts the task in the composer before checkout finishes", async () => { }), ); await pending; - expect(pointThread).toHaveBeenCalledWith({ - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }); + expect(pointThread).toHaveBeenCalledWith( + { + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }, + opened, + ); expect(clearHandoff).toHaveBeenCalled(); expect(state.update).toHaveBeenCalledWith( state.toastId, expect.objectContaining({ type: "success", title: "Checkout ready", + timeout: 8_000, + actionProps: undefined, }), ); }); @@ -109,22 +123,21 @@ it("cancels preparation and keeps the prompt without pointing the thread", async mode: "worktree", task: { prompt: "Fix the failing check" }, clearHandoff, - openThread: async () => ({ draftId: "draft-1" as never, threadId: "thread-1" as never }), + openThread: async () => opened, prepare: () => prepare.promise, pointThread, }); await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); - const toast = state.add.mock.calls[0]?.[0] as - | { actionProps?: { onClick?: () => void } } - | undefined; - toast?.actionProps?.onClick?.(); + cancelFromToast(); expect(clearHandoff).toHaveBeenCalled(); expect(state.update).toHaveBeenCalledWith( state.toastId, expect.objectContaining({ type: "info", - title: "Cancelled checkout preparation", + title: "Stopped applying the checkout", + timeout: 8_000, + actionProps: undefined, }), ); @@ -138,3 +151,31 @@ it("cancels preparation and keeps the prompt without pointing the thread", async await pending; expect(pointThread).not.toHaveBeenCalled(); }); + +it("seeds the prompt when cancel lands while openThread is still pending", async () => { + reset(); + const open = deferred(); + const clearHandoff = vi.fn(); + const pointThread = vi.fn(async () => true); + const pending = runPullRequestCheckoutHandoff({ + terminology, + mode: "worktree", + task: { prompt: "Fix the failing check" }, + clearHandoff, + openThread: () => open.promise, + prepare: async () => + AsyncResult.success({ + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }), + pointThread, + }); + + cancelFromToast(); + expect(state.setPrompt).not.toHaveBeenCalled(); + open.resolve(opened); + await pending; + expect(state.setPrompt).toHaveBeenCalledWith("draft-1", "Fix the failing check"); + expect(pointThread).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 8bfb8092ec0a..bc1b3f25efad 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -266,6 +266,26 @@ export type PullRequestCheckoutPrepared = { readonly isOnPullRequestHead: boolean; }; +type CheckoutHandoffOpened = { readonly draftId: DraftId; readonly threadId: ThreadId }; + +const CHECKOUT_HANDOFF_TOAST_TIMEOUT_MS = 8_000; + +function finishCheckoutHandoffToast( + toastId: ReturnType, + options: { + readonly type: "error" | "warning" | "success" | "info"; + readonly title: string; + readonly description?: string; + }, +) { + // Base UI merges updates into the loading toast, so clear Cancel and restore a finite timeout. + toastManager.update(toastId, { + ...options, + timeout: CHECKOUT_HANDOFF_TOAST_TIMEOUT_MS, + actionProps: undefined, + }); +} + /** * Opens a thread, puts any task in its composer before checkout finishes, then prepares the * branch. Cancel skips applying the checkout; the prompt stays in the composer. @@ -274,15 +294,19 @@ export async function runPullRequestCheckoutHandoff(input: { readonly terminology: ChangeRequestTerminology; readonly mode: "worktree" | "local"; readonly task: PullRequestThreadTask | null; - readonly openThread: () => Promise<{ draftId: DraftId; threadId: ThreadId } | null>; + readonly openThread: () => Promise; readonly prepare: ( threadId: ThreadId, ) => Promise>; - readonly pointThread: (prepared: PullRequestCheckoutPrepared) => Promise; + readonly pointThread: ( + prepared: PullRequestCheckoutPrepared, + opened: CheckoutHandoffOpened, + ) => Promise; readonly clearHandoff: () => void; }): Promise { // Explicit timeouts survive toast updates and would pin the result after loading. let cancelled = false; + let settled = false; const toastId = toastManager.add({ type: "loading", title: `Preparing the ${input.terminology.singular} checkout...`, @@ -290,18 +314,16 @@ export async function runPullRequestCheckoutHandoff(input: { actionProps: { children: "Cancel", onClick: () => { - if (cancelled) return; + if (cancelled || settled) return; cancelled = true; input.clearHandoff(); - toastManager.update(toastId, { + finishCheckoutHandoffToast(toastId, { type: "info", - title: "Cancelled checkout preparation", + title: "Stopped applying the checkout", description: input.task === null ? "The thread is still open." : "The prompt is still in the composer.", - timeout: 8_000, - actionProps: undefined, }); }, }, @@ -309,10 +331,15 @@ export async function runPullRequestCheckoutHandoff(input: { }); const opened = await input.openThread(); + // Cancel promises the prompt stays in the composer, so seed even after a cancel during open. + if (opened !== null && input.task !== null) { + writeHandoffToComposer(opened.draftId, input.task); + } if (cancelled) return; if (opened === null) { + settled = true; input.clearHandoff(); - toastManager.update(toastId, { + finishCheckoutHandoffToast(toastId, { type: "error", title: "Could not open a thread for the checkout", description: "Try again from the project, or open a thread first.", @@ -320,16 +347,12 @@ export async function runPullRequestCheckoutHandoff(input: { return; } - // Seed the composer before checkout finishes so a long prepare still shows the task. - if (input.task !== null) { - writeHandoffToComposer(opened.draftId, input.task); - } - const prepared = await input.prepare(opened.threadId); if (cancelled) return; if (prepared._tag === "Failure") { + settled = true; input.clearHandoff(); - toastManager.update(toastId, { + finishCheckoutHandoffToast(toastId, { type: "error", title: `Could not prepare the ${input.terminology.singular} checkout`, description: checkoutFailureDescription( @@ -339,11 +362,12 @@ export async function runPullRequestCheckoutHandoff(input: { return; } - const pointed = await input.pointThread(prepared.value); + const pointed = await input.pointThread(prepared.value, opened); if (cancelled) return; + settled = true; if (!pointed) { input.clearHandoff(); - toastManager.update(toastId, { + finishCheckoutHandoffToast(toastId, { type: "error", title: "Checked out, but the thread stayed where it was", description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, @@ -353,7 +377,7 @@ export async function runPullRequestCheckoutHandoff(input: { input.clearHandoff(); if (input.task === null) { - toastManager.update( + finishCheckoutHandoffToast( toastId, prepared.value.isOnPullRequestHead ? { @@ -368,7 +392,7 @@ export async function runPullRequestCheckoutHandoff(input: { ); return; } - toastManager.update( + finishCheckoutHandoffToast( toastId, prepared.value.isOnPullRequestHead ? { @@ -472,15 +496,15 @@ export function usePullRequestHandoffs({ mode, threadId, }), - pointThread: (prepared) => - newThread(projectRef, { + // Rebind the opened draft: newThread would open a second empty draft once the prompt is seeded. + pointThread: async (prepared, opened) => { + useComposerDraftStore.getState().setDraftThreadContext(opened.draftId, { branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", - }).then( - (session) => session !== null, - () => false, - ), + }); + return true; + }, }); }; From 0b7d1ac0d297058a15af9c83bbf587193f4c34e8 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Sun, 8 Nov 2026 09:26:42 -0800 Subject: [PATCH 3/7] fix(web): surface discarded-draft checkout rebind failures When prepare finishes after the opened draft is gone, pointThread no longer reports success so the handoff toast stays honest. --- .../pullRequest/PullRequestDetailPanel.tsx | 6 ++-- .../runPullRequestCheckoutHandoff.test.ts | 28 +++++++++++++++++++ .../pullRequest/usePullRequestActions.ts | 6 ++-- apps/web/src/composerDraftStore.test.ts | 10 +++++++ apps/web/src/composerDraftStore.ts | 8 ++++-- 5 files changed, 48 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 6a8c06f7b4ef..df7abced8393 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -989,14 +989,12 @@ export function PullRequestDetailPanel({ threadId, }), // Rebind the opened draft: newThread would open a second empty draft once the prompt is seeded. - pointThread: async (prepared, opened) => { + pointThread: async (prepared, opened) => useComposerDraftStore.getState().setDraftThreadContext(opened.draftId, { branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", - }); - return true; - }, + }), }); }; diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 8a532486dffc..2e34af388d3d 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -179,3 +179,31 @@ it("seeds the prompt when cancel lands while openThread is still pending", async expect(state.setPrompt).toHaveBeenCalledWith("draft-1", "Fix the failing check"); expect(pointThread).not.toHaveBeenCalled(); }); + +it("reports a failed rebind when the opened draft was discarded during prepare", async () => { + reset(); + const clearHandoff = vi.fn(); + await runPullRequestCheckoutHandoff({ + terminology, + mode: "worktree", + task: { prompt: "Fix the failing check" }, + clearHandoff, + openThread: async () => opened, + prepare: async () => + AsyncResult.success({ + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, + }), + pointThread: async () => false, + }); + + expect(clearHandoff).toHaveBeenCalled(); + expect(state.update).toHaveBeenCalledWith( + state.toastId, + expect.objectContaining({ + type: "error", + title: "Checked out, but the thread stayed where it was", + }), + ); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index bc1b3f25efad..57108a83a356 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -497,14 +497,12 @@ export function usePullRequestHandoffs({ threadId, }), // Rebind the opened draft: newThread would open a second empty draft once the prompt is seeded. - pointThread: async (prepared, opened) => { + pointThread: async (prepared, opened) => useComposerDraftStore.getState().setDraftThreadContext(opened.draftId, { branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", - }); - return true; - }, + }), }); }; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index b7f1f7ac366f..927d9d937ef0 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1171,6 +1171,16 @@ describe("composerDraftStore project draft thread mapping", () => { }); }); + it("reports whether setDraftThreadContext found a draft to update", () => { + const store = useComposerDraftStore.getState(); + expect(store.setDraftThreadContext(draftId, { branch: "gone" })).toBe(false); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + expect(store.setDraftThreadContext(draftId, { branch: "feature" })).toBe(true); + expect(store.setDraftThreadContext(draftId, { branch: "feature" })).toBe(true); + store.clearDraftThread(draftId); + expect(store.setDraftThreadContext(draftId, { branch: "after-clear" })).toBe(false); + }); + it("clears branch and worktree but keeps env mode when remapping a draft to another environment", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectRef, draftId, { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 95473066534c..3e5fa251bc90 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -524,7 +524,7 @@ interface ComposerDraftStoreState { loadBalancedEnvironmentId?: EnvironmentId | null; checkoutPullRequest?: DraftCheckoutPullRequest | null; }, - ) => void; + ) => boolean; clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void; clearProjectDraftThreadById: ( projectRef: ScopedProjectRef, @@ -2772,8 +2772,9 @@ const composerDraftStore = create()( setDraftThreadContext: (threadRef, options) => { const threadKey = resolveComposerDraftKey(get(), threadRef) ?? ""; if (threadKey.length === 0) { - return; + return false; } + let applied = false; set((state) => { const existing = state.draftThreadsByThreadKey[threadKey]; if (!existing) { @@ -2862,6 +2863,8 @@ const composerDraftStore = create()( existing.checkoutPullRequest, ) && scopedThreadRefsEqual(nextDraftThread.promotedTo, existing.promotedTo); + // Missing drafts stay false; an already-matching draft still counts as applied. + applied = true; if (isUnchanged) { return state; } @@ -2872,6 +2875,7 @@ const composerDraftStore = create()( }, }; }); + return applied; }, clearProjectDraftThreadId: (projectRef) => { set((state) => { From 2df0741e59a0f7ba21c4ea8a46a646ae38cb24c3 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Tue, 10 Nov 2026 07:11:04 +0000 Subject: [PATCH 4/7] fix(web): block sending during pull request checkout preparation --- apps/web/src/components/ChatView.tsx | 33 ++++--- .../src/components/chat/useComposerSend.ts | 2 + .../pullRequest/pullRequestCheckoutState.ts | 13 +++ .../runPullRequestCheckoutHandoff.test.ts | 3 + .../pullRequest/usePullRequestActions.ts | 92 ++++++++++--------- 5 files changed, 87 insertions(+), 56 deletions(-) create mode 100644 apps/web/src/components/pullRequest/pullRequestCheckoutState.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index af95eff230d6..181d03545c1c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,3 +1,4 @@ +import { usePullRequestCheckoutState } from "./pullRequest/pullRequestCheckoutState"; import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -477,6 +478,9 @@ export default function ChatView(props: ChatViewProps) { ? store.getDraftSession(draftId) : null, ); + const isPreparingPullRequestCheckout = usePullRequestCheckoutState( + (state) => draftId !== null && state.draftIds.has(draftId), + ); const serverThreadShell = useQuietThreadShell(routeThreadRef); const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, { shellExists: serverThreadShell !== null, @@ -3598,6 +3602,7 @@ export default function ChatView(props: ChatViewProps) { canSteer={!compactionBlocksSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ + isPreparingPullRequestCheckout || (isSendBusy && !sendQueuesBehindSetup) || (setupQueueSendThreadKey !== null && setupQueueSendThreadKey === activeThreadKey) || @@ -3607,19 +3612,21 @@ export default function ChatView(props: ChatViewProps) { canResume={resumableRunId !== null || hasHeldQueuedRuns} isRevertingCheckpoint={isRevertingCheckpoint} sendDisabledReason={ - !canOperateThread - ? "This connection cannot change threads." - : isEnvironmentChanging - ? "Preparing machine" - : isRevertingCheckpoint - ? "Rewinding conversation" - : feedbackUploading - ? "Sending feedback" - : threadDetailLoading - ? "Messages loading" - : worktreeSetupBlocksSend - ? "Preparing worktree" - : projectCloneSendBlockReason + isPreparingPullRequestCheckout + ? "Preparing pull request checkout" + : !canOperateThread + ? "This connection cannot change threads." + : isEnvironmentChanging + ? "Preparing machine" + : isRevertingCheckpoint + ? "Rewinding conversation" + : feedbackUploading + ? "Sending feedback" + : threadDetailLoading + ? "Messages loading" + : worktreeSetupBlocksSend + ? "Preparing worktree" + : projectCloneSendBlockReason } isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup} bannerItems={ diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index a69bc6f327ac..aabbe0985a91 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1,3 +1,4 @@ +import { usePullRequestCheckoutState } from "../pullRequest/pullRequestCheckoutState"; import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger"; import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms"; import { @@ -425,6 +426,7 @@ export function useComposerSend(input: ComposerSendInput) { ); }; if ( + (draftId !== null && usePullRequestCheckoutState.getState().draftIds.has(draftId)) || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || !activeThread || (isSendBusy && !sendQueuesBehindSetup) || diff --git a/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts new file mode 100644 index 000000000000..6beda5f0f0c5 --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts @@ -0,0 +1,13 @@ +import { create } from "zustand"; +import type { DraftId } from "~/composerDraftStore"; + +export const usePullRequestCheckoutState = create(() => ({ draftIds: new Set() })); + +export function setPullRequestCheckoutPending(draftId: DraftId, pending: boolean) { + usePullRequestCheckoutState.setState((state) => { + const draftIds = new Set(state.draftIds); + if (pending) draftIds.add(draftId); + else draftIds.delete(draftId); + return { draftIds }; + }); +} diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 2e34af388d3d..4835fca59d25 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -4,6 +4,7 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import { expect, it, vi } from "vite-plus/test"; import type { PullRequestCheckoutPrepared } from "./usePullRequestActions"; +import { usePullRequestCheckoutState } from "./pullRequestCheckoutState"; const state = vi.hoisted(() => ({ toastId: "checkout-toast", @@ -80,6 +81,7 @@ it("puts the task in the composer before checkout finishes", async () => { await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); expect(state.setPrompt).toHaveBeenCalledWith("draft-1", "Fix the failing check"); expect(pointThread).not.toHaveBeenCalled(); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(true); expect(state.add.mock.calls[0]?.[0]).toMatchObject({ type: "loading", actionProps: { children: "Cancel" }, @@ -93,6 +95,7 @@ it("puts the task in the composer before checkout finishes", async () => { }), ); await pending; + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); expect(pointThread).toHaveBeenCalledWith( { branch: "pr-1", diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 57108a83a356..158181ececd5 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -1,3 +1,4 @@ +import { setPullRequestCheckoutPending } from "./pullRequestCheckoutState"; import { useAtomCommand } from "~/state/use-atom-command"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { @@ -347,61 +348,66 @@ export async function runPullRequestCheckoutHandoff(input: { return; } - const prepared = await input.prepare(opened.threadId); - if (cancelled) return; - if (prepared._tag === "Failure") { + setPullRequestCheckoutPending(opened.draftId, true); + try { + const prepared = await input.prepare(opened.threadId); + if (cancelled) return; + if (prepared._tag === "Failure") { + settled = true; + input.clearHandoff(); + finishCheckoutHandoffToast(toastId, { + type: "error", + title: `Could not prepare the ${input.terminology.singular} checkout`, + description: checkoutFailureDescription( + isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared), + ), + }); + return; + } + + const pointed = await input.pointThread(prepared.value, opened); + if (cancelled) return; settled = true; - input.clearHandoff(); - finishCheckoutHandoffToast(toastId, { - type: "error", - title: `Could not prepare the ${input.terminology.singular} checkout`, - description: checkoutFailureDescription( - isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared), - ), - }); - return; - } + if (!pointed) { + input.clearHandoff(); + finishCheckoutHandoffToast(toastId, { + type: "error", + title: "Checked out, but the thread stayed where it was", + description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, + }); + return; + } - const pointed = await input.pointThread(prepared.value, opened); - if (cancelled) return; - settled = true; - if (!pointed) { input.clearHandoff(); - finishCheckoutHandoffToast(toastId, { - type: "error", - title: "Checked out, but the thread stayed where it was", - description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`, - }); - return; - } - - input.clearHandoff(); - if (input.task === null) { + if (input.task === null) { + finishCheckoutHandoffToast( + toastId, + prepared.value.isOnPullRequestHead + ? { + type: "success", + title: input.mode === "local" ? "Checked out here" : "Checked out", + description: + input.mode === "local" + ? `This repository is on the ${input.terminology.singular}'s branch, with a thread open on it.` + : `The ${input.terminology.singular} is in its own worktree, with a thread open on it.`, + } + : offHeadPullRequestCheckoutToast(input.terminology), + ); + return; + } finishCheckoutHandoffToast( toastId, prepared.value.isOnPullRequestHead ? { type: "success", - title: input.mode === "local" ? "Checked out here" : "Checked out", - description: - input.mode === "local" - ? `This repository is on the ${input.terminology.singular}'s branch, with a thread open on it.` - : `The ${input.terminology.singular} is in its own worktree, with a thread open on it.`, + title: "Checkout ready", + description: "The task is in the composer. Read it over, then send.", } : offHeadPullRequestCheckoutToast(input.terminology), ); - return; + } finally { + setPullRequestCheckoutPending(opened.draftId, false); } - finishCheckoutHandoffToast( - toastId, - prepared.value.isOnPullRequestHead - ? { - type: "success", - title: "Checkout ready", - description: "The task is in the composer. Read it over, then send.", - } - : offHeadPullRequestCheckoutToast(input.terminology), - ); } export type PullRequestHandoffDetail = Pick< From 95fb28f74e17e99474ab2bc4d02ecdbc501f2ba2 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Wed, 11 Nov 2026 09:44:50 -0800 Subject: [PATCH 5/7] fix(web): clear checkout pending on cancel and keep PR draft link Cancel unblocks the composer immediately instead of waiting for prepare to settle, and rebased handoffs still set checkoutPullRequest on the opened draft. Co-authored-by: Cursor --- .../pullRequest/PullRequestDetailPanel.tsx | 5 ++ .../runPullRequestCheckoutHandoff.test.ts | 49 ++++++------------- .../pullRequest/usePullRequestActions.ts | 10 ++++ 3 files changed, 30 insertions(+), 34 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index df7abced8393..e195a3efa8da 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -994,6 +994,11 @@ export function PullRequestDetailPanel({ branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", + // Draft carries the PR until its first send makes it a thread, which links it. + checkoutPullRequest: { + url: prepared.pullRequest.url, + branch: prepared.branch, + }, }), }); }; diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 4835fca59d25..46750c0844c5 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -48,6 +48,13 @@ type PreparedResult = AtomCommandResult; const opened = { draftId: "draft-1" as never, threadId: "thread-1" as never }; +const preparedCheckout: PullRequestCheckoutPrepared = { + pullRequest: { url: "https://github.com/pingdotgg/t3code/pull/1" }, + branch: "pr-1", + worktreePath: "/tmp/pr-1", + isOnPullRequestHead: true, +}; + function reset() { state.add.mockClear().mockReturnValue(state.toastId); state.update.mockClear(); @@ -87,23 +94,10 @@ it("puts the task in the composer before checkout finishes", async () => { actionProps: { children: "Cancel" }, }); - prepare.resolve( - AsyncResult.success({ - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }), - ); + prepare.resolve(AsyncResult.success(preparedCheckout)); await pending; expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); - expect(pointThread).toHaveBeenCalledWith( - { - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }, - opened, - ); + expect(pointThread).toHaveBeenCalledWith(preparedCheckout, opened); expect(clearHandoff).toHaveBeenCalled(); expect(state.update).toHaveBeenCalledWith( state.toastId, @@ -132,8 +126,10 @@ it("cancels preparation and keeps the prompt without pointing the thread", async }); await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(true); cancelFromToast(); expect(clearHandoff).toHaveBeenCalled(); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); expect(state.update).toHaveBeenCalledWith( state.toastId, expect.objectContaining({ @@ -144,15 +140,10 @@ it("cancels preparation and keeps the prompt without pointing the thread", async }), ); - prepare.resolve( - AsyncResult.success({ - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }), - ); + prepare.resolve(AsyncResult.success(preparedCheckout)); await pending; expect(pointThread).not.toHaveBeenCalled(); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); }); it("seeds the prompt when cancel lands while openThread is still pending", async () => { @@ -166,12 +157,7 @@ it("seeds the prompt when cancel lands while openThread is still pending", async task: { prompt: "Fix the failing check" }, clearHandoff, openThread: () => open.promise, - prepare: async () => - AsyncResult.success({ - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }), + prepare: async () => AsyncResult.success(preparedCheckout), pointThread, }); @@ -192,12 +178,7 @@ it("reports a failed rebind when the opened draft was discarded during prepare", task: { prompt: "Fix the failing check" }, clearHandoff, openThread: async () => opened, - prepare: async () => - AsyncResult.success({ - branch: "pr-1", - worktreePath: "/tmp/pr-1", - isOnPullRequestHead: true, - }), + prepare: async () => AsyncResult.success(preparedCheckout), pointThread: async () => false, }); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 158181ececd5..d746ecfeb4a3 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -262,6 +262,7 @@ export function writeHandoffToComposer( } export type PullRequestCheckoutPrepared = { + readonly pullRequest: { readonly url: string }; readonly branch: string; readonly worktreePath: string | null; readonly isOnPullRequestHead: boolean; @@ -308,6 +309,7 @@ export async function runPullRequestCheckoutHandoff(input: { // Explicit timeouts survive toast updates and would pin the result after loading. let cancelled = false; let settled = false; + let pendingDraftId: DraftId | null = null; const toastId = toastManager.add({ type: "loading", title: `Preparing the ${input.terminology.singular} checkout...`, @@ -317,6 +319,8 @@ export async function runPullRequestCheckoutHandoff(input: { onClick: () => { if (cancelled || settled) return; cancelled = true; + // Unblock send immediately; finally clears again after prepare/point settle. + if (pendingDraftId !== null) setPullRequestCheckoutPending(pendingDraftId, false); input.clearHandoff(); finishCheckoutHandoffToast(toastId, { type: "info", @@ -348,6 +352,7 @@ export async function runPullRequestCheckoutHandoff(input: { return; } + pendingDraftId = opened.draftId; setPullRequestCheckoutPending(opened.draftId, true); try { const prepared = await input.prepare(opened.threadId); @@ -508,6 +513,11 @@ export function usePullRequestHandoffs({ branch: prepared.branch, worktreePath: prepared.worktreePath, envMode: prepared.worktreePath === null ? "local" : "worktree", + // Draft carries the PR until its first send makes it a thread, which links it. + checkoutPullRequest: { + url: prepared.pullRequest.url, + branch: prepared.branch, + }, }), }); }; From 92050d13399bd65daccf8fb168e99d3366809161 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 11 Nov 2026 21:23:07 +0000 Subject: [PATCH 6/7] fix(web): wait for local checkout before unblocking send --- .../runPullRequestCheckoutHandoff.test.ts | 87 +++++++++++-------- .../pullRequest/usePullRequestActions.ts | 25 +++++- 2 files changed, 76 insertions(+), 36 deletions(-) diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 46750c0844c5..94fbecbed049 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -110,41 +110,58 @@ it("puts the task in the composer before checkout finishes", async () => { ); }); -it("cancels preparation and keeps the prompt without pointing the thread", async () => { - reset(); - const prepare = deferred(); - const clearHandoff = vi.fn(); - const pointThread = vi.fn(async () => true); - const pending = runPullRequestCheckoutHandoff({ - terminology, - mode: "worktree", - task: { prompt: "Fix the failing check" }, - clearHandoff, - openThread: async () => opened, - prepare: () => prepare.promise, - pointThread, - }); - - await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); - expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(true); - cancelFromToast(); - expect(clearHandoff).toHaveBeenCalled(); - expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); - expect(state.update).toHaveBeenCalledWith( - state.toastId, - expect.objectContaining({ - type: "info", - title: "Stopped applying the checkout", - timeout: 8_000, - actionProps: undefined, - }), - ); - - prepare.resolve(AsyncResult.success(preparedCheckout)); - await pending; - expect(pointThread).not.toHaveBeenCalled(); - expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); -}); +it.each(["worktree", "local"] as const)( + "cancels %s preparation without pointing the thread", + async (mode) => { + reset(); + const prepare = deferred(); + const clearHandoff = vi.fn(); + const pointThread = vi.fn(async () => true); + const pending = runPullRequestCheckoutHandoff({ + terminology, + mode, + task: { prompt: "Fix the failing check" }, + clearHandoff, + openThread: async () => opened, + prepare: () => prepare.promise, + pointThread, + }); + + await vi.waitFor(() => expect(state.setPrompt).toHaveBeenCalled()); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(true); + cancelFromToast(); + expect(clearHandoff).toHaveBeenCalledTimes(mode === "local" ? 0 : 1); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe( + mode === "local", + ); + expect(state.update).toHaveBeenCalledWith( + state.toastId, + expect.objectContaining({ + type: mode === "local" ? "loading" : "info", + title: + mode === "local" ? "Waiting for the local checkout" : "Stopped applying the checkout", + timeout: mode === "local" ? 0 : 8_000, + actionProps: undefined, + }), + ); + + prepare.resolve(AsyncResult.success(preparedCheckout)); + await pending; + expect(pointThread).not.toHaveBeenCalled(); + expect(clearHandoff).toHaveBeenCalled(); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); + if (mode === "local") { + expect(state.update).toHaveBeenLastCalledWith( + state.toastId, + expect.objectContaining({ + title: "Local checkout finished", + description: "This repository is now on `pr-1`. The thread is still open.", + timeout: 8_000, + }), + ); + } + }, +); it("seeds the prompt when cancel lands while openThread is still pending", async () => { reset(); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index d746ecfeb4a3..faf338afcea2 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -319,6 +319,18 @@ export async function runPullRequestCheckoutHandoff(input: { onClick: () => { if (cancelled || settled) return; cancelled = true; + // A local branch switch keeps running on the server, so send must wait for its result. + if (input.mode === "local" && pendingDraftId !== null) { + toastManager.update(toastId, { + type: "loading", + title: "Waiting for the local checkout", + description: + "The branch switch is already running. Sending stays blocked until it finishes.", + timeout: 0, + actionProps: undefined, + }); + return; + } // Unblock send immediately; finally clears again after prepare/point settle. if (pendingDraftId !== null) setPullRequestCheckoutPending(pendingDraftId, false); input.clearHandoff(); @@ -356,7 +368,7 @@ export async function runPullRequestCheckoutHandoff(input: { setPullRequestCheckoutPending(opened.draftId, true); try { const prepared = await input.prepare(opened.threadId); - if (cancelled) return; + if (cancelled && input.mode !== "local") return; if (prepared._tag === "Failure") { settled = true; input.clearHandoff(); @@ -370,6 +382,17 @@ export async function runPullRequestCheckoutHandoff(input: { return; } + if (cancelled) { + settled = true; + input.clearHandoff(); + finishCheckoutHandoffToast(toastId, { + type: "info", + title: "Local checkout finished", + description: `This repository is now on \`${prepared.value.branch}\`. The thread is still open.`, + }); + return; + } + const pointed = await input.pointThread(prepared.value, opened); if (cancelled) return; settled = true; From 6bf111c3d9adc8733c205963bdd6f153b1b8ee39 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 11 Nov 2026 21:34:39 +0000 Subject: [PATCH 7/7] fix(web): preserve newer checkout send guards --- .../pullRequest/pullRequestCheckoutState.ts | 9 ++++---- .../runPullRequestCheckoutHandoff.test.ts | 23 ++++++++++++++++++- .../pullRequest/usePullRequestActions.ts | 8 ++++--- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts index 6beda5f0f0c5..5ebbef309f4e 100644 --- a/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts +++ b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts @@ -1,12 +1,13 @@ import { create } from "zustand"; import type { DraftId } from "~/composerDraftStore"; -export const usePullRequestCheckoutState = create(() => ({ draftIds: new Set() })); +export const usePullRequestCheckoutState = create(() => ({ draftIds: new Map() })); -export function setPullRequestCheckoutPending(draftId: DraftId, pending: boolean) { +export function setPullRequestCheckoutPending(draftId: DraftId, pending: boolean, owner: symbol) { usePullRequestCheckoutState.setState((state) => { - const draftIds = new Set(state.draftIds); - if (pending) draftIds.add(draftId); + if (!pending && state.draftIds.get(draftId) !== owner) return state; + const draftIds = new Map(state.draftIds); + if (pending) draftIds.set(draftId, owner); else draftIds.delete(draftId); return { draftIds }; }); diff --git a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts index 94fbecbed049..f87497b20ea4 100644 --- a/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -145,11 +145,29 @@ it.each(["worktree", "local"] as const)( }), ); + const nextPrepare = deferred(); + const prepareNext = vi.fn(() => nextPrepare.promise); + const nextPending = + mode === "worktree" + ? runPullRequestCheckoutHandoff({ + terminology, + mode, + task: null, + clearHandoff: vi.fn(), + openThread: async () => opened, + prepare: prepareNext, + pointThread, + }) + : null; + if (nextPending !== null) await vi.waitFor(() => expect(prepareNext).toHaveBeenCalled()); + prepare.resolve(AsyncResult.success(preparedCheckout)); await pending; expect(pointThread).not.toHaveBeenCalled(); expect(clearHandoff).toHaveBeenCalled(); - expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe( + mode === "worktree", + ); if (mode === "local") { expect(state.update).toHaveBeenLastCalledWith( state.toastId, @@ -160,6 +178,9 @@ it.each(["worktree", "local"] as const)( }), ); } + nextPrepare.resolve(AsyncResult.success(preparedCheckout)); + await nextPending; + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); }, ); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index faf338afcea2..7640be1bd050 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -310,6 +310,7 @@ export async function runPullRequestCheckoutHandoff(input: { let cancelled = false; let settled = false; let pendingDraftId: DraftId | null = null; + const pendingOwner = Symbol(); const toastId = toastManager.add({ type: "loading", title: `Preparing the ${input.terminology.singular} checkout...`, @@ -332,7 +333,8 @@ export async function runPullRequestCheckoutHandoff(input: { return; } // Unblock send immediately; finally clears again after prepare/point settle. - if (pendingDraftId !== null) setPullRequestCheckoutPending(pendingDraftId, false); + if (pendingDraftId !== null) + setPullRequestCheckoutPending(pendingDraftId, false, pendingOwner); input.clearHandoff(); finishCheckoutHandoffToast(toastId, { type: "info", @@ -365,7 +367,7 @@ export async function runPullRequestCheckoutHandoff(input: { } pendingDraftId = opened.draftId; - setPullRequestCheckoutPending(opened.draftId, true); + setPullRequestCheckoutPending(opened.draftId, true, pendingOwner); try { const prepared = await input.prepare(opened.threadId); if (cancelled && input.mode !== "local") return; @@ -434,7 +436,7 @@ export async function runPullRequestCheckoutHandoff(input: { : offHeadPullRequestCheckoutToast(input.terminology), ); } finally { - setPullRequestCheckoutPending(opened.draftId, false); + setPullRequestCheckoutPending(opened.draftId, false, pendingOwner); } }