TypeScript
fix(web): show pull request checkout error detail (#15007)
Alex Southwell83cf6dbebe88
diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsxindex a1b80f2a7d6..47adb13580c 100644--- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx+++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx@@ -1,4 +1,13 @@-import { EnvironmentId, type PullRequestCheck } from "@t3tools/contracts";+import {+ EnvironmentId,+ GitCommandError,+ GitManagerError,+ ProjectId,+ ThreadId,+ type PullRequestCheck,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { DraftId } from "~/composerDraftStore";import { AsyncResult } from "effect/reactivity";import { act } from "react";import { createRoot, type Root } from "react-dom/client";@@ -8,6 +17,11 @@ const state = vi.hoisted(() => ({status: "success" as PullRequestCheck["status"],extraStatus: null as PullRequestCheck["status"] | null,perform: vi.fn(),+ newThread: vi.fn(),+ prepareThread: vi.fn(),+ checkoutError: null as Error | null,+ addToast: vi.fn(),+ updateToast: vi.fn(),}));vi.mock(import("~/state/entities"), async (importOriginal) => ({@@ -15,6 +29,9 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({useServerConfigs: (() => new Map()) as never,}));const queryData = () => ({+ projectId: ProjectId.make("project"),+ workspaceRoot: "/workspace",+ url: "https://github.com/owner/repo/pull/1",number: 1,title: "Test PR",state: "open",@@ -45,9 +62,32 @@ vi.mock(import("~/state/query"), async (importOriginal) => ({vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({...(await importOriginal()),usePullRequestActionRunner: () => ({ actionPending: false, perform: state.perform }),- usePullRequestHandoffs: () => ({ handoff: null, startAsk: vi.fn(), startHandoff: vi.fn() }),}));+vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({+ ...(await original()),+ useNewThreadHandler: (() => state.newThread) as never,+}));+vi.mock(import("~/lib/sourceControlActions"), async (original) => ({+ ...(await original()),+ usePreparePullRequestThreadAction: (() => ({+ run: state.prepareThread,+ isAllowed: true,+ error: state.checkoutError,+ })) as never,+}));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ toastManager: {+ ...actual.toastManager,+ add: state.addToast,+ update: state.updateToast,+ } as never,+ };+});+import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow";let root: Root;@@ -57,6 +97,14 @@ beforeEach(() => {container = document.createElement("div");document.body.append(container);root = createRoot(container);+ state.checkoutError = null;+ state.newThread.mockReset().mockResolvedValue({+ draftId: DraftId.make("new-draft"),+ threadId: ThreadId.make("new-thread"),+ });+ state.prepareThread.mockReset();+ state.addToast.mockReset().mockReturnValue("checkout-toast");+ state.updateToast.mockReset();});afterEach(() => {act(() => root.unmount());@@ -133,3 +181,48 @@ it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([.filter((value) => /^\d+\/\d+$/.test(value));expect(new Set(counts)).toEqual(new Set(count ? [count] : []));});++it("shows the current checkout recovery detail when fixing checks fails and is retried", async () => {+ state.status = "failure";+ const first = new GitManagerError({+ cwd: "/workspace",+ operation: "preparePullRequestThread",+ detail: "This PR branch is already checked out in the main repo. Use Local.",+ });+ const second = new GitCommandError({+ cwd: "/workspace",+ operation: "GitVcsDriver.createWorktree",+ command: "git worktree add",+ detail: "The worktree directory already exists. Choose another directory.",+ });+ await act(async () => {+ root.render(+ <ThreadDetailsPrRow+ environmentId={EnvironmentId.make("environment")}+ pr={null}+ number={1}+ status={null}+ project={null}+ label="Test PR"+ openAriaLabel="Open PR"+ onOpen={vi.fn()}+ />,+ );+ });++ for (const error of [first, second]) {+ state.prepareThread.mockImplementationOnce(async () => {+ state.checkoutError = error;+ return { _tag: "Failure", cause: Cause.fail(error) };+ });+ await act(async () => {+ [...container.querySelectorAll("button")]+ .find((button) => button.textContent?.trim() === "Fix")!+ .click();+ });+ }+ expect(state.updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([+ expect.stringContaining(first.detail),+ second.detail,+ ]);+});diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsxindex 5b2460ecb18..31fc9a3e440 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx@@ -1,5 +1,7 @@import {EnvironmentId,+ GitCommandError,+ GitManagerError,ProjectId,SourceControlProviderKind,ThreadId,@@ -7,6 +9,7 @@ import {type ScopedThreadRef,type ThreadPullRequestLink,} from "@t3tools/contracts";+import * as Cause from "effect/Cause";import { act, type ComponentProps } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";@@ -15,11 +18,16 @@ import { DraftId, useComposerDraftStore } from "~/composerDraftStore";import "~/index.css";-const { newThread, prepareThread, refresh } = vi.hoisted(() => ({- newThread: vi.fn(),- prepareThread: vi.fn(),- refresh: vi.fn(),-}));+const { newThread, prepareThread, refresh, addToast, updateToast, checkoutState } = vi.hoisted(+ () => ({+ newThread: vi.fn(),+ prepareThread: vi.fn(),+ refresh: vi.fn(),+ addToast: vi.fn(),+ updateToast: vi.fn(),+ checkoutState: { error: null as Error | null },+ }),+);vi.mock(import("~/state/session"), async (original) => ({...(await original()),@@ -39,7 +47,7 @@ vi.mock(import("~/lib/sourceControlActions"), async (original) => ({usePreparePullRequestThreadAction: (() => ({run: prepareThread,isAllowed: true,- error: null,+ error: checkoutState.error,})) as never,}));vi.mock(import("~/state/use-atom-command"), async (original) => ({@@ -146,6 +154,14 @@ vi.mock(import("./PullRequestCodeTab"), async (original) => ({)) as never,}));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ toastManager: { ...actual.toastManager, add: addToast, update: updateToast } as never,+ };+});+import { PullRequestDetailPanel } from "./PullRequestDetailPanel";import { pullRequestPanelContext } from "./pullRequestDetail.logic";@@ -244,6 +260,9 @@ beforeEach(() => {newThread.mockReset().mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });+ addToast.mockReset().mockReturnValue("checkout-toast");+ updateToast.mockReset();+ checkoutState.error = null;prepareThread.mockReset().mockResolvedValue({_tag: "Success",value: { branch: "feature", worktreePath: "/workspace/pr" },@@ -386,3 +405,32 @@ it("folds the title only for the active tab's own scroller", async () => {await tab("Code").click();await vi.waitFor(() => expect(titleFold()).toBe(true));});++it("shows the current checkout recovery detail on the first failure and on retry", async () => {+ const first = new GitManagerError({+ cwd: "/workspace",+ operation: "preparePullRequestThread",+ detail: "This PR branch is already checked out in the main repo. Use Local.",+ });+ const second = new GitCommandError({+ cwd: "/workspace",+ operation: "GitVcsDriver.createWorktree",+ command: "git worktree add",+ detail: "The worktree directory already exists. Choose another directory.",+ });+ await render();++ for (const [index, error] of [first, second].entries()) {+ prepareThread.mockImplementationOnce(async () => {+ checkoutState.error = error;+ return { _tag: "Failure", cause: Cause.fail(error) };+ });+ await page.getByRole("button", { name: "Check out", exact: true }).click();+ await page.getByRole("menuitem", { name: /In a separate worktree/ }).click();+ await vi.waitFor(() => expect(updateToast).toHaveBeenCalledTimes(index + 1));+ }+ expect(updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([+ expect.stringContaining(first.detail),+ second.detail,+ ]);+});diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 624fc420e2c..77f92ec836a 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -8,7 +8,10 @@ import {scopeProjectRef,scopeThreadRef,} from "@t3tools/client-runtime/environment";-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";import {AuthOrchestrationOperateScope,AuthSourceControlWriteScope,@@ -155,6 +158,7 @@ import {pullRequestFindingKey,pullRequestHandoffLabels,PULL_REQUEST_MERGE_METHOD_LABELS,+ checkoutFailureDescription,readableFailure,readPullRequestDetailSnapshot,resolvePullRequestReferenceHost,@@ -1214,12 +1218,12 @@ export function PullRequestDetailPanel({});if (prepared._tag === "Failure") {setHandoff(null);- const detailMessage =- prepareThread.error instanceof Error ? prepareThread.error.message : null;toastManager.update(toastId, {type: "error",title: "Could not prepare the pull request checkout",- ...(detailMessage ? { description: detailMessage } : {}),+ description: checkoutFailureDescription(+ isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),+ ),});return;}diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.tsindex ee86b2ddc25..42a5017fcd9 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts@@ -2,6 +2,7 @@ import { SourceControlProviderKind } from "@t3tools/contracts";import { resolvePlanFollowUpSubmission } from "../../proposedPlan";import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";import {+ GitCommandError,ProjectId,PullRequestAction,type PullRequestCheck,@@ -49,6 +50,7 @@ import {pullRequestCheckoutCommand,pullRequestFindingKey,pullRequestReviewOutcome,+ checkoutFailureDescription,readableFailure,readPullRequestDetailSnapshot,resolveDisplayedPullRequestDetail,@@ -1050,6 +1052,28 @@ describe("what to say when an action fails", () => {expect(readableFailure(undefined, hint)).toBe(hint);});+ it("uses bounded git diagnostics and falls back when checkout has no useful detail", () => {+ const diagnostic = (detail: string, reason?: GitCommandError["reason"]) =>+ new GitCommandError({+ cwd: "/workspace",+ operation: "GitVcsDriver.createWorktree",+ command: "git worktree add",+ detail,+ reason,+ });+ expect(+ checkoutFailureDescription(diagnostic("git worktree add failed", "path_already_exists")),+ ).toBe("git worktree add failed (path_already_exists)");+ const reason = "The worktree directory already exists. Choose another directory.";+ expect(checkoutFailureDescription(diagnostic(reason))).toBe(reason);+ expect(checkoutFailureDescription(diagnostic("x".repeat(900)))).toBe(`${"x".repeat(319)}…`);+ for (const failure of [undefined, diagnostic(""), diagnostic("exited with code 1")]) {+ expect(checkoutFailureDescription(failure)).toBe(+ "Check that the branch still exists and is not checked out elsewhere, then try again.",+ );+ }+ });+it("bounds a host that answers with a page of output", () => {const long = readableFailure(new Error("x".repeat(900)), hint);expect(long.length).toBeLessThanOrEqual(320);diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.tsindex e27659d08f8..cc20657d567 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts@@ -2,6 +2,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cliimport * as Schema from "effect/Schema";import {+ GitCommandError,PullRequestDetail,PullRequestOperationError,pullRequestHostOf,@@ -1095,6 +1096,20 @@ export function readableFailure(failure: unknown, hint: string): string {return bounded;}+const isGitCommandError = Schema.is(GitCommandError);++export function checkoutFailureDescription(failure: unknown): string {+ const description = isGitCommandError(failure)+ ? failure.reason === undefined+ ? failure.detail+ : `${failure.detail} (${failure.reason})`+ : failure;+ return readableFailure(+ description,+ "Check that the branch still exists and is not checked out elsewhere, then try again.",+ );+}+export function resolveBaseFreshness(detail: {readonly state: PullRequestState;readonly mergeability: PullRequestMergeability;diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.tsindex 4fa868f5cb1..eaaf92d77ea 100644--- a/apps/web/src/components/pullRequest/usePullRequestActions.ts+++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts@@ -1,6 +1,9 @@import { useAtomCommand } from "~/state/use-atom-command";import { scopeProjectRef } from "@t3tools/client-runtime/environment";-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";import type {EnvironmentId,ProjectId,@@ -28,7 +31,12 @@ import type { ReviewCommentContext } from "~/reviewCommentContext";import { pullRequestEnvironment } from "~/state/pullRequests";import { toastManager } from "../ui/toast";-import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";+import {+ checkoutFailureDescription,+ handoffPrompt,+ handoffReviewComments,+ readableFailure,+} from "./pullRequestDetail.logic";import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";export function usePullRequestDefaultMergeMethodResolver(@@ -337,12 +345,12 @@ export function usePullRequestHandoffs({});if (prepared._tag === "Failure") {setHandoff(null);- const detailMessage =- prepareThread.error instanceof Error ? prepareThread.error.message : null;toastManager.update(toastId, {type: "error",title: "Could not prepare the pull request checkout",- ...(detailMessage ? { description: detailMessage } : {}),+ description: checkoutFailureDescription(+ isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),+ ),});return;}