diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 115c30779a57b..e00ab1ccba95e 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"; @@ -500,6 +501,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, @@ -3656,6 +3660,7 @@ export default function ChatView(props: ChatViewProps) { canSteer={!compactionBlocksSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ + isPreparingPullRequestCheckout || (isSendBusy && !sendQueuesBehindSetup) || (setupQueueSendThreadKey !== null && setupQueueSendThreadKey === activeThreadKey) || @@ -3665,19 +3670,21 @@ export default function ChatView(props: ChatViewProps) { canResume={canResume} 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 1afe53a944707..50359c353678d 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 { @@ -433,6 +434,7 @@ export function useComposerSend(input: ComposerSendInput) { ); }; if ( + (draftId !== null && usePullRequestCheckoutState.getState().draftIds.has(draftId)) || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || !activeThread || isRevertingCheckpoint || diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 6e4a2bb6fb6a0..9d415dff8cb0a 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, @@ -970,99 +966,40 @@ 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, ), - }); - 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, - }, + prepare: (threadId) => + prepareThread.run({ + reference: handoffSummary.url, + mode, + threadId, + }), + // 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", + // Draft carries the PR until its first send makes it a thread, which links it. + checkoutPullRequest: { + url: prepared.pullRequest.url, + branch: prepared.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/pullRequestCheckoutState.ts b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts new file mode 100644 index 0000000000000..5ebbef309f4e6 --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestCheckoutState.ts @@ -0,0 +1,14 @@ +import { create } from "zustand"; +import type { DraftId } from "~/composerDraftStore"; + +export const usePullRequestCheckoutState = create(() => ({ draftIds: new Map() })); + +export function setPullRequestCheckoutPending(draftId: DraftId, pending: boolean, owner: symbol) { + usePullRequestCheckoutState.setState((state) => { + 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 new file mode 100644 index 0000000000000..f87497b20ea46 --- /dev/null +++ b/apps/web/src/components/pullRequest/runPullRequestCheckoutHandoff.test.ts @@ -0,0 +1,231 @@ +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"; +import { usePullRequestCheckoutState } from "./pullRequestCheckoutState"; + +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; + +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(); + state.setPrompt.mockClear(); + state.setReviewComments.mockClear(); + 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(); + 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(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" }, + }); + + prepare.resolve(AsyncResult.success(preparedCheckout)); + await pending; + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); + expect(pointThread).toHaveBeenCalledWith(preparedCheckout, opened); + expect(clearHandoff).toHaveBeenCalled(); + expect(state.update).toHaveBeenCalledWith( + state.toastId, + expect.objectContaining({ + type: "success", + title: "Checkout ready", + timeout: 8_000, + actionProps: undefined, + }), + ); +}); + +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, + }), + ); + + 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( + mode === "worktree", + ); + 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, + }), + ); + } + nextPrepare.resolve(AsyncResult.success(preparedCheckout)); + await nextPending; + expect(usePullRequestCheckoutState.getState().draftIds.has(opened.draftId)).toBe(false); + }, +); + +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(preparedCheckout), + 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(); +}); + +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(preparedCheckout), + 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 63681b4cf2167..11bbff1984695 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -1,8 +1,10 @@ +import { setPullRequestCheckoutPending } from "./pullRequestCheckoutState"; import { useAtomCommand } from "~/state/use-atom-command"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { isAtomCommandInterrupted, squashAtomCommandFailure, + type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, @@ -13,6 +15,7 @@ import type { PullRequestRef, PullRequestSummary, ScopedThreadRef, + ThreadId, } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { @@ -258,6 +261,181 @@ export function writeHandoffToComposer( store.setReviewComments(target, next.reviewComments); } +export type PullRequestCheckoutPrepared = { + readonly pullRequest: { readonly url: string }; + readonly branch: string; + readonly worktreePath: string | null; + 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. + */ +export async function runPullRequestCheckoutHandoff(input: { + readonly terminology: ChangeRequestTerminology; + readonly mode: "worktree" | "local"; + readonly task: PullRequestThreadTask | null; + readonly openThread: () => Promise; + readonly prepare: ( + threadId: ThreadId, + ) => 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; + let pendingDraftId: DraftId | null = null; + const pendingOwner = Symbol(); + const cancel = () => { + 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, pendingOwner); + input.clearHandoff(); + finishCheckoutHandoffToast(toastId, { + type: "info", + title: "Stopped applying the checkout", + description: + input.task === null ? "The thread is still open." : "The prompt is still in the composer.", + }); + }; + const toastId = toastManager.add({ + type: "loading", + title: `Preparing the ${input.terminology.singular} checkout...`, + timeout: 0, + actionProps: { children: "Cancel", onClick: cancel }, + // Dismissing the loading toast cancels the same way as the Cancel action. + data: { hideCopyButton: true, onClose: cancel }, + }); + + 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(); + finishCheckoutHandoffToast(toastId, { + type: "error", + title: "Could not open a thread for the checkout", + description: "Try again from the project, or open a thread first.", + }); + return; + } + + pendingDraftId = opened.draftId; + setPullRequestCheckoutPending(opened.draftId, true, pendingOwner); + try { + const prepared = await input.prepare(opened.threadId); + if (cancelled && input.mode !== "local") 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; + } + + 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; + 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) { + 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: "Checkout ready", + description: "The task is in the composer. Read it over, then send.", + } + : offHeadPullRequestCheckoutToast(input.terminology), + ); + } finally { + setPullRequestCheckoutPending(opened.draftId, false, pendingOwner); + } +} + export type PullRequestHandoffDetail = Pick< PullRequestDetail, "projectId" | "workspaceRoot" | "url" @@ -332,115 +510,37 @@ export function usePullRequestHandoffs({ ) => { if (!detail || handoff !== null) return; setHandoff(kind); - // Dismissing the loading toast cancels the handoff before it touches a draft. - let cancelled = false; - // Explicit timeouts survive toast updates and would pin the result after loading. - const toastId = toastManager.add({ - type: "loading", - title: `Preparing the ${terminology.singular} checkout...`, - data: { - onClose: () => { - cancelled = true; - }, - }, - }); const projectRef = scopeProjectRef(environmentId, detail.projectId); - // Checkout setup requires the thread to exist first. - const opened = await newThread(projectRef).then( - (session) => session, - () => null, - ); - if (cancelled) { - setHandoff(null); - return; - } - 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 (cancelled) { - setHandoff(null); - return; - } - 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, ), - }); - 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 (cancelled) { - setHandoff(null); - return; - } - 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, - }, + prepare: (threadId) => + prepareThread.run({ + reference: detail.url, + mode, + threadId, + }), + // 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", + // Draft carries the PR until its first send makes it a thread, which links it. + checkoutPullRequest: { + url: prepared.pullRequest.url, + branch: prepared.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 }; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 43d61924a8c74..a32d80399a831 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1205,6 +1205,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 0bf2b690b4696..9096ab95fbf41 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -624,7 +624,7 @@ interface ComposerDraftStoreState { loadBalancedEnvironmentId?: EnvironmentId | null; checkoutPullRequest?: DraftCheckoutPullRequest | null; }, - ) => void; + ) => boolean; clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void; clearProjectDraftThreadById: ( projectRef: ScopedProjectRef, @@ -2935,8 +2935,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) { @@ -3025,6 +3026,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; } @@ -3035,6 +3038,7 @@ const composerDraftStore = create()( }, }; }); + return applied; }, clearProjectDraftThreadId: (projectRef) => { set((state) => {