Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions apps/web/src/components/pullRequest/PullRequestDetailActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import type {
} from "@t3tools/contracts";
import { CheckIcon, ChevronDownIcon, FolderGit2Icon, GitBranchIcon, PlayIcon } from "lucide-react";
import { Branch, T, useGT } from "gt-react";
import type { ReactNode } from "react";
import { useState, type ReactNode } from "react";

import { AnimatedWidth } from "~/components/AnimatedWidth";
import { cn } from "~/lib/utils";
import { useEnvironmentQuery } from "~/state/query";
import { createCheckoutBranchSubscription } from "~/state/vcs";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
Expand Down Expand Up @@ -79,6 +81,7 @@ export function PullRequestCheckoutMenu({
handoff,
checkoutRoot,
canPrepareWorktree,
sameRepositoryHead,
canCheckoutHere,
onCheckout,
pickableEnvironments,
Expand All @@ -89,6 +92,7 @@ export function PullRequestCheckoutMenu({
handoff: string | null;
checkoutRoot: string | null;
canPrepareWorktree: boolean;
sameRepositoryHead: string | null;
canCheckoutHere: boolean;
onCheckout: (mode: "worktree" | "local") => void;
pickableEnvironments: ReadonlyArray<PickableEnvironment>;
Expand All @@ -97,8 +101,24 @@ export function PullRequestCheckoutMenu({
term: ChangeRequestTermKind;
}) {
const gt = useGT();
const [subscribeBranch, setSubscribeBranch] = useState<ReturnType<
typeof createCheckoutBranchSubscription
> | null>(null);
const branchAtom =
checkoutRoot !== null && sameRepositoryHead !== null && canPrepareWorktree
? (subscribeBranch?.({ environmentId: actingEnvironmentId, input: { cwd: checkoutRoot } }) ??
null)
: null;
const branch = useEnvironmentQuery(branchAtom);
const checkingBranch = branchAtom !== null && branch.data === null && branch.error === null;
const worktreeBranchAlreadyCheckedOut =
sameRepositoryHead !== null && branch.data?.refName === sameRepositoryHead;
return (
<Menu>
<Menu
onOpenChange={(open) =>
setSubscribeBranch(() => (open ? createCheckoutBranchSubscription() : null))
}
>
<Tooltip>
<TooltipTrigger
render={
Expand Down Expand Up @@ -132,14 +152,23 @@ export function PullRequestCheckoutMenu({
</TooltipPopup>
</Tooltip>
<MenuPopup align="end" side="bottom">
<MenuItem disabled={!canPrepareWorktree} onClick={() => onCheckout("worktree")}>
<MenuItem
disabled={!canPrepareWorktree || checkingBranch || worktreeBranchAlreadyCheckedOut}
onClick={() => onCheckout("worktree")}
>
<GitBranchIcon className="mt-1 size-3.5 shrink-0 self-start" />
<span className="flex min-w-0 flex-col">
<span>
<T>In a separate worktree</T>
</span>
<span className="text-xs text-muted-foreground">
<T>Its own folder and thread. Nothing you have open moves.</T>
{worktreeBranchAlreadyCheckedOut ? (
<T>Checked out here</T>
) : checkingBranch ? (
<T>Checking…</T>
) : (
<T>Its own folder and thread. Nothing you have open moves.</T>
)}
</span>
</span>
</MenuItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { RegistryContext } from "@effect/atom-react";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
Expand All @@ -7,18 +8,26 @@ import {
type PullRequestDetailView,
} from "@t3tools/contracts";
import { expect, it, vi } from "vite-plus/test";
import { AsyncResult, Atom } from "effect/reactivity";
import { page, userEvent } from "vite-plus/test/browser";
import appCss from "~/index.css?inline";
import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { act, fakeTimers, render } from "../../../test/render";

const { command, permissions, reads, shown } = vi.hoisted(() => ({
const { command, createCheckoutBranch, permissions, reads, shown } = vi.hoisted(() => ({
command: vi.fn(),
createCheckoutBranch: vi.fn(),
permissions: { checkout: true, operate: true },
reads: { diff: [] as unknown[] },
shown: { detail: null as PullRequestDetailView | null },
}));

vi.mock(import("~/state/vcs"), async (original) => ({
...(await original()),
createCheckoutBranchSubscription: createCheckoutBranch,
}));

vi.mock(import("~/state/session"), async (original) => ({
...(await original()),
useEnvironmentScope: (_environmentId: unknown, scope: unknown) =>
Expand Down Expand Up @@ -155,9 +164,73 @@ function setup() {
reads.diff = [];
shown.detail = detail;
command.mockReset();
createCheckoutBranch.mockReset();
useComposerDraftStore.setState({ draftsByThreadKey: {} });
}

it("reads the checkout branch again when the menu reopens", async () => {
setup();
shown.detail = { ...detail, headRepositoryNameWithOwner: detail.repository };
const before = Atom.make(AsyncResult.success({ refName: "feature" }));
const after = Atom.make(AsyncResult.success({ refName: "main" }));
createCheckoutBranch.mockReturnValueOnce(() => before).mockReturnValueOnce(() => after);
await using screen = await render(panel());
const checkout = screen.getByRole("button", { name: "Check out", exact: true });
await userEvent.click(checkout);
const worktree = page.getByRole("menuitem", { name: /In a separate worktree/ });
await expect.element(worktree.getByText("Checked out here", { exact: true })).toBeVisible();
await userEvent.keyboard("{Escape}");
await userEvent.click(checkout);
await expect.element(worktree).toBeEnabled();
});

it.each([
{ branch: "feature", headRepository: "owner/repo", blocked: true },
{ branch: "main", headRepository: "owner/repo", blocked: false },
{ branch: "feature", headRepository: "fork/repo", blocked: false },
])(
"checks worktree checkout for $headRepository with $branch checked out",
async ({ branch, headRepository, blocked }) => {
setup();
const status = Atom.make(AsyncResult.success({ refName: branch }));
createCheckoutBranch.mockReturnValue(() => status);
shown.detail = { ...detail, headRepositoryNameWithOwner: headRepository };
await using screen = await render(panel());
await userEvent.click(screen.getByRole("button", { name: "Check out", exact: true }));
const worktree = page.getByRole("menuitem", { name: /In a separate worktree/ });
if (blocked) {
await expect.element(worktree).toBeDisabled();
await expect.element(worktree.getByText("Checked out here", { exact: true })).toBeVisible();
} else {
await expect.element(worktree).toBeEnabled();
}
await expect.element(page.getByRole("menuitem", { name: /In this repository/ })).toBeEnabled();
},
);

it("waits for the local branch only after the checkout menu opens", async () => {
setup();
shown.detail = { ...detail, headRepositoryNameWithOwner: detail.repository };
const branch = Atom.make<AsyncResult.AsyncResult<{ refName: string }, never>>(
AsyncResult.initial(true),
);
createCheckoutBranch.mockReturnValue(() => branch);
await using screen = await render(
<RegistryContext.Provider value={appAtomRegistry}>{panel()}</RegistryContext.Provider>,
);
expect(createCheckoutBranch).not.toHaveBeenCalled();
await userEvent.click(screen.getByRole("button", { name: "Check out", exact: true }));
await expect
.element(page.getByRole("menuitem", { name: /In a separate worktree/ }))
.toBeDisabled();
expect(createCheckoutBranch).toHaveBeenCalledOnce();
await expect.element(page.getByRole("menuitem", { name: /In this repository/ })).toBeEnabled();
await act(() => appAtomRegistry.set(branch, AsyncResult.success({ refName: "main" })));
await expect
.element(page.getByRole("menuitem", { name: /In a separate worktree/ }))
.toBeEnabled();
});

it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
"disables conflict checkout when the connection loses %s",
async (scope) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1530,6 +1530,11 @@ export function PullRequestDetailPanel({
handoff={handoff}
checkoutRoot={checkoutRoot}
canPrepareWorktree={canPrepareWorktree}
sameRepositoryHead={
detail !== null && detail.headRepositoryNameWithOwner === detail.repository
? detail.headBranch
: null
}
canCheckoutHere={prepareThread.isAllowed}
onCheckout={startCheckout}
pickableEnvironments={pickableEnvironments}
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -6807,6 +6807,7 @@
"853a77d42f86c918": "Ausgecheckt, aber der Thread ist geblieben, wo er war",
"0746dfa692f895cc": "Der Checkout ist auf `{branch}` bereit. Richte einen Thread über die Branch-Auswahl darauf aus und frage dann erneut.",
"88db70a96177d202": "Hier ausgecheckt",
"c9a052ee6afb40d4": "Hier ausgecheckt",
"baa66fde3613022b": "Ausgecheckt",
"10feb68552356a08": "{term, select, mr {Dieses Repository ist auf dem Branch des Merge Requests, mit einem darauf geöffneten Thread.} cr {Dieses Repository ist auf dem Branch der Änderungsanfrage, mit einem darauf geöffneten Thread.} other {Dieses Repository ist auf dem Branch des Pull Requests, mit einem darauf geöffneten Thread.}}",
"c0298c6b34aa5de1": "{term, select, mr {Der Merge Request ist in einem eigenen Worktree, mit einem darauf geöffneten Thread.} cr {Die Änderungsanfrage ist in einem eigenen Worktree, mit einem darauf geöffneten Thread.} other {Der Pull Request ist in einem eigenen Worktree, mit einem darauf geöffneten Thread.}}",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -6814,6 +6814,7 @@
"853a77d42f86c918": "Checked out, but the thread stayed where it was",
"0746dfa692f895cc": "The checkout is ready on `{branch}`. Point a thread at it from the branch picker, then ask again.",
"88db70a96177d202": "Checked out here",
"c9a052ee6afb40d4": "Checked out here",
"baa66fde3613022b": "Checked out",
"10feb68552356a08": "This repository is on the {term, select, mr {merge request} cr {change request} other {pull request}}'s branch, with a thread open on it.",
"c0298c6b34aa5de1": "The {term, select, mr {merge request} cr {change request} other {pull request}} is in its own worktree, with a thread open on it.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -6807,6 +6807,7 @@
"853a77d42f86c918": "Checkout hecho, pero el hilo se quedó donde estaba",
"0746dfa692f895cc": "El checkout está listo en `{branch}`. Apunta un hilo a él desde el selector de ramas y vuelve a preguntar.",
"88db70a96177d202": "Checkout hecho aquí",
"c9a052ee6afb40d4": "Checkout hecho aquí",
"baa66fde3613022b": "Checkout hecho",
"10feb68552356a08": "Este repositorio está en la rama de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}, con un hilo abierto en ella.",
"c0298c6b34aa5de1": "La {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}} está en su propio worktree, con un hilo abierto en ella.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -6808,6 +6808,7 @@
"853a77d42f86c918": "Récupérée, mais le fil est resté où il était",
"0746dfa692f895cc": "Le checkout est prêt sur `{branch}`. Pointez un fil dessus depuis le sélecteur de branche, puis reposez la question.",
"88db70a96177d202": "Récupérée ici",
"c9a052ee6afb40d4": "Récupérée ici",
"baa66fde3613022b": "Récupérée",
"10feb68552356a08": "Ce dépôt est sur la branche de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}, avec un fil ouvert dessus.",
"c0298c6b34aa5de1": "La {term, select, mr {merge request} cr {demande de modification} other {pull request}} est dans son propre worktree, avec un fil ouvert dessus.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -6777,6 +6777,7 @@
"853a77d42f86c918": "チェックアウトしましたが、スレッドは元のままです",
"0746dfa692f895cc": "`{branch}` でチェックアウトの準備ができました。ブランチの選択からスレッドをそこに向けてから、もう一度質問してください。",
"88db70a96177d202": "ここでチェックアウトしました",
"c9a052ee6afb40d4": "ここでチェックアウトしました",
"baa66fde3613022b": "チェックアウトしました",
"10feb68552356a08": "{term, select, mr {このリポジトリはマージリクエストのブランチにあり、そのスレッドが開いています。} cr {このリポジトリは変更リクエストのブランチにあり、そのスレッドが開いています。} other {このリポジトリはプルリクエストのブランチにあり、そのスレッドが開いています。}}",
"c0298c6b34aa5de1": "{term, select, mr {マージリクエストは専用のワークツリーにあり、そのスレッドが開いています。} cr {変更リクエストは専用のワークツリーにあり、そのスレッドが開いています。} other {プルリクエストは専用のワークツリーにあり、そのスレッドが開いています。}}",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -6781,6 +6781,7 @@
"853a77d42f86c918": "체크아웃했지만 스레드는 그대로입니다",
"0746dfa692f895cc": "`{branch}`에 체크아웃이 준비되었습니다. 브랜치 선택기에서 스레드를 연결한 후 다시 질문하세요.",
"88db70a96177d202": "여기에 체크아웃됨",
"c9a052ee6afb40d4": "여기에 체크아웃됨",
"baa66fde3613022b": "체크아웃됨",
"10feb68552356a08": "이 저장소는 {term, select, mr {병합 요청의} cr {변경 요청의} other {풀 리퀘스트의}} 브랜치에 있으며, 해당 브랜치에서 스레드가 열려 있습니다.",
"c0298c6b34aa5de1": "{term, select, mr {병합 요청은} cr {변경 요청은} other {풀 리퀘스트는}} 자체 워크트리에 있으며, 해당 워크트리에서 스레드가 열려 있습니다.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -6807,6 +6807,7 @@
"853a77d42f86c918": "Checkout feito, mas a thread ficou onde estava",
"0746dfa692f895cc": "O checkout está pronto em `{branch}`. Aponte uma thread para ele pelo seletor de branch e pergunte novamente.",
"88db70a96177d202": "Checkout feito aqui",
"c9a052ee6afb40d4": "Checkout feito aqui",
"baa66fde3613022b": "Checkout feito",
"10feb68552356a08": "Este repositório está no branch {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}, com uma thread aberta nele.",
"c0298c6b34aa5de1": "{term, select, mr {O merge request está} cr {A solicitação de alteração está} other {O pull request está}} em um worktree próprio, com uma thread aberta nele.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -6807,6 +6807,7 @@
"853a77d42f86c918": "Переключено, но тред остался на месте",
"0746dfa692f895cc": "Checkout готов в `{branch}`. Укажите на него тред через выбор ветки и спросите снова.",
"88db70a96177d202": "Переключено здесь",
"c9a052ee6afb40d4": "Переключено здесь",
"baa66fde3613022b": "Переключено",
"10feb68552356a08": "{term, select, mr {Этот репозиторий на ветке мерж-реквеста, и для неё открыт тред.} cr {Этот репозиторий на ветке запроса на изменение, и для неё открыт тред.} other {Этот репозиторий на ветке пул-реквеста, и для неё открыт тред.}}",
"c0298c6b34aa5de1": "{term, select, mr {Мерж-реквест в отдельном рабочем дереве, и для него открыт тред.} cr {Запрос на изменение в отдельном рабочем дереве, и для него открыт тред.} other {Пул-реквест в отдельном рабочем дереве, и для него открыт тред.}}",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -6813,6 +6813,7 @@
"853a77d42f86c918": "Utcheckad, men tråden stannade där den var",
"0746dfa692f895cc": "Utcheckningen är redo på `{branch}`. Peka en tråd mot den från grenväljaren och fråga sedan igen.",
"88db70a96177d202": "Utcheckad här",
"c9a052ee6afb40d4": "Utcheckad här",
"baa66fde3613022b": "Utcheckad",
"10feb68552356a08": "Det här repot är på grenen för {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}, med en tråd öppen på den.",
"c0298c6b34aa5de1": "{term, select, mr {Merge requesten} cr {Ändringsbegäran} other {Pull requesten}} finns i en egen worktree, med en tråd öppen på den.",
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/i18n/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -6820,6 +6820,7 @@
"853a77d42f86c918": "已检出,但会话仍在原处",
"0746dfa692f895cc": "工作副本已在 `{branch}` 上准备好。请从分支选择器将会话指向它,然后再次提问。",
"88db70a96177d202": "已在此检出",
"c9a052ee6afb40d4": "已在此检出",
"baa66fde3613022b": "已检出",
"10feb68552356a08": "此仓库位于该 {term, select, mr {merge request} cr {change request} other {pull request}} 的分支上,并已在其上打开一个会话。",
"c0298c6b34aa5de1": "该 {term, select, mr {merge request} cr {change request} other {pull request}} 位于其专属工作树中,并已在其上打开一个会话。",
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/state/vcs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { subscribeVcsBranch } from "@t3tools/client-runtime/rpc";
import { createEnvironmentSubscriptionAtomFamily } from "@t3tools/client-runtime/state/runtime";
import {
createVcsActionManager,
createVcsEnvironmentAtoms,
Expand All @@ -12,6 +14,15 @@ import { subscribeDocumentReturn } from "../lib/documentActivity";
export const vcsEnvironment = createVcsEnvironmentAtoms(connectionAtomRuntime);
export const vcsActionManager = createVcsActionManager(connectionAtomRuntime);

// An independent subscription avoids reusing another view's cached HEAD.
export function createCheckoutBranchSubscription() {
return createEnvironmentSubscriptionAtomFamily(connectionAtomRuntime, {
label: "web:vcs:checkout-branch",
idleTtlMs: 0,
subscribe: subscribeVcsBranch,
});
}

/** Only what a chat view reads, so changing file counts don't re-render it on every edit. */
export const chatGitStatusAtom = Atom.family((status: ReturnType<typeof vcsEnvironment.status>) =>
Atom.map(status, (result) => {
Expand Down
Loading