diff --git a/docs/glossary.md b/docs/glossary.md index a6ff393c6a..acac5f62e9 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -6,7 +6,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Workspace** — One concrete `cwd` on one daemon, with git state; belongs to exactly one project. Its `id` is opaque workspace identity; its `cwd` is the filesystem directory. UI: "Workspace". Code: `WorkspaceDescriptorPayload` (`packages/protocol/src/messages.ts:2178`). Don't confuse with: Branch (one branch can back many workspaces via worktrees). Forbidden: "Folder", "Directory" as UI label. - **Archive workspace** — Removes one workspace from active use and archives everything it owns. UI, CLI, and MCP always say "Archive workspace", regardless of backing. The daemon leaves ordinary directories intact and removes a Paseo-owned worktree only when no active workspace still references it. - **Workspace kind** — `"directory" | "local_checkout" | "worktree"`. The git-derived, persisted property of a workspace, used across its lifetime (archive safety, sidebar, grouping). Derived from the cwd's git reality by `deriveWorkspaceKind` in `workspace-registry-model.ts`, not stored from a user choice. Don't confuse with **Isolation** (the create-time intent). -- **Isolation** — Create-time choice for a new workspace: reuse the existing checkout (**Local**) or cut a dedicated git worktree (**New worktree**). A transient setup input, also remembered as a create-form preference; it is not a workspace property. UI: "Isolation" control on the New Workspace screen. Code: `isolation` (`"local" | "worktree"`), `useWorkspaceIsolation` (`packages/app/src/screens/new-workspace-screen.tsx`); persisted as `FormPreferences.isolation` (`packages/app/src/create-agent-preferences/preferences.ts`). Distinct from **Workspace kind**, which is the git-derived property the intent produces (Local → `local_checkout` or `directory` by git-ness; New worktree → `worktree`). On the wire it is the create request's `source.kind` (`directory | worktree`, `packages/protocol/src/messages.ts:1693`). +- **Isolation** — Create-time choice for a new workspace, with three options: work in the project's own directory (**Project directory**), cut a dedicated git worktree (**New worktree**), or work in a git worktree already on disk (**Existing worktree**). A transient setup input; Project directory and New worktree are also remembered as a create-form preference. It is not a workspace property. UI: "Isolation" control on the New Workspace screen. Code: `isolation` (`"local" | "worktree"`), `useWorkspaceIsolation` (`packages/app/src/screens/new-workspace-screen.tsx`); persisted as `FormPreferences.isolation` (`packages/app/src/create-agent-preferences/preferences.ts`). Existing worktree is not a third value: it is `local` with the worktree's path as the source directory (`existingWorktreePath` in `packages/app/src/screens/new-workspace/setup-model.ts`), so plugins, preferences, and the wire see `local`. Distinct from **Workspace kind**, which is the git-derived property the intent produces (Project directory → `local_checkout` or `directory` by git-ness; New worktree and Existing worktree → `worktree`). On the wire it is the create request's `source.kind` (`directory | worktree`, `packages/protocol/src/messages.ts`). Forbidden: "Local" as the UI label. - **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run". - **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`). - **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host). @@ -17,7 +17,8 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Forge** — Git hosting service behind Paseo's change-request features: GitHub, GitLab, Gitea, Forgejo, or a future registered adapter. Code: `ForgeService`, `forge-registry`, `forge-resolver`. Use `forge` for internal abstraction and registry IDs; use concrete forge names only when a behavior or RPC is forge-specific. - **Change request** — Forge-neutral term for a proposed branch-to-branch code change. UI normally renders the forge noun instead: GitHub/Gitea/Forgejo "PR", GitLab "MR". Code: `forge_change_request` attachments, `checkoutSource: { kind: "change_request" }`, and PR/MR status payloads. - **MR** — GitLab merge request. UI label for GitLab change requests only; do not use MR for GitHub/Gitea/Forgejo. -- **Worktree** — Paseo-managed git worktree (`~/.paseo/worktrees/{name}`); also a `workspaceKind` value. User-facing creation treats it as the `worktree` workspace isolation choice. Code and `paseo.json` retain worktree terminology for git lifecycle implementation. Forbidden: "Checkout" as a product synonym. +- **Worktree** — A git worktree: any working directory that `git worktree list` reports for the repository, whoever created it. Paseo creates its own under `$PASEO_HOME/worktrees/` and owns their setup and removal; worktrees made with `git worktree add` are listed by the Existing worktree picker but never removed by Paseo. Also a `workspaceKind` value. Code: `checkout.worktrees.list` RPC (`listGitWorktrees` in `packages/server/src/utils/worktree.ts`), gated on `server_info.features.checkoutWorktreeList`. Code and `paseo.json` retain worktree terminology for git lifecycle implementation. Don't confuse with: **Workspace** (Paseo's place for a task; several workspaces can work in one worktree, and a worktree with no workspace is still a worktree). Forbidden: "Checkout" as a product synonym. +- **Branch off / Check out** — What a New worktree does with the branch or pull request picked in the ref picker. **Branch off** starts a new branch from it; **Check out** works on that branch itself. Branches default to Branch off and pull requests to Check out; the user can switch either. Branching off a pull request starts the new branch at the pull request's head with no upstream. Git keeps a branch in one worktree at a time, so checking out a branch another worktree holds sends the user to that worktree instead of creating a copy. Code: `RefAction` (`packages/app/src/screens/new-workspace-picker-item.ts`), the worktree source's `action` (`"branch-off" | "checkout"`), gated on `server_info.features.worktreeRefActions`. - **Repository / Remote** — Internal Git observations. They may produce mutable kind, branch, and project-grouping metadata but never the host-local project ID, root, display name, or workspace membership. No UI label. - **Sidebar items** — The configurable entries of the app sidebar, in two sections. Header: the rows at the head of the sidebar — New workspace, History, Search, Schedules, and plugin header items. Footer: the full-width rows between Add project and the footer icon row — Usage and plugin footer items. Add project and the icon row (Hosts, Help and support, Settings) are fixed and are not sidebar items. A plugin item may render several rows, such as one per bot; it is still one item that moves and hides as a block. Each section's order and visibility is one per-device preference (`AppSettings.sidebarNavItems`, `AppSettings.sidebarFooterItems`); every item may be off. UI: the Header and Footer cards on the Sidebar settings page. Code: `packages/app/src/sidebar-nav/model.ts` resolves a section, and the sidebar (`components/sidebar/sidebar-nav-rows.tsx`, the footer in `components/left-sidebar.tsx`) and the settings page (`screens/settings/sidebar/sidebar-nav-section.tsx`) read it through `useSidebarNavItems(section)`. Never hardcode one of these entries or add a second place that decides which ones show. Don't confuse with **Explorer sidebar**. - **Explorer sidebar** — The dedicated navigation dock containing the Files and Changes trees. UI: "Explorer sidebar". Code: `packages/app/src/workspace-tabs/explorer-sidebar.ts`; persisted pane identifiers retain the `explorer` spelling. See [explorer-sidebar.md](explorer-sidebar.md). diff --git a/docs/plugins.md b/docs/plugins.md index a9895f2aee..30757c1f93 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -788,14 +788,15 @@ is the [New workspace items reference](../public-docs/plugins/reference.md#new-w The screen's choices that a plugin may change live in one plain store, `createNewWorkspaceSetup` (`packages/app/src/screens/new-workspace/setup-model.ts`): the base -picker selection, the manual isolation, the branch name and the workspace metadata. The pickers and +picker selection, the manual isolation, the chosen existing worktree, the Branch off or Check out +action per ref list, the branch name and the workspace metadata. The pickers and the plugin commands write to it, so a command sees what an earlier command left. Project and host stay in the screen's hooks (`useNewWorkspaceHostSelector` reconciles them against each other), and they are read-only to plugins; a command that switched them would unmount the item that called it. The store is built in the render that creates the screen, with what the screen derives from its hooks (the lock, the project, whether the project can make worktrees, whether the host supports -metadata), so a command is valid from a child's first effect, which runs before the screen's own +metadata and ref actions, the project's git worktrees), so a command is valid from a child's first effect, which runs before the screen's own effects. `syncInputs` refreshes those inputs in a layout effect on every commit, and commands read them when they run, never from the render that built them. The pickers and the commands pick through the same `chooseBase` and `chooseIsolation`, so a plugin command has the effects of a diff --git a/packages/app/e2e/browser/new-workspace.spec.ts b/packages/app/e2e/browser/new-workspace.spec.ts index 7206c9f52e..7ee6fe9737 100644 --- a/packages/app/e2e/browser/new-workspace.spec.ts +++ b/packages/app/e2e/browser/new-workspace.spec.ts @@ -1,4 +1,6 @@ +import { execSync } from "node:child_process"; import { existsSync } from "node:fs"; +import { realpath } from "node:fs/promises"; import path from "node:path"; import { buildHostWorkspaceRoute } from "@/utils/host-routes"; import { expect, test } from "../support/fixtures"; @@ -890,6 +892,53 @@ test.describe("New workspace flow", () => { }); }); + test("existing worktree starts the first agent in the chosen worktree", async ({ page }) => { + const tempRepo = await createTempGitRepo("existing-worktree-"); + // Made with git, not Paseo: the list holds every git worktree of the repository. + const worktreePath = path.join(tempRepo.path, "manual-worktree"); + execSync(`git worktree add -b e2e/manual ${JSON.stringify(worktreePath)}`, { + cwd: tempRepo.path, + stdio: "ignore", + }); + + try { + const openedProject = await openProjectViaDaemon(client, tempRepo.path); + localWorkspaceIds.add(openedProject.workspaceId); + localProjectIds.add(openedProject.projectId); + + await gotoAppShell(page); + await waitForSidebarHydration(page); + await openNewWorkspaceComposer(page, { + projectKey: openedProject.projectKey, + projectDisplayName: openedProject.projectDisplayName, + }); + await selectWorkspaceIsolation(page, "existing"); + await expect(page.getByTestId("new-workspace-worktree-picker-trigger")).toContainText( + "e2e/manual", + ); + await submitNewWorkspacePrompt(page); + + const createdWorkspace = await assertNewWorkspaceSidebarAndHeader(page, { + serverId: getServerId(), + client, + previousWorkspaceId: openedProject.workspaceId, + projectDisplayName: openedProject.projectDisplayName, + }); + localWorkspaceIds.add(createdWorkspace.workspaceId); + expect(await realpath(createdWorkspace.workspaceDirectory)).toBe( + await realpath(worktreePath), + ); + + const agentTabs = page + .getByTestId(`workspace-deck-entry-${getServerId()}:${createdWorkspace.workspaceId}`) + .filter({ visible: true }) + .locator('[data-testid^="workspace-tab-agent_"]'); + await expect(agentTabs).toHaveCount(1, { timeout: 30_000 }); + } finally { + await tempRepo.cleanup(); + } + }); + test("branch picker opens via keyboard and selects the filtered option on Enter", async ({ page, }) => { diff --git a/packages/app/e2e/browser/schedules-project-target.spec.ts b/packages/app/e2e/browser/schedules-project-target.spec.ts index 4c36eb3985..fe09a02408 100644 --- a/packages/app/e2e/browser/schedules-project-target.spec.ts +++ b/packages/app/e2e/browser/schedules-project-target.spec.ts @@ -362,7 +362,7 @@ test.describe("Schedules project target", () => { ).toHaveCount(0); await page.getByTestId("schedule-isolation-trigger").click(); await page.getByTestId("schedule-isolation-worktree").click(); - await expect(page.getByTestId("schedule-isolation-trigger")).toContainText("Worktree"); + await expect(page.getByTestId("schedule-isolation-trigger")).toContainText("New worktree"); await page.getByTestId("schedule-archive-on-finish-switch").click(); await page.getByLabel("Schedule name").fill(scheduleName); await page.getByLabel("Prompt").fill("Run with custom workspace cleanup."); @@ -383,7 +383,7 @@ test.describe("Schedules project target", () => { const formSheet = page.getByTestId("schedule-form-sheet"); await expect(formSheet).toBeVisible({ timeout: 10_000 }); await expectStableHeight(formSheet); - await expect(page.getByTestId("schedule-isolation-trigger")).toContainText("Worktree"); + await expect(page.getByTestId("schedule-isolation-trigger")).toContainText("New worktree"); await expect(page.getByTestId("schedule-archive-on-finish-switch")).toHaveAttribute( "aria-checked", "false", diff --git a/packages/app/e2e/mobile/composer-keyboard/android.sh b/packages/app/e2e/mobile/composer-keyboard/android.sh index b3b20ed2b7..f40246bb4f 100755 --- a/packages/app/e2e/mobile/composer-keyboard/android.sh +++ b/packages/app/e2e/mobile/composer-keyboard/android.sh @@ -583,7 +583,7 @@ run_host_scroll() { prepare_composer closed if [[ "${host}" == new-workspace ]]; then ad press 'id="workspace-create-isolation-trigger"' --settle - ad press 'text="Local"' --settle + ad press 'text="Project directory"' --settle fi # Submit through each real host; draft/workspace creation then mounts its chat. # A selectable mock model keeps this test independent of provider credentials. diff --git a/packages/app/e2e/support/helpers/new-workspace.ts b/packages/app/e2e/support/helpers/new-workspace.ts index d383f8cd34..6d2833bc8c 100644 --- a/packages/app/e2e/support/helpers/new-workspace.ts +++ b/packages/app/e2e/support/helpers/new-workspace.ts @@ -334,16 +334,19 @@ export async function selectNewWorkspaceProject( await expectNewWorkspaceProjectSelected(page, input.projectDisplayName); } -// The isolation trigger renders the active isolation's label ("Local" / "New -// worktree"), so asserting its text proves what the screen currently remembers. -const ISOLATION_TRIGGER_LABEL: Record<"local" | "worktree", string> = { - local: "Local", +type IsolationChoice = "local" | "worktree" | "existing"; + +// The isolation trigger renders the active isolation's label ("Project directory" / "New +// worktree" / "Existing worktree"), so asserting its text proves what the screen remembers. +const ISOLATION_TRIGGER_LABEL: Record = { + local: "Project directory", worktree: "New worktree", + existing: "Existing worktree", }; export async function expectWorkspaceIsolationSelected( page: Page, - isolation: "local" | "worktree", + isolation: IsolationChoice, ): Promise { const trigger = page.getByRole("button", { name: "Workspace isolation" }); await expect(trigger).toBeVisible({ timeout: 30_000 }); @@ -352,7 +355,7 @@ export async function expectWorkspaceIsolationSelected( export async function selectWorkspaceIsolation( page: Page, - isolation: "local" | "worktree", + isolation: IsolationChoice, ): Promise { const trigger = page.getByTestId("workspace-create-isolation-trigger"); await expect(trigger).toBeVisible({ timeout: 30_000 }); @@ -385,8 +388,16 @@ export async function selectBranchInPicker(page: Page, name: string): Promise { + const tab = page.getByTestId(`new-workspace-ref-picker-tab-${list}`); + await expect(tab).toBeVisible({ timeout: 30_000 }); + await tab.click(); +} + export async function searchAndSelectBranchInPicker(page: Page, name: string): Promise { - const searchInput = page.getByPlaceholder("Search branches and PRs"); + await showRefList(page, "branches"); + const searchInput = page.getByPlaceholder("Search branches"); await expect(searchInput).toBeVisible({ timeout: 30_000 }); await searchInput.fill(name); await selectBranchInPicker(page, name); @@ -410,6 +421,7 @@ export async function captureStartingRefPicker(page: Page, screenshotPath: strin } export async function selectGitHubPrInPicker(page: Page, number: number): Promise { + await showRefList(page, "pull-requests"); const prRow = page.getByTestId(`new-workspace-ref-picker-pr-${number}`); await expect(prRow).toBeVisible({ timeout: 30_000 }); await prRow.click(); @@ -432,7 +444,7 @@ export async function openBranchPicker(page: Page): Promise { } export async function selectPickerOptionByKeyboard(page: Page, label: string): Promise { - const searchInput = page.getByPlaceholder("Search branches and PRs"); + const searchInput = page.getByPlaceholder("Search branches"); await expect(searchInput).toBeVisible({ timeout: 30_000 }); await page.keyboard.type(label); await expect(page.getByTestId(`new-workspace-ref-picker-branch-${label}`)).toBeVisible({ diff --git a/packages/app/src/components/schedules/schedule-form-sheet.tsx b/packages/app/src/components/schedules/schedule-form-sheet.tsx index f66e70b520..3d12599350 100644 --- a/packages/app/src/components/schedules/schedule-form-sheet.tsx +++ b/packages/app/src/components/schedules/schedule-form-sheet.tsx @@ -825,20 +825,22 @@ function ScheduleIsolationField({ { id: "local", value: "local", - label: "Local", + label: "Project directory", testID: "schedule-isolation-local", }, { id: "worktree", value: "worktree", - label: "Worktree", + label: "New worktree", testID: "schedule-isolation-worktree", }, ], [], ); const selectedDisplay = useMemo( - () => ({ label: state.effectiveIsolation === "worktree" ? "Worktree" : "Local" }), + () => ({ + label: state.effectiveIsolation === "worktree" ? "New worktree" : "Project directory", + }), [state.effectiveIsolation], ); const triggerLeading = useMemo( diff --git a/packages/app/src/components/ui/combobox.tsx b/packages/app/src/components/ui/combobox.tsx index cae61ea100..ef3e76bc9d 100644 --- a/packages/app/src/components/ui/combobox.tsx +++ b/packages/app/src/components/ui/combobox.tsx @@ -130,6 +130,8 @@ export interface ComboboxProps { desktopFixedHeight?: number; /** Content rendered above the scroll area on desktop (sticky header). */ stickyHeader?: ReactNode; + /** Controls rendered between the search field and the options, such as list tabs. */ + toolbar?: ReactNode; /** Content rendered below the scroll area. */ footer?: ReactNode; /** When true, selecting an option does not close the picker (multi-select mode). */ @@ -227,6 +229,8 @@ export function SearchInput({ export interface ComboboxItemProps { label: string; + /** Muted text before the label, such as a pull request number. */ + labelPrefix?: string; description?: string; kind?: "directory" | "file"; leadingSlot?: ReactNode; @@ -243,6 +247,7 @@ export interface ComboboxItemProps { export function ComboboxItem({ label, + labelPrefix, description, kind, leadingSlot, @@ -284,8 +289,15 @@ export function ComboboxItem({ ); const itemContentStyle = useMemo( - () => [styles.comboboxItemContent, description && styles.comboboxItemContentInline], - [description], + () => [ + styles.comboboxItemContent, + (description || labelPrefix) && styles.comboboxItemContentInline, + ], + [description, labelPrefix], + ); + const labelStyle = useMemo( + () => [styles.comboboxItemLabel, labelPrefix && styles.comboboxItemLabelAfterPrefix], + [labelPrefix], ); return ( @@ -299,7 +311,12 @@ export function ComboboxItem({ > {leadingContent} - + {labelPrefix ? ( + + {labelPrefix} + + ) : null} + {label} {description ? ( @@ -920,6 +937,7 @@ interface MobileBodyProps { header: SheetHeader | undefined; onClose: () => void; stickyHeader: ReactNode; + toolbar: ReactNode; footer: ReactNode; searchable: boolean; hasChildren: boolean; @@ -1012,6 +1030,7 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement { resetKey={props.searchResetKey} /> ) : null} + {props.toolbar ? {props.toolbar} : null} )} {props.hasChildren && !props.mobileChildrenScrollEnabled ? ( @@ -1072,6 +1091,7 @@ interface DesktopBodyProps { handleDesktopContentLayout: (event: LayoutChangeEvent) => void; header: SheetHeader | undefined; stickyHeader: ReactNode; + toolbar: ReactNode; footer: ReactNode; searchable: boolean; searchPlaceholder: string; @@ -1126,6 +1146,7 @@ function DesktopComboboxChildrenBody(props: { function DesktopComboboxOptionsBody(props: { header: SheetHeader | undefined; stickyHeader: ReactNode; + toolbar: ReactNode; searchable: boolean; searchPlaceholder: string; searchQuery: string; @@ -1165,6 +1186,7 @@ function DesktopComboboxOptionsBody(props: { useBottomSheetInput={false} /> )} + {props.toolbar ? {props.toolbar} : null} {props.effectiveOptionsPosition === "above-search" ? ( ({ borderBottomColor: theme.colors.border, ...(IS_WEB ? {} : { marginHorizontal: theme.spacing[1] }), }, + toolbar: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + gap: theme.spacing[2], + // The search field's inset, so a filled control starts on the rows' leading rail. + paddingHorizontal: theme.spacing[3], + paddingVertical: theme.spacing[2], + borderBottomWidth: 1, + borderBottomColor: theme.colors.border, + ...(IS_WEB ? {} : { marginHorizontal: theme.spacing[1] }), + }, searchInput: { flex: 1, paddingVertical: theme.spacing[3], @@ -1752,6 +1790,16 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foreground, flexShrink: 0, }, + comboboxItemLabelPrefix: { + fontSize: theme.fontSize.base, + color: theme.colors.foregroundMuted, + fontVariant: ["tabular-nums"], + flexShrink: 0, + }, + // The prefix holds its width; the label gives way. + comboboxItemLabelAfterPrefix: { + flexShrink: 1, + }, comboboxItemDescription: { fontSize: theme.fontSize.sm, color: theme.colors.foregroundMuted, diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index 05d7fedec4..5b18b7499d 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -8,6 +8,7 @@ import { type ControlSize, } from "@/components/ui/control-geometry"; import { useContainedControlSize } from "@/components/ui/control-size"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import type { Theme } from "@/styles/theme"; type SegmentedControlIconRenderer = (props: { color: string; size: number }) => ReactNode; @@ -18,6 +19,8 @@ export interface SegmentedControlOption { icon?: SegmentedControlIconRenderer; disabled?: boolean; testID?: string; + /** Shown below the segment while the pointer is over it. */ + tooltip?: string; } interface SegmentedControlProps { @@ -136,7 +139,7 @@ function SegmentItem({ () => ({ selected: isSelected, disabled: option.disabled }), [isSelected, option.disabled], ); - return ( + const segment = ( ({ )} ); + if (!option.tooltip) return segment; + return ( + + {segment} + + {option.tooltip} + + + ); } const styles = StyleSheet.create((theme) => { @@ -220,5 +232,9 @@ const styles = StyleSheet.create((theme) => { labelSelected: { color: theme.colors.foreground, }, + tooltipText: { + fontSize: theme.fontSize.base, + color: theme.colors.popoverForeground, + }, }; }); diff --git a/packages/app/src/i18n/resources.test.ts b/packages/app/src/i18n/resources.test.ts index 7eb0072736..1f82532d27 100644 --- a/packages/app/src/i18n/resources.test.ts +++ b/packages/app/src/i18n/resources.test.ts @@ -451,7 +451,7 @@ describe("translation resources", () => { "Update the host to remove projects.", ); expect(en.newWorkspace.title).toBe("New workspace"); - expect(en.newWorkspace.refPicker.searchPlaceholder).toBe("Search branches and PRs"); + expect(en.newWorkspace.refPicker.searchBranches).toBe("Search branches"); expect(en.openProject.tiles.addProject.title).toBe("Add a project"); }); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index e885b13256..483b09ce4f 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -1399,8 +1399,9 @@ export const ar: TranslationResources = { title: "مساحة عمل جديدة", create: "يخلق", isolation: { - local: "محلي", + local: "مجلد المشروع", worktree: "شجرة عمل جديدة", + existing: "شجرة عمل موجودة", label: "العزل", }, fields: { @@ -1415,12 +1416,17 @@ export const ar: TranslationResources = { createWorktreeFailed: "فشل في إنشاء شجرة العمل", composerStateRequired: "حالة الملحن مطلوبة", selectModel: "اختر نموذجا", + branchInProjectDirectory: + "الفرع {{branch}} مفعّل في مجلد المشروع. اختر مجلد المشروع للعمل عليه، أو أنشئ فرعًا جديدًا منه.", + branchInWorktree: + "الفرع {{branch}} مفعّل في {{path}}. اختر شجرة العمل هذه من شجرة عمل موجودة، أو أنشئ فرعًا جديدًا منه.", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "اختر من أين تبدأ", + worktree: "اختر شجرة العمل التي تعمل فيها", launch: "Choose what to launch", }, refPicker: { @@ -1428,9 +1434,32 @@ export const ar: TranslationResources = { intoBase: "إلى {{baseRef}}", searching: "جارٍ البحث...", noMatchingRefs: "لا توجد مراجع مطابقة.", - searchPlaceholder: "بحث الفروع والعلاقات العامة", + searchBranches: "ابحث في الفروع", + searchPullRequests: "ابحث في طلبات الدمج", + searchPullRequests_mr: "ابحث في MR", + branches: "الفروع", + pullRequests: "طلبات الدمج", + pullRequests_mr: "MR", + pullRequestsShort: "الدمج", + pullRequestsShort_mr: "MR", + branchOff: "فرع جديد", + checkout: "العمل عليه", + branchOffHint: "ينشئ فرعًا جديدًا منه", + checkoutHint: "يعمل عليه مباشرة", + base: "الأساس", + from: "من", + branch: "الفرع", + pullRequest: "طلب الدمج", + pullRequest_mr: "MR", + inProjectDirectory: "في مجلد المشروع", + inWorktree: "في شجرة عمل", title: "ابدأ من", }, + worktreePicker: { + title: "شجرة العمل", + searchPlaceholder: "ابحث في أشجار العمل", + empty: "لا توجد أشجار عمل مطابقة.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index df535636a6..7fcd230092 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1409,8 +1409,9 @@ export const en = { title: "New workspace", create: "Create", isolation: { - local: "Local", + local: "Project directory", worktree: "New worktree", + existing: "Existing worktree", label: "Isolation", }, fields: { @@ -1425,12 +1426,17 @@ export const en = { createWorktreeFailed: "Failed to create worktree", composerStateRequired: "Composer state is required", selectModel: "Select a model", + branchInProjectDirectory: + "{{branch}} is checked out in the project directory. Choose Project directory to work on it, or branch off it.", + branchInWorktree: + "{{branch}} is checked out in {{path}}. Choose that worktree under Existing worktree, or branch off it.", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "Choose where to start from", + worktree: "Choose the worktree to work in", launch: "Choose what to launch", }, refPicker: { @@ -1438,9 +1444,32 @@ export const en = { intoBase: "into {{baseRef}}", searching: "Searching...", noMatchingRefs: "No matching refs.", - searchPlaceholder: "Search branches and PRs", + searchBranches: "Search branches", + searchPullRequests: "Search pull requests", + searchPullRequests_mr: "Search merge requests", + branches: "Branches", + pullRequests: "Pull requests", + pullRequests_mr: "Merge requests", + pullRequestsShort: "PRs", + pullRequestsShort_mr: "MRs", + branchOff: "Branch off", + checkout: "Check out", + branchOffHint: "Start a new branch from it", + checkoutHint: "Work on it directly", + base: "Base", + from: "from", + branch: "Branch", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "In project directory", + inWorktree: "In a worktree", title: "Start from", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "Search worktrees", + empty: "No matching worktrees.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index afa54968e6..b7bf6c6eba 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -1435,8 +1435,9 @@ export const es: TranslationResources = { title: "Nuevo espacio de trabajo", create: "Crear", isolation: { - local: "Local", + local: "Directorio del proyecto", worktree: "Nuevo worktree", + existing: "Worktree existente", label: "Aislamiento", }, fields: { @@ -1451,12 +1452,17 @@ export const es: TranslationResources = { createWorktreeFailed: "No se pudo crear el árbol de trabajo", composerStateRequired: "Se requiere el estado del compositor", selectModel: "Selecciona un modelo", + branchInProjectDirectory: + "{{branch}} está activa en el directorio del proyecto. Elige Directorio del proyecto para trabajar en ella, o crea una rama a partir de ella.", + branchInWorktree: + "{{branch}} está activa en {{path}}. Elige ese worktree en Worktree existente, o crea una rama a partir de ella.", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "Elige por dónde empezar", + worktree: "Elige el worktree en el que trabajar", launch: "Choose what to launch", }, refPicker: { @@ -1464,9 +1470,32 @@ export const es: TranslationResources = { intoBase: "en {{baseRef}}", searching: "Búsqueda...", noMatchingRefs: "No hay árbitros coincidentes.", - searchPlaceholder: "Buscar sucursales y relaciones públicas", + searchBranches: "Buscar ramas", + searchPullRequests: "Buscar pull requests", + searchPullRequests_mr: "Buscar merge requests", + branches: "Ramas", + pullRequests: "Pull requests", + pullRequests_mr: "Merge requests", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "Nueva rama", + checkout: "Usar directamente", + branchOffHint: "Crea una rama nueva a partir de ella", + checkoutHint: "Trabaja directamente en ella", + base: "Base", + from: "desde", + branch: "Rama", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "En el directorio del proyecto", + inWorktree: "En un worktree", title: "Empezar desde", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "Buscar worktrees", + empty: "No hay worktrees que coincidan.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index f4d498f10d..b223321b84 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -1429,8 +1429,9 @@ export const fr: TranslationResources = { title: "Nouvel espace de travail", create: "Créer", isolation: { - local: "Local", + local: "Répertoire du projet", worktree: "Nouveau worktree", + existing: "Worktree existant", label: "Isolation", }, fields: { @@ -1445,12 +1446,17 @@ export const fr: TranslationResources = { createWorktreeFailed: "Impossible de créer le worktree", composerStateRequired: "L’état de la zone de saisie est requis", selectModel: "Sélectionnez un modèle", + branchInProjectDirectory: + "{{branch}} est extraite dans le répertoire du projet. Choisissez Répertoire du projet pour y travailler, ou créez une branche à partir d’elle.", + branchInWorktree: + "{{branch}} est extraite dans {{path}}. Choisissez ce worktree dans Worktree existant, ou créez une branche à partir d’elle.", }, tooltips: { project: "Choisir le projet", host: "Choisir l’hôte", isolation: "Choisir le niveau d’isolation", startingRef: "Choisir le point de départ", + worktree: "Choisir le worktree où travailler", launch: "Choisir quoi lancer", }, refPicker: { @@ -1458,9 +1464,32 @@ export const fr: TranslationResources = { intoBase: "vers {{baseRef}}", searching: "Recherche…", noMatchingRefs: "Aucune référence correspondante.", - searchPlaceholder: "Rechercher des branches et des PR", + searchBranches: "Rechercher des branches", + searchPullRequests: "Rechercher des PR", + searchPullRequests_mr: "Rechercher des MR", + branches: "Branches", + pullRequests: "Pull requests", + pullRequests_mr: "Merge requests", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "Nouvelle branche", + checkout: "Extraire", + branchOffHint: "Crée une nouvelle branche à partir de celle-ci", + checkoutHint: "Travaille directement dessus", + base: "Base", + from: "depuis", + branch: "Branche", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "Dans le répertoire du projet", + inWorktree: "Dans un worktree", title: "Partir de", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "Rechercher des worktrees", + empty: "Aucun worktree correspondant.", + }, launch: { title: "Que lancer ?", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index c8860bde1e..1aa50bbfa3 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -1413,8 +1413,9 @@ export const ja: TranslationResources = { title: "新しいワークスペース", create: "作成", isolation: { - local: "ローカル", + local: "プロジェクトディレクトリ", worktree: "新しいワークツリー", + existing: "既存のワークツリー", label: "分離方法", }, fields: { @@ -1429,12 +1430,17 @@ export const ja: TranslationResources = { createWorktreeFailed: "ワークツリーの作成に失敗しました", composerStateRequired: "コンポーザーの状態が必要です", selectModel: "モデルを選択してください", + branchInProjectDirectory: + "{{branch}} はプロジェクトディレクトリでチェックアウト済みです。そこで作業するにはプロジェクトディレクトリを選ぶか、そこから新しいブランチを作成してください。", + branchInWorktree: + "{{branch}} は {{path}} でチェックアウト済みです。既存のワークツリーでそのワークツリーを選ぶか、そこから新しいブランチを作成してください。", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "開始点を選択", + worktree: "作業するワークツリーを選択", launch: "Choose what to launch", }, refPicker: { @@ -1442,9 +1448,32 @@ export const ja: TranslationResources = { intoBase: "{{baseRef}}に", searching: "検索中...", noMatchingRefs: "一致するRefがありません。", - searchPlaceholder: "ブランチとPRを検索", + searchBranches: "ブランチを検索", + searchPullRequests: "プルリクエストを検索", + searchPullRequests_mr: "MRを検索", + branches: "ブランチ", + pullRequests: "プルリクエスト", + pullRequests_mr: "マージリクエスト", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "新しいブランチ", + checkout: "チェックアウト", + branchOffHint: "ここから新しいブランチを作成します", + checkoutHint: "直接作業します", + base: "ベース", + from: "起点", + branch: "ブランチ", + pullRequest: "プルリクエスト", + pullRequest_mr: "マージリクエスト", + inProjectDirectory: "プロジェクトディレクトリ内", + inWorktree: "ワークツリー内", title: "開始点", }, + worktreePicker: { + title: "ワークツリー", + searchPlaceholder: "ワークツリーを検索", + empty: "一致するワークツリーがありません。", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 40608117a0..27ae440dbe 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -1406,8 +1406,9 @@ export const ko: TranslationResources = { title: "새 워크스페이스", create: "생성", isolation: { - local: "로컬", + local: "프로젝트 디렉터리", worktree: "새 워크트리", + existing: "기존 워크트리", label: "격리", }, fields: { @@ -1422,12 +1423,17 @@ export const ko: TranslationResources = { createWorktreeFailed: "워크트리를 생성하지 못했습니다", composerStateRequired: "작성기 상태가 필요합니다", selectModel: "모델을 선택하세요", + branchInProjectDirectory: + "{{branch}} 브랜치는 프로젝트 디렉터리에 체크아웃되어 있습니다. 거기서 작업하려면 프로젝트 디렉터리를 선택하거나, 새 브랜치를 만드세요.", + branchInWorktree: + "{{branch}} 브랜치는 {{path}}에 체크아웃되어 있습니다. 기존 워크트리에서 그 워크트리를 선택하거나, 새 브랜치를 만드세요.", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "시작 위치를 선택하세요", + worktree: "작업할 워크트리를 선택하세요", launch: "Choose what to launch", }, refPicker: { @@ -1435,9 +1441,32 @@ export const ko: TranslationResources = { intoBase: "{{baseRef}}(으)로", searching: "검색 중...", noMatchingRefs: "일치하는 ref가 없습니다.", - searchPlaceholder: "브랜치와 PR 검색", + searchBranches: "브랜치 검색", + searchPullRequests: "풀 리퀘스트 검색", + searchPullRequests_mr: "머지 리퀘스트 검색", + branches: "브랜치", + pullRequests: "풀 리퀘스트", + pullRequests_mr: "머지 리퀘스트", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "새 브랜치", + checkout: "체크아웃", + branchOffHint: "여기서 새 브랜치를 만듭니다", + checkoutHint: "바로 작업합니다", + base: "기준", + from: "기준", + branch: "브랜치", + pullRequest: "풀 리퀘스트", + pullRequest_mr: "머지 리퀘스트", + inProjectDirectory: "프로젝트 디렉터리에 있음", + inWorktree: "워크트리에 있음", title: "시작 위치", }, + worktreePicker: { + title: "워크트리", + searchPlaceholder: "워크트리 검색", + empty: "일치하는 워크트리가 없습니다.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index dbb2ce47f3..c07d1479b0 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -1425,8 +1425,9 @@ export const ptBR: TranslationResources = { title: "Novo workspace", create: "Criar", isolation: { - local: "Local", + local: "Diretório do projeto", worktree: "Novo worktree", + existing: "Worktree existente", label: "Isolamento", }, fields: { @@ -1441,12 +1442,17 @@ export const ptBR: TranslationResources = { createWorktreeFailed: "Falha ao criar worktree", composerStateRequired: "O estado do composer é obrigatório", selectModel: "Selecione um modelo", + branchInProjectDirectory: + "{{branch}} está em uso no diretório do projeto. Escolha Diretório do projeto para trabalhar nela, ou crie uma branch a partir dela.", + branchInWorktree: + "{{branch}} está em uso em {{path}}. Escolha esse worktree em Worktree existente, ou crie uma branch a partir dela.", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "Escolha de onde começar", + worktree: "Escolha o worktree em que trabalhar", launch: "Choose what to launch", }, refPicker: { @@ -1454,9 +1460,32 @@ export const ptBR: TranslationResources = { intoBase: "em {{baseRef}}", searching: "Buscando...", noMatchingRefs: "Nenhuma ref correspondente.", - searchPlaceholder: "Buscar branches e PRs", + searchBranches: "Buscar branches", + searchPullRequests: "Buscar pull requests", + searchPullRequests_mr: "Buscar merge requests", + branches: "Branches", + pullRequests: "Pull requests", + pullRequests_mr: "Merge requests", + pullRequestsShort: "PRs", + pullRequestsShort_mr: "MRs", + branchOff: "Nova branch", + checkout: "Usar diretamente", + branchOffHint: "Cria uma branch nova a partir dela", + checkoutHint: "Trabalha diretamente nela", + base: "Base", + from: "de", + branch: "Branch", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "No diretório do projeto", + inWorktree: "Em um worktree", title: "Começar de", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "Buscar worktrees", + empty: "Nenhum worktree correspondente.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 548d55f2bc..263e4e4f29 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -1418,8 +1418,9 @@ export const ru: TranslationResources = { title: "Новое рабочее пространство", create: "Создать", isolation: { - local: "Локально", + local: "Папка проекта", worktree: "Новый worktree", + existing: "Существующий worktree", label: "Изоляция", }, fields: { @@ -1434,12 +1435,17 @@ export const ru: TranslationResources = { createWorktreeFailed: "Не удалось создать worktree.", composerStateRequired: "Редактор сообщения ещё не готов.", selectModel: "Выберите модель", + branchInProjectDirectory: + "Ветка {{branch}} уже открыта в папке проекта. Выберите «Папка проекта», чтобы работать в ней, или создайте от неё новую ветку.", + branchInWorktree: + "Ветка {{branch}} уже открыта в {{path}}. Выберите этот worktree в «Существующий worktree» или создайте от неё новую ветку.", }, tooltips: { project: "Выберите проект", host: "Выберите хост", isolation: "Выберите уровень изоляции", startingRef: "Выберите, с чего начать", + worktree: "Выберите worktree для работы", launch: "Выберите, что запустить", }, refPicker: { @@ -1447,9 +1453,32 @@ export const ru: TranslationResources = { intoBase: "в ветку {{baseRef}}", searching: "Идет поиск...", noMatchingRefs: "Нет подходящих веток или PR.", - searchPlaceholder: "Поиск веток и PR", + searchBranches: "Поиск веток", + searchPullRequests: "Поиск PR", + searchPullRequests_mr: "Поиск MR", + branches: "Ветки", + pullRequests: "Pull requests", + pullRequests_mr: "Merge requests", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "Новая ветка", + checkout: "Переключиться", + branchOffHint: "Создать от неё новую ветку", + checkoutHint: "Работать прямо в ней", + base: "База", + from: "от", + branch: "Ветка", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "В папке проекта", + inWorktree: "В worktree", title: "Начать с", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "Поиск worktree", + empty: "Нет подходящих worktree.", + }, launch: { title: "Что запустить", chat: "Чат", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 8ce7eb5e36..2440c00f0c 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1388,8 +1388,9 @@ export const zhCN: TranslationResources = { title: "新建 workspace", create: "创建", isolation: { - local: "本地", + local: "项目目录", worktree: "新建 worktree", + existing: "已有 worktree", label: "隔离", }, fields: { @@ -1404,12 +1405,17 @@ export const zhCN: TranslationResources = { createWorktreeFailed: "创建 worktree 失败", composerStateRequired: "Composer 状态必填", selectModel: "请选择模型", + branchInProjectDirectory: + "{{branch}} 已在项目目录中检出。选择“项目目录”以在其中工作,或从它创建新分支。", + branchInWorktree: + "{{branch}} 已在 {{path}} 中检出。在“已有 worktree”中选择该 worktree,或从它创建新分支。", }, tooltips: { project: "Choose the project", host: "Choose the host", isolation: "Choose the isolation level", startingRef: "选择起始位置", + worktree: "选择要工作的 worktree", launch: "Choose what to launch", }, refPicker: { @@ -1417,9 +1423,32 @@ export const zhCN: TranslationResources = { intoBase: "进入 {{baseRef}}", searching: "正在搜索...", noMatchingRefs: "没有匹配的 refs。", - searchPlaceholder: "搜索分支和 PR", + searchBranches: "搜索分支", + searchPullRequests: "搜索 PR", + searchPullRequests_mr: "搜索 MR", + branches: "分支", + pullRequests: "Pull request", + pullRequests_mr: "Merge request", + pullRequestsShort: "PR", + pullRequestsShort_mr: "MR", + branchOff: "新建分支", + checkout: "检出", + branchOffHint: "从它创建一个新分支", + checkoutHint: "直接在它上面工作", + base: "基准", + from: "从", + branch: "分支", + pullRequest: "Pull request", + pullRequest_mr: "Merge request", + inProjectDirectory: "在项目目录中", + inWorktree: "在 worktree 中", title: "起始位置", }, + worktreePicker: { + title: "Worktree", + searchPlaceholder: "搜索 worktree", + empty: "没有匹配的 worktree。", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/plugins/new-workspace-items/model.test.ts b/packages/app/src/plugins/new-workspace-items/model.test.ts index 1a90194126..c22ed1e270 100644 --- a/packages/app/src/plugins/new-workspace-items/model.test.ts +++ b/packages/app/src/plugins/new-workspace-items/model.test.ts @@ -44,6 +44,8 @@ describe("the base ref a plugin reads", () => { project: { id: "p", name: "repo" }, canCreateWorktree: true, supportsMetadata: true, + supportsRefActions: true, + worktrees: [], }, { persistIsolation: () => {}, syncBaseAttachment: (item) => chosen.push(item) }, ); @@ -72,6 +74,8 @@ describe("the metadata a plugin sets", () => { project: { id: "p", name: "repo" }, canCreateWorktree: true, supportsMetadata: true, + supportsRefActions: true, + worktrees: [], }, { persistIsolation: () => {}, syncBaseAttachment: () => {} }, ); diff --git a/packages/app/src/screens/new-workspace-picker-item.test.ts b/packages/app/src/screens/new-workspace-picker-item.test.ts index fd1e97dd11..6ef493cece 100644 --- a/packages/app/src/screens/new-workspace-picker-item.test.ts +++ b/packages/app/src/screens/new-workspace-picker-item.test.ts @@ -8,6 +8,7 @@ import { buildPickerOptionData, defaultBasePickerItem, pickerItemToCheckoutRequest, + refListOptions, startsNewBranch, type PickerItem, } from "./new-workspace-picker-item"; @@ -106,6 +107,72 @@ describe("pickerItemToCheckoutRequest", () => { }); }); +describe("pickerItemToCheckoutRequest with an action", () => { + it("checks a branch out by its branch name, whichever ref the row stands for", () => { + const item: PickerItem = { + kind: "branch", + name: "dev", + refName: "refs/remotes/origin/dev", + accessibilityLabel: "dev, origin branch", + }; + expect(pickerItemToCheckoutRequest(item, "checkout")).toEqual({ + action: "checkout", + refName: "dev", + }); + }); + + it("branches off a pull request, still naming the pull request", () => { + const item: PickerItem = { kind: "github-pr", item: prItem }; + expect(pickerItemToCheckoutRequest(item, "branch-off")).toEqual({ + action: "branch-off", + refName: "feature/picker", + checkoutSource: { kind: "change_request", forge: "github", number: 42 }, + githubPrNumber: 42, + }); + }); +}); + +describe("refListOptions", () => { + const branchDetails: BranchPickerDetail[] = [ + { + name: "main", + committerDate: 20, + hasLocal: true, + hasRemote: true, + localAhead: 1, + localBehind: 0, + }, + { name: "dev", committerDate: 10, hasLocal: true, hasRemote: false }, + ]; + const data = buildPickerOptionData({ branchDetails, prItems: [prItem], baseItem: null }); + + it("lists branches and pull requests apart", () => { + const list = (kind: PickerItem["kind"]) => + refListOptions({ ...data, kind, action: "branch-off" }).map((option) => option.label); + expect(list("branch")).toEqual(["main", "main (local)", "dev"]); + expect(list("github-pr")).toEqual(["#42 Add picker"]); + }); + + it("shows one row per branch when checking out, since both refs check out the same branch", () => { + const rows = refListOptions({ ...data, kind: "branch", action: "checkout" }); + expect(rows.map((option) => option.label)).toEqual(["main", "dev"]); + }); + + it("keeps the selected row of a branch when checking out", () => { + const localMain = branchPickerOptionId("refs/heads/main"); + const rows = refListOptions({ + ...data, + selectedOptionId: localMain, + kind: "branch", + action: "checkout", + }); + expect(rows.map((option) => [option.id, option.label])).toEqual([ + [localMain, "main"], + [branchPickerOptionId("refs/heads/dev"), "dev"], + ]); + }); +}); + describe("buildBranchPickerItems", () => { it("keeps a single origin row when local and origin match", () => { expect( @@ -403,4 +470,13 @@ describe("startsNewBranch", () => { ).toBe(false); expect(startsNewBranch({ githubPrNumber: 7 })).toBe(false); }); + + it("is true for a branch-off from a change request", () => { + expect( + startsNewBranch({ + action: "branch-off", + checkoutSource: { kind: "change_request", forge: "github", number: 7 }, + }), + ).toBe(true); + }); }); diff --git a/packages/app/src/screens/new-workspace-picker-item.ts b/packages/app/src/screens/new-workspace-picker-item.ts index 897f99a561..a8f6ae4d4b 100644 --- a/packages/app/src/screens/new-workspace-picker-item.ts +++ b/packages/app/src/screens/new-workspace-picker-item.ts @@ -31,6 +31,15 @@ export type PickerCheckoutRequest = Pick< "action" | "refName" | "checkoutSource" | "githubPrNumber" >; +/** What a new worktree does with the picked ref: start a new branch from it, or work on it. */ +export type RefAction = "branch-off" | "checkout"; + +/** A branch is a base to branch off by default; a pull request is checked out. */ +export const DEFAULT_REF_ACTION: Record = { + branch: "branch-off", + "github-pr": "checkout", +}; + const BRANCH_OPTION_PREFIX = "branch:"; const PR_OPTION_PREFIX = "github-pr:"; const REMOTE_TRACKING_PREFIX = "refs/remotes/"; @@ -180,16 +189,20 @@ export function defaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem export function pickerItemToCheckoutRequest( item: PickerItem | null, + action: RefAction = item ? DEFAULT_REF_ACTION[item.kind] : "branch-off", ): PickerCheckoutRequest | undefined { if (!item) return undefined; switch (item.kind) { case "branch": - return { action: "branch-off", refName: item.refName }; + // A checkout works on the local branch; both the origin row and the local row stand for it. + return action === "checkout" + ? { action, refName: branchNameFromRef(item.refName) } + : { action, refName: item.refName }; case "github-pr": { const headRefName = item.item.headRefName?.trim(); const forge = item.item.forge ?? "github"; return { - action: "checkout", + action, ...(headRefName ? { refName: headRefName } : {}), checkoutSource: { kind: "change_request", @@ -211,16 +224,42 @@ export function pickerItemToCheckoutRequest( } /** - * Whether creating a worktree from this request cuts a new branch, which is what the daemon does - * for anything but a checkout. No request at all (a detached HEAD gives the screen no default - * base) cuts one from the repository's default branch. + * Whether creating a worktree from this request cuts a new branch. No request at all (a detached + * HEAD gives the screen no default base) cuts one from the repository's default branch. A request + * with no action is read as the daemon reads it: a change request is checked out. */ export function startsNewBranch(request: PickerCheckoutRequest | undefined): boolean { if (!request) return true; - if (request.action === "checkout") return false; + if (request.action) return request.action === "branch-off"; return !request.checkoutSource && request.githubPrNumber === undefined; } +/** + * The rows of one ref list. Checking out works on the local branch, so the origin and local rows + * of a branch are one choice there: one row per branch, named by the branch, keeping the selected + * row's id so its checkmark stays. + */ +export function refListOptions(input: { + options: readonly ComboboxOptionModel[]; + itemById: ReadonlyMap; + selectedOptionId: string; + kind: PickerItem["kind"]; + action: RefAction; +}): ComboboxOptionModel[] { + const { options, itemById, selectedOptionId, kind, action } = input; + const ofKind = options.filter((option) => itemById.get(option.id)?.kind === kind); + if (kind !== "branch" || action !== "checkout") return ofKind; + const rowByBranch = new Map(); + for (const option of ofKind) { + const item = itemById.get(option.id); + if (item?.kind !== "branch") continue; + const branchName = branchNameFromRef(item.refName); + if (rowByBranch.has(branchName) && option.id !== selectedOptionId) continue; + rowByBranch.set(branchName, { ...option, label: branchName }); + } + return [...rowByBranch.values()]; +} + export function prPickerOptionId(number: number): string { return `${PR_OPTION_PREFIX}${number}`; } diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index 96d076224d..6e2e34c54c 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -7,6 +7,7 @@ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useSta import type { ReactNode } from "react"; import { useIsFocused } from "expo-router/react-navigation"; import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { createNameId } from "mnemonic-id"; @@ -25,6 +26,8 @@ import { useIsCompactFormFactor } from "@/constants/layout"; import { useToast } from "@/contexts/toast-context"; import { useAgentInputDraft } from "@/composer/draft/input-draft"; import { useForgeSearchQuery } from "@/git/use-forge-search-query"; +import { getForgePresentation } from "@/git/forge"; +import { useCheckoutPrStatusQuery } from "@/git/use-pr-status-query"; import { useCheckoutStatusQuery } from "@/git/use-status-query"; import { ensureCheckoutStatus } from "@/git/checkout-status-cache"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; @@ -87,7 +90,6 @@ import { buildPickerOptionData, defaultBasePickerItem, pickerItemLabel, - pickerItemToCheckoutRequest, startsNewBranch, type BranchPickerDetail, type PickerCheckoutRequest, @@ -103,16 +105,26 @@ import { type NewWorkspaceItemsScreen, } from "@/plugins/new-workspace-items"; import { + BranchInWorktreeError, createNewWorkspaceSetup, + refActionOf, useNewWorkspaceSetupState, type NewWorkspaceSetup, + type SetupInputs, } from "./new-workspace/setup-model"; +import type { IsolationChoice } from "./new-workspace/form"; +import { shortenPath } from "@/utils/shorten-path"; import { resolveNewWorkspaceAutomaticServerId, resolveNewWorkspaceInitialServerId, } from "./new-workspace-initial-context"; import { buildNewWorkspaceProjectIconTargets } from "./new-workspace/project-icon-targets"; import { useNewWorkspaceProjectPicker } from "./new-workspace/project-picker"; +import { + useExistingWorktrees, + useProjectWorktrees, + type ExistingWorktree, +} from "./new-workspace/existing-worktrees"; import { useNewWorkspaceForm } from "./new-workspace/form"; import { ImportSessionButton } from "./new-workspace/import-session-button"; import { useImportSession } from "@/hooks/use-import-session"; @@ -196,7 +208,14 @@ const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [ interface WorkspaceIsolationState { isolation: "local" | "worktree"; setIsolation: (value: "local" | "worktree") => void; + /** What the workspace is created as. An existing worktree is a local workspace at its path. */ effectiveIsolation: "local" | "worktree"; + /** The Isolation field's choice. */ + choice: IsolationChoice; + /** The worktree an Existing worktree workspace is created in. */ + existingWorktreePath: string | null; + /** Where the workspace works: the existing worktree, else the project directory. */ + workingDirectory: string | null; canCreateWorktree: boolean; showRefPicker: boolean; } @@ -207,25 +226,58 @@ function useWorkspaceIsolation(input: { setup: NewWorkspaceSetup; supportsMultiplicity: boolean; canCreateWorktree: boolean; + existingWorktrees: readonly ExistingWorktree[]; + projectDirectory: string | null; }): WorkspaceIsolationState { - const { setup, supportsMultiplicity, canCreateWorktree } = input; + const { setup, supportsMultiplicity, canCreateWorktree, existingWorktrees } = input; // The last isolation choice is remembered alongside the other New Workspace // form preferences (provider, model, mode). A manual in-screen pick overrides // the remembered default until the screen remounts. const { preferences } = useFormPreferences(); - const { manualIsolation } = useNewWorkspaceSetupState(setup); + const { manualIsolation, existingWorktreePath: chosenPath } = useNewWorkspaceSetupState(setup); const isolation = manualIsolation ?? preferences.isolation ?? "local"; - const isWorktree = isolation === "worktree" && canCreateWorktree; + // A worktree that left the list (removed since it was chosen) is no choice. + const existingWorktreePath = + canCreateWorktree && existingWorktrees.some((worktree) => worktree.path === chosenPath) + ? chosenPath + : null; + const isWorktree = isolation === "worktree" && canCreateWorktree && !existingWorktreePath; + const worktreeChoice = isWorktree ? "worktree" : "local"; return { isolation, setIsolation: setup.chooseIsolation, effectiveIsolation: isWorktree ? "worktree" : "local", + choice: existingWorktreePath ? "existing" : worktreeChoice, + existingWorktreePath, + workingDirectory: existingWorktreePath ?? input.projectDirectory, canCreateWorktree, showRefPicker: !supportsMultiplicity || isWorktree, }; } +/** Create's checkout request, with the model's refusal said in the user's language. */ +function checkoutRequestOrExplain( + resolve: () => PickerCheckoutRequest | undefined, + t: TFunction, +): PickerCheckoutRequest | undefined { + try { + return resolve(); + } catch (error) { + if (!(error instanceof BranchInWorktreeError)) throw error; + const branch = error.branchName; + throw new Error( + error.worktree.containsCwd + ? t("newWorkspace.errors.branchInProjectDirectory", { branch }) + : t("newWorkspace.errors.branchInWorktree", { + branch, + path: shortenPath(error.worktree.path), + }), + { cause: error }, + ); + } +} + function normalizeBranchDetails( data: { branchDetails?: BranchPickerDetail[]; branches?: string[] } | undefined, ): BranchPickerDetail[] { @@ -1005,9 +1057,17 @@ export function NewWorkspaceScreen({ }), }); const composerState = chatDraft.composerState; + const supportsWorktreeList = useHostFeature(selectedServerId, "checkoutWorktreeList"); + const projectWorktrees = useProjectWorktrees({ + client, + serverId: selectedServerId, + cwd: selectedSourceDirectory, + enabled: supportsWorktreeList && isConnected, + }); const { setup, pluginProject, canCreateWorktree, isPending } = usePluginSetup({ serverId: selectedServerId, project: selectedProject, + worktrees: projectWorktrees, supportsMultiplicity: supportsWorkspaceMultiplicity, pendingAction, isDraftHandoffActive, @@ -1015,7 +1075,18 @@ export function NewWorkspaceScreen({ setAttachments: chatDraft.setAttachments, }); const dispatchPickerSelection = setup.dispatchPicker; - const selectedItem = useNewWorkspaceSetupState(setup).pickerSelection.selectedItem; + const setupState = useNewWorkspaceSetupState(setup); + const selectedItem = setupState.pickerSelection.selectedItem; + const supportsRefActions = useHostFeature(selectedServerId, "worktreeRefActions"); + const { refActions } = setupState; + const refActionFor = useMemo( + () => ({ + branch: refActionOf({ refActions, supportsRefActions, kind: "branch" }), + "github-pr": refActionOf({ refActions, supportsRefActions, kind: "github-pr" }), + }), + [refActions, supportsRefActions], + ); + const existingWorktrees = useExistingWorktrees(projectWorktrees); const handleForgeChangeRequestDetected = useCallback(() => { dispatchPickerSelection({ type: "pr-detected" }); @@ -1048,10 +1119,19 @@ export function NewWorkspaceScreen({ cwd: selectedSourceDirectory ?? "", }); - const { effectiveIsolation, setIsolation, showRefPicker } = useWorkspaceIsolation({ + const { + effectiveIsolation, + setIsolation, + showRefPicker, + choice, + existingWorktreePath, + workingDirectory, + } = useWorkspaceIsolation({ setup, supportsMultiplicity: supportsWorkspaceMultiplicity, canCreateWorktree, + existingWorktrees, + projectDirectory: selectedSourceDirectory, }); const branchSuggestionsQuery = useQuery({ @@ -1076,6 +1156,13 @@ export function NewWorkspaceScreen({ staleTime: 15_000, }); + const changeRequestContext = useChangeRequestContext({ + serverId: selectedServerId, + cwd: selectedSourceDirectory, + pickerOpen: pickerQueryEnabled, + selectedItem, + }); + const githubPrSearchQuery = useForgeSearchQuery({ client, serverId: selectedServerId, @@ -1116,7 +1203,7 @@ export function NewWorkspaceScreen({ }, [itemById, selectedOptionId]); const selectPickerItem = useCallback( (item: PickerItem) => { - setup.chooseBase(item); + setup.chooseRef(item); setPickerOpen(false); }, [setup], @@ -1238,7 +1325,7 @@ export function NewWorkspaceScreen({ if (!selectedProject) { throw new Error("Choose a project"); } - if (!selectedSourceDirectory) { + if (!selectedSourceDirectory || !workingDirectory) { throw new Error("Choose a host for this project"); } const connectedClient = withConnectedClient(); @@ -1252,8 +1339,12 @@ export function NewWorkspaceScreen({ }) : null; const checkoutRequest = checkoutStatusForCreate - ? pickerItemToCheckoutRequest( - selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate), + ? checkoutRequestOrExplain( + () => + setup.checkoutRequestFor( + selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate), + ), + t, ) : undefined; const normalizedWorkspace = await createMultiplicityWorkspace({ @@ -1262,7 +1353,7 @@ export function NewWorkspaceScreen({ client: connectedClient, isolation: createsWorktree ? "worktree" : "local", project: selectedProject, - sourceDirectory: selectedSourceDirectory, + sourceDirectory: workingDirectory, checkoutRequest, branchName: setup.getSnapshot().branch, metadata: setup.getSnapshot().metadata, @@ -1292,6 +1383,7 @@ export function NewWorkspaceScreen({ supportsWorkspaceMultiplicity, t, withConnectedClient, + workingDirectory, ], ); @@ -1381,7 +1473,7 @@ export function NewWorkspaceScreen({ setPendingAction("terminal"); let outcome: SubmitOutcome = "background"; await runCreateTerminalWorkspace({ - cwd: selectedSourceDirectory ?? "", + cwd: workingDirectory ?? "", prompt: terminalPromptText, profile: selectedTerminalProfile, profileName: selectedTerminalProfile?.name, @@ -1440,7 +1532,6 @@ export function NewWorkspaceScreen({ launchTarget, queryClient, selectedServerId, - selectedSourceDirectory, selectedTerminalProfile, t, terminalPromptText, @@ -1448,6 +1539,7 @@ export function NewWorkspaceScreen({ leaveFullscreen, updateFormPreferences, withConnectedClient, + workingDirectory, ]); const agentControlsWithDisabled = useMemo( @@ -1503,9 +1595,12 @@ export function NewWorkspaceScreen({ open: openIsolationPicker, openState: isolationPickerOpen, onOpenChange: handleIsolationPickerOpenChange, - effectiveIsolation, + choice, canCreateWorktree, onSelect: setIsolation, + existingWorktrees, + existingWorktreePath, + onChooseExistingWorktree: setup.chooseExistingWorktree, }, base: { anchorRef: pickerAnchorRef, @@ -1522,6 +1617,11 @@ export function NewWorkspaceScreen({ setSearchQuery: setPickerSearchQuery, emptyText: pickerEmptyText, showRefPicker, + worktrees: projectWorktrees, + actionFor: refActionFor, + onActionChange: setup.chooseRefAction, + canChooseAction: supportsRefActions, + changeRequestContext, }, launch: { serverId: selectedServerId, @@ -1558,7 +1658,7 @@ export function NewWorkspaceScreen({ textReplacement={terminalTextReplacement} attachments={NO_TERMINAL_ATTACHMENTS} onChangeAttachments={noopChangeAttachments} - cwd={selectedSourceDirectory ?? ""} + cwd={workingDirectory ?? ""} clearDraft={noopClearDraft} autoFocus={terminalTakesPrompt} autoFocusKey={launchFocusKey} @@ -1587,7 +1687,7 @@ export function NewWorkspaceScreen({ onChangeAttachments={chatDraft.setAttachments} onForgeChangeRequestDetected={handleForgeChangeRequestDetected} onForgeChangeRequestAutoAttach={handleForgeChangeRequestAutoAttach} - cwd={selectedSourceDirectory ?? ""} + cwd={workingDirectory ?? ""} clearDraft={handleClearDraft} autoFocus autoFocusKey={launchFocusKey} @@ -1619,6 +1719,7 @@ export function NewWorkspaceScreen({ function usePluginSetup(input: { serverId: string; project: Parameters[0] | null; + worktrees: SetupInputs["worktrees"]; supportsMultiplicity: boolean; pendingAction: Parameters[0]["pendingAction"]; isDraftHandoffActive: boolean; @@ -1628,6 +1729,7 @@ function usePluginSetup(input: { const { serverId, project, + worktrees, supportsMultiplicity, pendingAction, isDraftHandoffActive, @@ -1646,7 +1748,16 @@ function usePluginSetup(input: { () => (projectId && projectName ? { id: projectId, name: projectName } : null), [projectId, projectName], ); - const inputs = { serverId, locked, project: pluginProject, canCreateWorktree, supportsMetadata }; + const supportsRefActions = useHostFeature(serverId, "worktreeRefActions"); + const inputs: SetupInputs = { + serverId, + locked, + project: pluginProject, + canCreateWorktree, + supportsMetadata, + supportsRefActions, + worktrees, + }; // Both are stable for the life of the screen: preferences write through the query client, and // the draft is keyed per mount. A command and a pick run the same effects. const [setup] = useState(() => @@ -1762,3 +1873,21 @@ const styles = StyleSheet.create((theme) => ({ lineHeight: 20, }, })); + +/** + * The project's forge names its change requests: pull requests, or merge requests on GitLab. + * The forge is looked up once the ref picker opens or a change request is chosen. + */ +function useChangeRequestContext(input: { + serverId: string; + cwd: string | null; + pickerOpen: boolean; + selectedItem: PickerItem | null; +}): "mr" | undefined { + const { forge } = useCheckoutPrStatusQuery({ + serverId: input.serverId, + cwd: input.cwd ?? "", + enabled: input.pickerOpen || input.selectedItem?.kind === "github-pr", + }); + return getForgePresentation(forge).changeRequestContext; +} diff --git a/packages/app/src/screens/new-workspace/existing-worktrees.ts b/packages/app/src/screens/new-workspace/existing-worktrees.ts new file mode 100644 index 0000000000..454b561cba --- /dev/null +++ b/packages/app/src/screens/new-workspace/existing-worktrees.ts @@ -0,0 +1,66 @@ +import { useMemo } from "react"; +import type { CheckoutWorktree } from "@getpaseo/protocol/messages"; +import { useFetchQuery } from "@/data/query"; + +/** An existing worktree, as the Worktree picker lists it. */ +export interface ExistingWorktree { + path: string; + /** The branch it has checked out, or its directory name when HEAD is detached. */ + name: string; + createdAt: Date | null; +} + +interface WorktreeListClient { + listCheckoutWorktrees(cwd: string): Promise; +} + +const NO_WORKTREES: readonly CheckoutWorktree[] = []; + +/** Every git worktree of the project at `cwd`, whoever created it. Empty until it loads. */ +export function useProjectWorktrees(input: { + client: WorktreeListClient | null; + serverId: string; + cwd: string | null; + enabled: boolean; +}): readonly CheckoutWorktree[] { + const { client, serverId, cwd, enabled } = input; + const query = useFetchQuery({ + dataShape: "list", + queryKey: ["checkout-worktrees", serverId, cwd], + queryFn: async () => { + if (!client || !cwd) throw new Error("Choose a project"); + return client.listCheckoutWorktrees(cwd); + }, + enabled: enabled && client !== null && cwd !== null, + staleTimeMs: 15_000, + }); + return query.data ?? NO_WORKTREES; +} + +function directoryNameOf(path: string): string { + return path.split(/[\\/]/).findLast((segment) => segment.length > 0) ?? path; +} + +/** + * The worktrees the Worktree picker offers, newest first. The project directory is left out: it + * is the Project directory choice. + */ +export function useExistingWorktrees( + worktrees: readonly CheckoutWorktree[], +): readonly ExistingWorktree[] { + return useMemo( + () => + worktrees + .filter((worktree) => !worktree.containsCwd) + .map((worktree) => { + const createdAtMs = Date.parse(worktree.createdAt); + return { + path: worktree.path, + name: worktree.branchName ?? directoryNameOf(worktree.path), + createdAt: Number.isNaN(createdAtMs) ? null : new Date(createdAtMs), + }; + }) + .sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0)), + [worktrees], + ); +} diff --git a/packages/app/src/screens/new-workspace/form/field-trigger.tsx b/packages/app/src/screens/new-workspace/form/field-trigger.tsx index e4ed92d8ea..8b1fab9a1c 100644 --- a/packages/app/src/screens/new-workspace/form/field-trigger.tsx +++ b/packages/app/src/screens/new-workspace/form/field-trigger.tsx @@ -36,6 +36,8 @@ export interface FieldTriggerContentProps { label: string; icon: ReactNode; value: string; + /** A word before the value that a badge needs because it shows no label, such as "from". */ + qualifier?: string; /** Secondary text after the value, such as a terminal profile's name. */ detail?: string; } @@ -45,12 +47,14 @@ export function FieldTriggerContent({ label, icon, value, + qualifier, detail, }: FieldTriggerContentProps): ReactElement { const valueLine = ( <> {icon} + {qualifier && variant === "badge" ? {qualifier} : null} {value} {detail ? {detail} : null} diff --git a/packages/app/src/screens/new-workspace/form/icons.tsx b/packages/app/src/screens/new-workspace/form/icons.tsx index 9fa277542d..fa039e9995 100644 --- a/packages/app/src/screens/new-workspace/form/icons.tsx +++ b/packages/app/src/screens/new-workspace/form/icons.tsx @@ -1,17 +1,19 @@ import type { ReactElement } from "react"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { Folder, FolderPlus, GitBranch, GitPullRequest } from "lucide-react-native"; +import { Folder, FolderGit2, FolderPlus, GitBranch, GitPullRequest } from "lucide-react-native"; import { ProjectIconView } from "@/components/project-icon-view"; import { ICON_SIZE, type Theme } from "@/styles/theme"; import { projectIconPlaceholderLabelFromDisplayName } from "@/utils/project-display-name"; const ThemedFolder = withUnistyles(Folder); const ThemedFolderPlus = withUnistyles(FolderPlus); +const ThemedFolderGit = withUnistyles(FolderGit2); const ThemedGitBranch = withUnistyles(GitBranch); const ThemedGitPullRequest = withUnistyles(GitPullRequest); const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); export const folderIcon = ; +export const existingWorktreeIcon = ; export const addProjectIcon = ; export const branchIcon = ; export const pullRequestIcon = ; diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index da9368a6a7..2bb097b2a3 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -1,26 +1,58 @@ -import { useCallback, useMemo, type ReactElement, type ReactNode, type RefObject } from "react"; +import { + useCallback, + useMemo, + useRef, + useState, + type ReactElement, + type ReactNode, + type RefObject, +} from "react"; import { View } from "react-native"; import { useTranslation } from "react-i18next"; import { StyleSheet } from "react-native-unistyles"; -import type { TerminalProfile } from "@getpaseo/protocol/messages"; +import type { CheckoutWorktree, TerminalProfile } from "@getpaseo/protocol/messages"; import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox"; import { HostStatusDot } from "@/components/host-status-dot"; import { HostPicker } from "@/components/hosts/host-picker"; import type { LaunchTarget } from "@/new-workspace-launch/target"; import type { HostProjectListItem } from "@/projects/host-projects"; import type { HostProfile } from "@/types/host-connection"; -import type { PickerItem } from "../../new-workspace-picker-item"; +import { shortenPath } from "@/utils/shorten-path"; +import { + branchNameFromRef, + refListOptions, + type PickerItem, + type RefAction, +} from "../../new-workspace-picker-item"; +import type { ExistingWorktree } from "../existing-worktrees"; +import { worktreeHoldingBranch } from "../setup-model"; import { FIELD_BADGE_HEIGHT, FIELD_HEIGHT, FieldTrigger, type FieldTriggerVariant, } from "./field-trigger"; -import { branchIcon, folderIcon, ProjectIcon, pullRequestIcon } from "./icons"; +import { + branchIcon, + existingWorktreeIcon, + folderIcon, + ProjectIcon, + pullRequestIcon, +} from "./icons"; import { LaunchControl } from "./launch-control"; -import { AddProjectOption, IsolationOption, ProjectOption, RefOption } from "./options"; +import { + AddProjectOption, + IsolationOption, + ProjectOption, + RefOption, + WorktreeOption, + type BranchHolder, +} from "./options"; +import { RefPickerToolbar, type RefList } from "./ref-picker-toolbar"; type Isolation = "local" | "worktree"; +/** The Isolation field's choice. Existing worktree creates a local workspace at the worktree. */ +export type IsolationChoice = Isolation | "existing"; type RenderOption = NonNullable; interface PickerControl { @@ -55,9 +87,13 @@ export interface NewWorkspaceFormProps { onAddHost: () => void; }; isolation: PickerControl & { - effectiveIsolation: Isolation; + choice: IsolationChoice; canCreateWorktree: boolean; onSelect: (isolation: Isolation) => void; + /** The project's worktrees other than its own directory, newest first. */ + existingWorktrees: readonly ExistingWorktree[]; + existingWorktreePath: string | null; + onChooseExistingWorktree: (path: string) => void; }; base: PickerControl & { selectedSourceDirectory: string | null; @@ -70,6 +106,14 @@ export interface NewWorkspaceFormProps { setSearchQuery: (query: string) => void; emptyText: string; showRefPicker: boolean; + /** Every git worktree of the project, to say where a branch is already checked out. */ + worktrees: readonly CheckoutWorktree[]; + actionFor: Record; + onActionChange: (list: RefList, action: RefAction) => void; + /** Whether the host lets the user pick the action; otherwise each list keeps its default. */ + canChooseAction: boolean; + /** Selects the forge's change-request words, such as "Merge requests" on GitLab. */ + changeRequestContext: "mr" | undefined; }; launch: { serverId: string; @@ -125,38 +169,200 @@ function useProjectPicker( return { renderOption, footer }; } -function useIsolationPicker( - isolation: NewWorkspaceFormProps["isolation"], - isPending: boolean, -): { options: ComboboxOption[]; onSelect: (id: string) => void; renderOption: RenderOption } { +function useIsolationPicker(input: { + isolation: NewWorkspaceFormProps["isolation"]; + projectDirectory: string | null; + isPending: boolean; +}): { + /** The trigger's value and icon for the choice. */ + value: string; + icon: ReactElement; + options: ComboboxOption[]; + onSelect: (id: string) => void; + renderOption: RenderOption; +} { const { t } = useTranslation(); - const { canCreateWorktree, onSelect, onOpenChange } = isolation; - // "New worktree" is omitted entirely (not disabled) when the project isn't a - // git checkout, since worktree isolation is impossible there. + const { isolation, projectDirectory, isPending } = input; + const { canCreateWorktree, choice, existingWorktrees, onSelect, onOpenChange } = isolation; + const { existingWorktreePath, onChooseExistingWorktree } = isolation; + const newestWorktree = existingWorktrees[0]; + // The worktree options are omitted entirely (not disabled) when they cannot apply: a project + // that is not a git checkout has no worktrees, and one with none has nothing to reuse. const options = useMemo(() => { - const local = { id: "local", label: t("newWorkspace.isolation.local") }; + const local = { + id: "local", + label: t("newWorkspace.isolation.local"), + description: projectDirectory ? shortenPath(projectDirectory) : undefined, + }; if (!canCreateWorktree) return [local]; - return [local, { id: "worktree", label: t("newWorkspace.isolation.worktree") }]; - }, [canCreateWorktree, t]); + const worktree = { id: "worktree", label: t("newWorkspace.isolation.worktree") }; + if (!newestWorktree) return [local, worktree]; + return [local, worktree, { id: "existing", label: t("newWorkspace.isolation.existing") }]; + }, [canCreateWorktree, newestWorktree, projectDirectory, t]); const handleSelect = useCallback( (id: string) => { - onSelect(id === "worktree" ? "worktree" : "local"); + // The newest worktree is the likeliest one to return to, so it is the first pick. + if (id === "existing" && newestWorktree) { + onChooseExistingWorktree(existingWorktreePath ?? newestWorktree.path); + } else if (id === "local" || id === "worktree") { + onSelect(id); + } onOpenChange(false); }, - [onOpenChange, onSelect], + [existingWorktreePath, newestWorktree, onChooseExistingWorktree, onOpenChange, onSelect], ); const renderOption = useCallback( (row) => , [isPending], ); - return { options, onSelect: handleSelect, renderOption }; + const value = { + local: t("newWorkspace.isolation.local"), + worktree: t("newWorkspace.isolation.worktree"), + existing: t("newWorkspace.isolation.existing"), + }[choice]; + const icon = { local: folderIcon, worktree: branchIcon, existing: existingWorktreeIcon }[choice]; + return { value, icon, options, onSelect: handleSelect, renderOption }; } -function useRefRenderOption(itemById: Map, isPending: boolean): RenderOption { - return useCallback( - (row) => , - [isPending, itemById], +/** Picks which existing worktree the workspace works in. */ +function useWorktreePicker(isolation: NewWorkspaceFormProps["isolation"], isPending: boolean) { + const { existingWorktrees, existingWorktreePath, onChooseExistingWorktree } = isolation; + const anchorRef = useRef(null); + const [openState, setOpenState] = useState(false); + const selected = existingWorktrees.find((worktree) => worktree.path === existingWorktreePath); + const options = useMemo( + () => existingWorktrees.map((worktree) => ({ id: worktree.path, label: worktree.name })), + [existingWorktrees], ); + const open = useCallback(() => setOpenState(true), []); + const onSelect = useCallback( + (path: string) => { + onChooseExistingWorktree(path); + setOpenState(false); + }, + [onChooseExistingWorktree], + ); + const renderOption = useCallback( + (row) => ( + worktree.path === row.option.id)} + disabled={isPending} + /> + ), + [existingWorktrees, isPending], + ); + return { + anchorRef, + openState, + onOpenChange: setOpenState, + open, + selected, + options, + onSelect, + renderOption, + }; +} + +function refListOf(item: PickerItem | null | undefined): RefList { + return item?.kind ?? "branch"; +} + +/** Where a checkout of `item` would work, when a worktree already has the branch. */ +function branchHolderOf( + item: PickerItem | undefined, + action: RefAction, + worktrees: readonly CheckoutWorktree[], +): BranchHolder { + if (item?.kind !== "branch" || action !== "checkout") return null; + const holder = worktreeHoldingBranch(worktrees, branchNameFromRef(item.refName)); + if (!holder) return null; + return holder.containsCwd ? "project-directory" : "worktree"; +} + +/** + * The ref picker's two lists, the action control, and what the trigger says. Branching off reads + * "from " on a badge, which has no label of its own; working on the pick names what it is. + */ +function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { + const { t } = useTranslation(); + const { options: allOptions, itemById, selectedItem, selectedOptionId, worktrees } = base; + const { open: openPicker, onSelect, actionFor, onActionChange } = base; + const context = base.changeRequestContext; + const [list, setList] = useState("branch"); + const action = actionFor[list]; + const options = useMemo( + () => refListOptions({ options: allOptions, itemById, selectedOptionId, kind: list, action }), + [action, allOptions, itemById, list, selectedOptionId], + ); + // Opens on the list the current pick is in. + const open = useCallback(() => { + setList(refListOf(selectedItem)); + openPicker(); + }, [openPicker, selectedItem]); + const handleActionChange = useCallback( + (next: RefAction) => onActionChange(list, next), + [list, onActionChange], + ); + const renderOption = useCallback( + (row) => { + const item = itemById.get(row.option.id); + return ( + + ); + }, + [action, isPending, itemById, worktrees], + ); + const toolbar = useMemo( + () => ( + + ), + [action, base.canChooseAction, context, handleActionChange, list], + ); + const shown = itemById.get(selectedOptionId); + const shownList = refListOf(shown); + const shownAction = actionFor[shownList]; + const icon = shownList === "github-pr" ? pullRequestIcon : branchIcon; + const checksOutBranch = shown?.kind === "branch" && shownAction === "checkout"; + const trigger = + shownAction === "branch-off" + ? { label: t("newWorkspace.refPicker.base"), qualifier: t("newWorkspace.refPicker.from") } + : { + label: + shownList === "github-pr" + ? t("newWorkspace.refPicker.pullRequest", { context }) + : t("newWorkspace.refPicker.branch"), + qualifier: undefined, + }; + return { + options, + open, + onSelect, + renderOption, + toolbar, + searchPlaceholder: + list === "github-pr" + ? t("newWorkspace.refPicker.searchPullRequests", { context }) + : t("newWorkspace.refPicker.searchBranches"), + trigger: { + ...trigger, + icon, + // A checkout works on the branch itself, so its origin and local rows read the same. + value: checksOutBranch ? branchNameFromRef(shown.refName) : base.triggerLabel, + }, + }; } /** @@ -170,8 +376,13 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props; const variant: FieldTriggerVariant = isCompact ? "field" : "badge"; const projectPicker = useProjectPicker(project, isPending); - const isolationPicker = useIsolationPicker(isolation, isPending); - const renderRefOption = useRefRenderOption(base.itemById, isPending); + const isolationPicker = useIsolationPicker({ + isolation, + projectDirectory: base.selectedSourceDirectory, + isPending, + }); + const worktreePicker = useWorktreePicker(isolation, isPending); + const refPicker = useRefPicker(base, isPending); const selectedHostLabel = host.allHosts.find((h) => h.serverId === host.selectedServerId)?.label ?? "Host"; @@ -196,11 +407,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement () => , [host.selectedServerId], ); - const isWorktree = isolation.effectiveIsolation === "worktree"; - const isolationValue = isWorktree - ? t("newWorkspace.isolation.worktree") - : t("newWorkspace.isolation.local"); - const refIcon = base.selectedItem?.kind === "github-pr" ? pullRequestIcon : branchIcon; + const { choice } = isolation; const projectField = ( ) : null; - const baseField = base.showRefPicker ? ( - - ) : null; + const worktreeField = + choice === "existing" && worktreePicker.selected ? ( + + ) : null; + const refField = + base.showRefPicker && !worktreeField ? ( + + ) : null; + // Which one shows follows the isolation; they share a slot. + const baseField = worktreeField ?? refField; const launchField = ( + ); diff --git a/packages/app/src/screens/new-workspace/form/options.tsx b/packages/app/src/screens/new-workspace/form/options.tsx index 88f5c5d4dd..d9d1b25edc 100644 --- a/packages/app/src/screens/new-workspace/form/options.tsx +++ b/packages/app/src/screens/new-workspace/form/options.tsx @@ -5,9 +5,21 @@ import { StyleSheet } from "react-native-unistyles"; import { ComboboxItem, type ComboboxOption } from "@/components/ui/combobox"; import { Shortcut } from "@/components/ui/shortcut"; import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; +import { getForgePresentation } from "@/git/forge"; +import { PullRequestStateIcon } from "@/git/pull-request-state-icon"; +import { useCompactTimeAgo } from "@/hooks/use-time-ago"; import { getHostProjectSourceDirectory, type HostProjectListItem } from "@/projects/host-projects"; +import { ICON_SIZE } from "@/styles/theme"; import { pickerItemLabel, type PickerItem } from "../../new-workspace-picker-item"; -import { addProjectIcon, branchIcon, folderIcon, ProjectIcon, pullRequestIcon } from "./icons"; +import type { ExistingWorktree } from "../existing-worktrees"; +import { + addProjectIcon, + branchIcon, + existingWorktreeIcon, + folderIcon, + ProjectIcon, + pullRequestIcon, +} from "./icons"; interface OptionRowState { option: ComboboxOption; @@ -83,8 +95,11 @@ export function AddProjectOption({ onPress }: { onPress: () => void }): ReactEle ); } -const worktreeLeading = {branchIcon}; -const localLeading = {folderIcon}; +const ISOLATION_LEADING: Record = { + local: {folderIcon}, + worktree: {branchIcon}, + existing: {existingWorktreeIcon}, +}; export function IsolationOption({ option, @@ -97,11 +112,12 @@ export function IsolationOption({ ); } @@ -109,44 +125,116 @@ export function IsolationOption({ const branchLeading = {branchIcon}; const pullRequestLeading = {pullRequestIcon}; +type PullRequestState = "open" | "merged" | "closed"; +const PULL_REQUEST_STATES: Record = { + open: "open", + opened: "open", + merged: "merged", + closed: "closed", +}; + +function PullRequestLeading({ state }: { state: string }): ReactElement { + const known = PULL_REQUEST_STATES[state.toLowerCase()]; + if (!known) return pullRequestLeading; + return ( + + + + ); +} + +function WorktreeAge({ createdAt }: { createdAt: Date | null }): ReactElement { + return {useCompactTimeAgo(createdAt)}; +} + +export function WorktreeOption({ + option, + selected, + active, + onPress, + worktree, + disabled, +}: OptionRowState & { worktree: ExistingWorktree | undefined; disabled: boolean }): ReactElement { + const createdAt = worktree?.createdAt ?? null; + const trailingSlot = useMemo(() => , [createdAt]); + if (!worktree) return ; + return ( + + ); +} + +/** Where a branch is already checked out, when checking it out means working there. */ +export type BranchHolder = "project-directory" | "worktree" | null; + export function RefOption({ option, selected, active, onPress, item, + heldIn, disabled, -}: OptionRowState & { item: PickerItem | undefined; disabled: boolean }): ReactElement { +}: OptionRowState & { + item: PickerItem | undefined; + heldIn: BranchHolder; + disabled: boolean; +}): ReactElement { const { t } = useTranslation(); - const divergenceLabel = item?.kind === "branch" ? item.divergenceLabel : undefined; + const branchNote = item?.kind === "branch" ? item.divergenceLabel : undefined; + const heldLabel = { + "project-directory": t("newWorkspace.refPicker.inProjectDirectory"), + worktree: t("newWorkspace.refPicker.inWorktree"), + }; + const divergenceLabel = heldIn ? heldLabel[heldIn] : branchNote; const trailingSlot = useMemo( () => divergenceLabel ? {divergenceLabel} : undefined, [divergenceLabel], ); + const pullRequestState = item?.kind === "github-pr" ? item.item.state : null; + const pullRequestLeadingSlot = useMemo( + () => (pullRequestState === null ? undefined : ), + [pullRequestState], + ); if (!item) return ; - const isBranch = item.kind === "branch"; + if (item.kind === "branch") { + return ( + + ); + } + // The number is the row's identity and the title its name, so they read as two things. + const { numberPrefix } = getForgePresentation(item.item.forge ?? "github"); return ( ); } diff --git a/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx b/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx new file mode 100644 index 0000000000..5af8bcb942 --- /dev/null +++ b/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx @@ -0,0 +1,89 @@ +import { useMemo, type ReactElement } from "react"; +import { useWindowDimensions } from "react-native"; +import { useTranslation } from "react-i18next"; +import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; +import type { PickerItem, RefAction } from "../../new-workspace-picker-item"; + +/** Which list the ref picker shows: branches or pull requests. */ +export type RefList = PickerItem["kind"]; + +/** Below this width "Pull requests" and the action control do not fit on one row. */ +const SHORT_LABEL_MAX_WIDTH = 390; + +/** + * The ref picker's row under its search field: the list on the left, and on the right what a + * new worktree does with the pick. Each action segment says what it does while the pointer is on it. + * The action control is left out on a host that only knows the default actions. + */ +export function RefPickerToolbar({ + list, + onListChange, + action, + onActionChange, + canChooseAction, + changeRequestContext: context, +}: { + list: RefList; + onListChange: (list: RefList) => void; + action: RefAction; + onActionChange: (action: RefAction) => void; + canChooseAction: boolean; + changeRequestContext: "mr" | undefined; +}): ReactElement { + const { t } = useTranslation(); + const isNarrow = useWindowDimensions().width < SHORT_LABEL_MAX_WIDTH; + const listOptions = useMemo[]>( + () => [ + { + value: "branch", + label: t("newWorkspace.refPicker.branches"), + testID: "new-workspace-ref-picker-tab-branches", + }, + { + value: "github-pr", + label: isNarrow + ? t("newWorkspace.refPicker.pullRequestsShort", { context }) + : t("newWorkspace.refPicker.pullRequests", { context }), + testID: "new-workspace-ref-picker-tab-pull-requests", + }, + ], + [context, isNarrow, t], + ); + const actionOptions = useMemo[]>( + () => [ + { + value: "branch-off", + label: t("newWorkspace.refPicker.branchOff"), + tooltip: t("newWorkspace.refPicker.branchOffHint"), + testID: "new-workspace-ref-picker-branch-off", + }, + { + value: "checkout", + label: t("newWorkspace.refPicker.checkout"), + tooltip: t("newWorkspace.refPicker.checkoutHint"), + testID: "new-workspace-ref-picker-checkout", + }, + ], + [t], + ); + return ( + <> + + {canChooseAction ? ( + + ) : null} + + ); +} diff --git a/packages/app/src/screens/new-workspace/setup-model.test.ts b/packages/app/src/screens/new-workspace/setup-model.test.ts index 2e395cd99f..21a74d76fe 100644 --- a/packages/app/src/screens/new-workspace/setup-model.test.ts +++ b/packages/app/src/screens/new-workspace/setup-model.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; +import type { CheckoutWorktree } from "@getpaseo/protocol/messages"; import type { PickerItem } from "../new-workspace-picker-item"; import { + BranchInWorktreeError, createNewWorkspaceSetup, setupTargetOf, type NewWorkspaceSetup, @@ -14,6 +16,35 @@ const READY: SetupInputs = { project: { id: "p1", name: "repo" }, canCreateWorktree: true, supportsMetadata: true, + supportsRefActions: true, + worktrees: [], +}; + +function worktree(path: string, branchName: string | null, containsCwd = false): CheckoutWorktree { + return { path, branchName, head: null, createdAt: "2026-11-01T00:00:00.000Z", containsCwd }; +} + +const PROJECT_DIRECTORY = worktree("/repo", "main", true); +const FEATURE_WORKTREE = worktree("/worktrees/feature", "feature"); + +function branchItem(refName: string): PickerItem { + const name = refName.replace(/^refs\/(heads|remotes\/origin)\//, ""); + return { kind: "branch", name, refName, accessibilityLabel: `${name}, branch` }; +} + +const PULL_REQUEST: PickerItem = { + kind: "github-pr", + item: { + kind: "change_request", + number: 42, + title: "Add picker", + url: "https://example.com/pull/42", + state: "open", + body: null, + labels: [], + baseRefName: "main", + headRefName: "feature/picker", + }, }; /** The commands an item mounted for `inputs`' project and host receives. */ @@ -64,6 +95,22 @@ describe("New workspace setup commands", () => { expect(setup.getSnapshot().manualIsolation).toBe("worktree"); }); + it("branches off a plugin's base ref, even after the user switched branches to check out", async () => { + const setup = createNewWorkspaceSetup( + { ...READY, worktrees: [PROJECT_DIRECTORY] }, + recordingEffects().effects, + ); + setup.chooseRefAction("branch", "checkout"); + + await commandsOf(setup).setBaseRef({ type: "branch", name: "refs/remotes/origin/main" }); + + expect(setup.refActionFor("branch")).toBe("branch-off"); + expect(setup.checkoutRequestFor(setup.getSnapshot().pickerSelection.selectedItem)).toEqual({ + action: "branch-off", + refName: "refs/remotes/origin/main", + }); + }); + it("shows a base ref's short name and keeps the exact ref for creation", async () => { const setup = createNewWorkspaceSetup(READY, recordingEffects().effects); @@ -178,3 +225,100 @@ describe("New workspace setup commands", () => { expect(setup.getSnapshot().branch).toBeNull(); }); }); + +describe("New workspace isolation and ref actions", () => { + const WITH_WORKTREES: SetupInputs = { + ...READY, + worktrees: [PROJECT_DIRECTORY, FEATURE_WORKTREE], + }; + + it("works in an existing worktree without remembering it as the default isolation", () => { + const { effects, isolations } = recordingEffects(); + const setup = createNewWorkspaceSetup(WITH_WORKTREES, effects); + + setup.chooseExistingWorktree(FEATURE_WORKTREE.path); + + expect(setup.getSnapshot().existingWorktreePath).toBe("/worktrees/feature"); + expect(isolations).toEqual([]); + + setup.chooseIsolation("worktree"); + + expect(setup.getSnapshot().existingWorktreePath).toBeNull(); + expect(isolations).toEqual(["worktree"]); + }); + + it("branches off a branch and checks out a pull request until the user switches the action", () => { + const setup = createNewWorkspaceSetup(WITH_WORKTREES, recordingEffects().effects); + const release = branchItem("refs/remotes/origin/release"); + + expect(setup.checkoutRequestFor(release)).toEqual({ + action: "branch-off", + refName: "refs/remotes/origin/release", + }); + expect(setup.checkoutRequestFor(PULL_REQUEST)?.action).toBe("checkout"); + + setup.chooseRefAction("branch", "checkout"); + setup.chooseRefAction("github-pr", "branch-off"); + + expect(setup.checkoutRequestFor(release)).toEqual({ action: "checkout", refName: "release" }); + expect(setup.checkoutRequestFor(PULL_REQUEST)?.action).toBe("branch-off"); + }); + + it("keeps the default actions on a host that cannot branch off a pull request", () => { + const setup = createNewWorkspaceSetup( + { ...WITH_WORKTREES, supportsRefActions: false }, + recordingEffects().effects, + ); + + setup.chooseRefAction("github-pr", "branch-off"); + + expect(setup.refActionFor("github-pr")).toBe("checkout"); + expect(setup.checkoutRequestFor(PULL_REQUEST)?.action).toBe("checkout"); + }); + + it("sends checking out a branch another worktree holds to that worktree", () => { + const { effects, chosen, isolations } = recordingEffects(); + const setup = createNewWorkspaceSetup(WITH_WORKTREES, effects); + setup.chooseRefAction("branch", "checkout"); + + setup.chooseRef(branchItem("refs/remotes/origin/feature")); + + expect(setup.getSnapshot().existingWorktreePath).toBe("/worktrees/feature"); + expect(chosen).toEqual([]); + + setup.chooseRef(branchItem("refs/heads/main")); + + expect(setup.getSnapshot().existingWorktreePath).toBeNull(); + expect(setup.getSnapshot().manualIsolation).toBe("local"); + expect(isolations).toEqual([]); + }); + + it("takes a branch-off pick as the base even when a worktree holds the branch", () => { + const { effects, chosen } = recordingEffects(); + const setup = createNewWorkspaceSetup(WITH_WORKTREES, effects); + const feature = branchItem("refs/heads/feature"); + + setup.chooseRef(feature); + + expect(chosen).toEqual([feature]); + expect(setup.getSnapshot().existingWorktreePath).toBeNull(); + }); + + it("refuses to check out a branch another worktree holds instead of creating a renamed copy", () => { + const setup = createNewWorkspaceSetup(WITH_WORKTREES, recordingEffects().effects); + setup.chooseRefAction("branch", "checkout"); + + expect(() => setup.checkoutRequestFor(branchItem("refs/remotes/origin/main"))).toThrow( + new BranchInWorktreeError({ branchName: "main", worktree: PROJECT_DIRECTORY }), + ); + }); + + it("drops the chosen existing worktree when the project changes", () => { + const setup = createNewWorkspaceSetup(WITH_WORKTREES, recordingEffects().effects); + setup.chooseExistingWorktree(FEATURE_WORKTREE.path); + + setup.syncInputs({ ...WITH_WORKTREES, project: { id: "p2", name: "other" } }); + + expect(setup.getSnapshot().existingWorktreePath).toBeNull(); + }); +}); diff --git a/packages/app/src/screens/new-workspace/setup-model.ts b/packages/app/src/screens/new-workspace/setup-model.ts index 2a810d24c1..ca5998339e 100644 --- a/packages/app/src/screens/new-workspace/setup-model.ts +++ b/packages/app/src/screens/new-workspace/setup-model.ts @@ -1,7 +1,15 @@ import { useSyncExternalStore } from "react"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; +import type { CheckoutWorktree } from "@getpaseo/protocol/messages"; import { applyMetadataPatch } from "@/composer/draft/metadata"; -import { branchNameFromRef, type PickerItem } from "../new-workspace-picker-item"; +import { + branchNameFromRef, + DEFAULT_REF_ACTION, + pickerItemToCheckoutRequest, + type PickerCheckoutRequest, + type PickerItem, + type RefAction, +} from "../new-workspace-picker-item"; import { initialPickerSelectionState, reducePickerSelection, @@ -10,6 +18,7 @@ import { } from "../new-workspace-picker-state"; type Isolation = "local" | "worktree"; +type RefKind = PickerItem["kind"]; /** What the user has chosen on the New workspace screen, apart from project and host. */ interface SetupState { @@ -19,6 +28,13 @@ interface SetupState { branch: string | null; /** The created workspace's metadata. */ metadata: Readonly>; + /** + * The git worktree the workspace works in when the user chose Existing worktree. That is a + * local workspace at the worktree's path, so the isolation underneath stays as it was. + */ + existingWorktreePath: string | null; + /** The action the user switched to, per kind of ref; a kind without one uses its default. */ + refActions: Partial>; } /** @@ -32,6 +48,10 @@ export interface SetupInputs { project: { id: string; name: string } | null; canCreateWorktree: boolean; supportsMetadata: boolean; + /** Whether the host can branch off a pull request, so the user may pick either action. */ + supportsRefActions: boolean; + /** The project's git worktrees, the project directory's own among them. */ + worktrees: readonly CheckoutWorktree[]; } /** The project on the host a screen creates in; what an item is mounted for. */ @@ -61,6 +81,17 @@ export interface NewWorkspaceSetup { chooseBase(item: PickerItem): void; /** The isolation picker's entry, and the one `setIsolation` takes. */ chooseIsolation(isolation: Isolation): void; + /** The Existing worktree picker's entry. Not remembered as the next screen's default. */ + chooseExistingWorktree(path: string): void; + /** + * The ref picker's entry. Checking out a branch that a worktree already holds works in that + * worktree, since git keeps a branch in one worktree at a time. + */ + chooseRef(item: PickerItem): void; + chooseRefAction(kind: RefKind, action: RefAction): void; + refActionFor(kind: RefKind): RefAction; + /** What creating a new worktree from `item` asks the host for. */ + checkoutRequestFor(item: PickerItem | null): PickerCheckoutRequest | undefined; syncInputs(inputs: SetupInputs): void; /** * Commands for the items mounted for `target`. Once the screen is on another project or host @@ -77,6 +108,37 @@ export interface SetupEffects { syncBaseAttachment(item: PickerItem): void; } +/** The action a pick of `kind` takes: the user's switch, on a host that allows one, else the default. */ +export function refActionOf(input: { + refActions: SetupState["refActions"]; + supportsRefActions: boolean; + kind: RefKind; +}): RefAction { + const chosen = input.supportsRefActions ? input.refActions[input.kind] : undefined; + return chosen ?? DEFAULT_REF_ACTION[input.kind]; +} + +/** The worktree that has `branchName` checked out. Git keeps a branch in one worktree at a time. */ +export function worktreeHoldingBranch( + worktrees: readonly CheckoutWorktree[], + branchName: string, +): CheckoutWorktree | undefined { + return worktrees.find((worktree) => worktree.branchName === branchName); +} + +/** A checkout of a branch that is already checked out in another worktree. */ +export class BranchInWorktreeError extends Error { + readonly branchName: string; + readonly worktree: CheckoutWorktree; + + constructor(params: { branchName: string; worktree: CheckoutWorktree }) { + super(`${params.branchName} is already checked out in ${params.worktree.path}`); + this.name = "BranchInWorktreeError"; + this.branchName = params.branchName; + this.worktree = params.worktree; + } +} + const MOVED_MESSAGE = "The New workspace screen moved to another project or host; this item belongs to the previous one."; const LOCKED_MESSAGE = "The New workspace screen is locked while the workspace is being created."; @@ -97,6 +159,8 @@ export function createNewWorkspaceSetup( manualIsolation: null, branch: null, metadata: {}, + existingWorktreePath: null, + refActions: {}, }; let inputs = initial; let screenTarget = initial.project ? `${initial.serverId}\n${initial.project.id}` : null; @@ -116,9 +180,33 @@ export function createNewWorkspaceSetup( effects.syncBaseAttachment(item); }; const chooseIsolation = (isolation: Isolation) => { - update({ manualIsolation: isolation }); + update({ manualIsolation: isolation, existingWorktreePath: null }); effects.persistIsolation(isolation); }; + const refActionFor = (kind: RefKind): RefAction => + refActionOf({ + refActions: state.refActions, + supportsRefActions: inputs.supportsRefActions, + kind, + }); + /** The worktree a checkout of `item` would collide with, if `item` is a branch one holds. */ + const worktreeHolding = (item: PickerItem): CheckoutWorktree | undefined => { + if (item.kind !== "branch" || refActionFor(item.kind) !== "checkout") return undefined; + return worktreeHoldingBranch(inputs.worktrees, branchNameFromRef(item.refName)); + }; + const chooseRef = (item: PickerItem) => { + const holder = worktreeHolding(item); + if (!holder) { + chooseBase(item); + return; + } + // The project directory is Project directory, not one of the existing worktrees. + update( + holder.containsCwd + ? { manualIsolation: "local", existingWorktreePath: null } + : { existingWorktreePath: holder.path }, + ); + }; const commandsFor = (target: SetupTarget): SetupCommands => { const unlocked = (): SetupInputs => { if (!sameTarget(target)) throw new Error(MOVED_MESSAGE); @@ -138,6 +226,8 @@ export function createNewWorkspaceSetup( const refName = name.trim(); if (!current.project) throw new Error("Choose a project first."); if (!refName) throw new Error("A base branch needs a name."); + // A base is what a new worktree starts from, so the worktree branches off it. + update({ refActions: { ...state.refActions, branch: "branch-off" } }); chooseBase({ kind: "branch", name: branchNameFromRef(refName), @@ -167,6 +257,19 @@ export function createNewWorkspaceSetup( dispatchPicker, chooseBase, chooseIsolation, + chooseExistingWorktree: (path) => update({ existingWorktreePath: path }), + chooseRef, + chooseRefAction: (kind, action) => + update({ refActions: { ...state.refActions, [kind]: action } }), + refActionFor, + checkoutRequestFor: (item) => { + if (!item) return undefined; + const holder = worktreeHolding(item); + if (holder?.branchName) { + throw new BranchInWorktreeError({ branchName: holder.branchName, worktree: holder }); + } + return pickerItemToCheckoutRequest(item, refActionFor(item.kind)); + }, syncInputs: (next) => { inputs = next; // A branch and metadata are chosen for one project on one host. A project id can repeat @@ -174,7 +277,9 @@ export function createNewWorkspaceSetup( // target. An absent project is a screen that is still resolving, not a switch. if (!next.project) return; const nextTarget = `${next.serverId}\n${next.project.id}`; - if (screenTarget && screenTarget !== nextTarget) update({ branch: null, metadata: {} }); + if (screenTarget && screenTarget !== nextTarget) { + update({ branch: null, metadata: {}, existingWorktreePath: null }); + } screenTarget = nextTarget; }, commandsFor, diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index e677fbe3b0..04af82f604 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -68,6 +68,7 @@ import type { GitSetupOptions, CheckoutStatusResponse, CheckoutCommit, + CheckoutWorktree, ParsedDiffFile, CheckoutCommitResponse, CheckoutMergeResponse, @@ -5133,6 +5134,23 @@ export class DaemonClient { return { baseRef: payload.baseRef, commits: payload.commits }; } + /** Every git worktree of the repository `cwd` is in, whoever created it. */ + async listCheckoutWorktrees(cwd: string, requestId?: string): Promise { + const payload = + await this.sendNamespacedCorrelatedSessionRequest<"checkout.worktrees.list.response">({ + requestId, + message: { + type: "checkout.worktrees.list.request", + cwd, + }, + timeout: 60000, + }); + if (payload.error) { + throw new Error(payload.error.message); + } + return payload.worktrees; + } + async getCommitFileDiff( cwd: string, sha: string, diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index be4041976e..6a61389a96 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -2612,6 +2612,12 @@ export const CheckoutCommitsListRequestSchema = z.object({ requestId: z.string(), }); +export const CheckoutWorktreesListRequestSchema = z.object({ + type: z.literal("checkout.worktrees.list.request"), + cwd: z.string(), + requestId: z.string(), +}); + export const CheckoutCommitFileDiffRequestSchema = z.object({ type: z.literal("checkout.commits.file_diff.request"), cwd: z.string(), @@ -3656,6 +3662,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ CheckoutForgeSetAutoMergeRequestSchema, CheckoutGithubSetAutoMergeRequestSchema, CheckoutCommitsListRequestSchema, + CheckoutWorktreesListRequestSchema, CheckoutCommitFileDiffRequestSchema, CheckoutForgeGetCheckDetailsRequestSchema, CheckoutGithubGetCheckDetailsRequestSchema, @@ -3947,6 +3954,11 @@ export const ServerInfoStatusPayloadSchema = z terminalCollection: z.boolean().optional(), // COMPAT(workspaceBaseBranch): added after v0.11.2, remove gate after 2027-10-14. workspaceBaseBranch: z.boolean().optional(), + // COMPAT(checkoutWorktreeList): added after v0.16.2, remove gate after 2027-11-19. + checkoutWorktreeList: z.boolean().optional(), + // COMPAT(worktreeRefActions): added after v0.16.2, remove gate after 2027-11-19. + // Hosts without it check out a change request even when asked to branch off it. + worktreeRefActions: z.boolean().optional(), // COMPAT(workspaceSetupRun): added in v0.8.0, remove gate after 2027-09-02. workspaceSetupRun: z.boolean().optional(), // COMPAT(workspaceTerminals): added in v0.8.0, remove gate after 2027-09-05. @@ -6090,6 +6102,26 @@ export const CheckoutCommitsListResponseSchema = z.object({ }), }); +export const CheckoutWorktreeSchema = z.object({ + path: z.string(), + // null when HEAD is detached + branchName: z.string().nullable(), + head: z.string().nullable(), + createdAt: z.string(), // ISO 8601 + // true for the worktree the request's cwd is in + containsCwd: z.boolean(), +}); + +export const CheckoutWorktreesListResponseSchema = z.object({ + type: z.literal("checkout.worktrees.list.response"), + payload: z.object({ + cwd: z.string(), + worktrees: z.array(CheckoutWorktreeSchema), + error: CheckoutErrorSchema.nullable(), + requestId: z.string(), + }), +}); + export const CheckoutCommitFileDiffResponseSchema = z.object({ type: z.literal("checkout.commits.file_diff.response"), payload: z.object({ @@ -7590,6 +7622,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ CheckoutForgeSetAutoMergeResponseSchema, CheckoutGithubSetAutoMergeResponseSchema, CheckoutCommitsListResponseSchema, + CheckoutWorktreesListResponseSchema, CheckoutCommitFileDiffResponseSchema, CheckoutForgeGetCheckDetailsResponseSchema, CheckoutGithubGetCheckDetailsResponseSchema, @@ -7974,6 +8007,9 @@ export type CheckoutCommitFile = z.infer; export type CheckoutCommit = z.infer; export type CheckoutCommitsListRequest = z.infer; export type CheckoutCommitsListResponse = z.infer; +export type CheckoutWorktree = z.infer; +export type CheckoutWorktreesListRequest = z.infer; +export type CheckoutWorktreesListResponse = z.infer; export type CheckoutCommitFileDiffRequest = z.infer; export type CheckoutCommitFileDiffResponse = z.infer; export type ParsedDiffFile = z.infer; diff --git a/packages/server/src/server/agent/host-operations/index.test.ts b/packages/server/src/server/agent/host-operations/index.test.ts index bc54209e60..12272ef66c 100644 --- a/packages/server/src/server/agent/host-operations/index.test.ts +++ b/packages/server/src/server/agent/host-operations/index.test.ts @@ -14,6 +14,7 @@ class OlderHostSocket { onclose: Handler = null; onerror: Handler = null; private readonly createSent = Promise.withResolvers>(); + private readonly workspaceCreateSent = Promise.withResolvers>(); constructor() { queueMicrotask(() => this.onopen?.()); @@ -23,6 +24,10 @@ class OlderHostSocket { return this.createSent.promise; } + workspaceCreateRequest(): Promise> { + return this.workspaceCreateSent.promise; + } + send(data: string): void { const frame = JSON.parse(data); if (frame.type === "hello") { @@ -57,6 +62,7 @@ class OlderHostSocket { }); } if (message.type === "create_agent_request") this.createSent.resolve(message); + if (message.type === "workspace.create.request") this.workspaceCreateSent.resolve(message); } close(): void { @@ -189,3 +195,40 @@ test("a remote child of another provider leaves its mode to the host", async () test("a remote create without a caller agent leaves its mode to the host", async () => { expect(await forwardedMode(null)).toBeUndefined(); }); + +async function forwardedWorktreeSource(args: Record) { + const { client, socket } = await olderHost(); + const creating = resolverFor(client, null).use("srv_older", (host) => + host.createWorkspace({ isolation: "worktree", path: "/repo/older", ...args }, {} as never), + ); + creating.catch(() => {}); + const request = (await socket.workspaceCreateRequest()) as { source: Record }; + return request.source; +} + +test("a remote worktree for a pull request without a mode checks the pull request out", async () => { + expect(await forwardedWorktreeSource({ prNumber: 42 })).toMatchObject({ + action: "checkout", + githubPrNumber: 42, + }); +}); + +test("a remote worktree without a mode or pull request branches off", async () => { + expect(await forwardedWorktreeSource({ baseBranch: "main" })).toMatchObject({ + action: "branch-off", + }); +}); + +test("a remote worktree that branches off a pull request is refused, as on the local host", async () => { + const { client, socket } = await olderHost(); + + await expect( + resolverFor(client, null).use("srv_older", (host) => + host.createWorkspace( + { isolation: "worktree", path: "/repo/older", mode: "branch-off", prNumber: 42 }, + {} as never, + ), + ), + ).rejects.toThrow("branch, prNumber, and forge require a checkout mode"); + expect(socket.requests.map((request) => request.type)).not.toContain("workspace.create.request"); +}); diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index 93b7ad2233..4abc9b9d0a 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -353,6 +353,10 @@ export function createHostResolver(input: { async createWorkspace(args) { const isolation = z.enum(["local", "worktree"]).parse(args.isolation); const path = z.string().min(1).parse(args.path); + if (args.mode === "branch-off" && args.prNumber !== undefined) { + // As on the local host: branching off a pull request is the app's, not this tool's. + throw new Error("branch, prNumber, and forge require a checkout mode"); + } const response = await client.createWorkspace({ source: isolation === "local" @@ -361,10 +365,12 @@ export function createHostResolver(input: { kind: "worktree", cwd: path, projectId: args.projectId as string | undefined, + // A pull request with no mode is checked out, as it was before a pull request could be branched off. action: - args.mode === "checkout-branch" || args.mode === "checkout-pr" - ? "checkout" - : "branch-off", + args.mode === "branch-off" || + (args.mode === undefined && args.prNumber === undefined) + ? "branch-off" + : "checkout", baseBranch: args.baseBranch as string | undefined, branchName: args.branchName as string | undefined, refName: args.branch as string | undefined, diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 2015316b07..2214f6bb5e 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -53,6 +53,7 @@ const INBOUND_PERMISSION = { "chat/wait": "workspace.read", "checkout.commits.file_diff.request": "workspace.read", "checkout.commits.list.request": "workspace.read", + "checkout.worktrees.list.request": "workspace.read", "checkout.discard_changes.request": "workspace.write", "checkout.forge.get_check_details.request": "workspace.read", "checkout.forge.set_auto_merge.request": "workspace.write", @@ -303,6 +304,7 @@ const OUTBOUND_PERMISSION = { "chat/wait/response": "workspace.read", "checkout.commits.file_diff.response": "workspace.read", "checkout.commits.list.response": "workspace.read", + "checkout.worktrees.list.response": "workspace.read", "checkout.discard_changes.response": "workspace.write", "checkout.forge.get_check_details.response": "workspace.read", "checkout.forge.set_auto_merge.response": "workspace.write", diff --git a/packages/server/src/server/resolve-worktree-creation-intent.test.ts b/packages/server/src/server/resolve-worktree-creation-intent.test.ts index 8d44b9ba80..94e463a48f 100644 --- a/packages/server/src/server/resolve-worktree-creation-intent.test.ts +++ b/packages/server/src/server/resolve-worktree-creation-intent.test.ts @@ -6,6 +6,7 @@ import { CheckoutSourceForgeMismatchError, MissingCheckoutTargetError, resolveWorktreeCreationIntent, + type ResolveWorktreeCreationIntentDeps, UnsupportedForgeCheckoutTargetError, } from "./resolve-worktree-creation-intent.js"; @@ -19,6 +20,7 @@ interface ResolverHarness { forgeService: ForgeService; headRefLookups: GitHubHeadRefLookup[]; resolveDefaultBranch: (repoRoot: string) => Promise; + fetchRef: ResolveWorktreeCreationIntentDeps["fetchRef"]; } function createResolverHarness(overrides?: { @@ -86,6 +88,7 @@ function createResolverHarness(overrides?: { forgeService, headRefLookups, resolveDefaultBranch: async () => "main", + fetchRef: async () => "origin", }; } diff --git a/packages/server/src/server/resolve-worktree-creation-intent.ts b/packages/server/src/server/resolve-worktree-creation-intent.ts index 34d587da03..011384a61e 100644 --- a/packages/server/src/server/resolve-worktree-creation-intent.ts +++ b/packages/server/src/server/resolve-worktree-creation-intent.ts @@ -1,5 +1,5 @@ import type { ForgeService, PullRequestCheckoutTarget } from "../services/forge-service.js"; -import type { WorktreeSource } from "../utils/worktree.js"; +import type { WorktreeCheckoutRef, WorktreeSource } from "../utils/worktree.js"; export type WorktreeCreationIntent = Exclude< WorktreeSource, @@ -29,6 +29,14 @@ export interface ResolveWorktreeCreationIntentDeps { forge: string; forgeService: ForgeService; resolveDefaultBranch: (repoRoot: string) => Promise; + /** Fetches the first ref a remote serves into a local ref, and returns that remote's name. */ + fetchRef: (input: FetchRefInput) => Promise; +} + +export interface FetchRefInput { + repoRoot: string; + sources: WorktreeCheckoutRef[]; + destination: string; } export class MissingCheckoutTargetError extends Error { @@ -70,10 +78,19 @@ export async function resolveWorktreeCreationIntent( deps: ResolveWorktreeCreationIntentDeps, ): Promise { if (input.action === "branch-off") { + const branchName = input.branchName ?? input.worktreeSlug ?? "worktree"; + const changeRequest = resolveInputChangeRequest(input); + if (changeRequest) { + return { + kind: "branch-off", + ...(await fetchChangeRequestHead({ input, changeRequest, repoRoot, deps })), + branchName, + }; + } return { kind: "branch-off", baseBranch: input.refName?.trim() || (await resolveDefaultBranch(repoRoot, deps)), - branchName: input.branchName ?? input.worktreeSlug ?? "worktree", + branchName, }; } @@ -126,6 +143,50 @@ export async function resolveWorktreeCreationIntent( }; } +/** + * Fetches a change request's head, so a new branch can start from it without checking the change + * request out. The head lands outside `refs/remotes`, which base branch pickers list. The remote + * that serves the change request is the repository it merges into, which is `upstream` in a fork + * clone. The base comes from that remote: a same-repository change request's own branch, so its + * pull request stacks on the change request, or a fork's target branch, since the fork's branch is + * not in this repository. + */ +async function fetchChangeRequestHead(params: { + input: ResolveWorktreeCreationIntentInput; + changeRequest: { number: number; forge?: string }; + repoRoot: string; + deps: ResolveWorktreeCreationIntentDeps; +}): Promise<{ baseBranch: string; startPoint: string }> { + const { input, changeRequest, repoRoot, deps } = params; + assertCheckoutSourceMatchesResolvedForge(changeRequest, deps); + const checkout = await resolvePrCheckoutIntent({ + refName: input.refName, + changeRequestNumber: changeRequest.number, + repoRoot, + deps, + }); + const startPoint = `refs/paseo/change-requests/${changeRequest.number}`; + const remote = await deps.fetchRef({ + repoRoot, + sources: checkout.checkoutRefs, + destination: startPoint, + }); + const baseName = checkout.trackOriginHead ? checkout.headRef : checkout.baseRefName; + const baseBranch = `refs/remotes/${remote}/${baseName}`; + try { + // Compared as the remote has it, not as a local branch last pulled. + await deps.fetchRef({ + repoRoot, + sources: [{ remoteName: remote, remoteRef: `refs/heads/${baseName}` }], + destination: baseBranch, + }); + return { baseBranch, startPoint }; + } catch { + // Without the remote's copy, the base resolves as any base branch name does. + return { baseBranch: baseName, startPoint }; + } +} + interface PrCheckoutIntentParams { refName?: string; changeRequestNumber: number; @@ -163,9 +224,11 @@ function assertCheckoutSourceMatchesResolvedForge( } } -async function resolvePrCheckoutIntent( - params: PrCheckoutIntentParams, -): Promise> { +async function resolvePrCheckoutIntent(params: PrCheckoutIntentParams): Promise< + Extract & { + checkoutRefs: WorktreeCheckoutRef[]; + } +> { const { deps } = params; const service = deps.forgeService; const checkoutTarget = await resolvePrCheckoutTarget(params); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 18080617e7..df317e94cf 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -3326,6 +3326,8 @@ export class Session { return this.checkoutSession.handleStatusRequest(msg); case "checkout.commits.list.request": return this.checkoutSession.handleCommitsListRequest(msg); + case "checkout.worktrees.list.request": + return this.checkoutSession.handleWorktreesListRequest(msg); case "checkout.commits.file_diff.request": return this.checkoutSession.handleCommitFileDiffRequest(msg, this.delivery.requestSignal); case "validate_branch_request": diff --git a/packages/server/src/server/session/checkout/checkout-session.ts b/packages/server/src/server/session/checkout/checkout-session.ts index 1611356bc8..8f180a36c4 100644 --- a/packages/server/src/server/session/checkout/checkout-session.ts +++ b/packages/server/src/server/session/checkout/checkout-session.ts @@ -11,6 +11,7 @@ import type { CheckoutRefreshRequest, CheckoutRenameBranchRequest, CheckoutStatusRequest, + CheckoutWorktreesListRequest, SessionInboundMessage, SessionOutboundMessage, SubscribeCheckoutDiffRequest, @@ -54,6 +55,7 @@ import { } from "../../../utils/checkout-git.js"; import { runGitCommand } from "../../../utils/run-git-command.js"; import { expandTilde } from "../../../utils/path.js"; +import { listGitWorktrees } from "../../../utils/worktree.js"; import type { GitMetadataGenerator } from "./git-metadata-generator.js"; /** @@ -290,6 +292,23 @@ export class CheckoutSession { } } + async handleWorktreesListRequest(msg: CheckoutWorktreesListRequest): Promise { + const { cwd, requestId } = msg; + + try { + const worktrees = await listGitWorktrees({ cwd: expandTilde(cwd) }); + this.host.emit({ + type: "checkout.worktrees.list.response", + payload: { cwd, worktrees, error: null, requestId }, + }); + } catch (error) { + this.host.emit({ + type: "checkout.worktrees.list.response", + payload: { cwd, worktrees: [], error: toCheckoutError(error), requestId }, + }); + } + } + async handleCommitFileDiffRequest( msg: CheckoutCommitFileDiffRequest, signal: AbortSignal, diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index bd6a4d56fb..2fab6c73a4 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2058,6 +2058,10 @@ export class VoiceAssistantWebSocketServer { // COMPAT(backgroundAgents): added in v0.15.0; remove gate after 2027-05-03. backgroundAgents: true, workspaceBaseBranch: true, + // COMPAT(checkoutWorktreeList): added after v0.16.2, remove gate after 2027-11-19. + checkoutWorktreeList: true, + // COMPAT(worktreeRefActions): added after v0.16.2, remove gate after 2027-11-19. + worktreeRefActions: true, // COMPAT(directorySync): added in v0.3.x, remove gate after 2027-02-12. directorySync: true, // COMPAT(workspaceLabels): added in v0.5.0, remove after 2027-08-14. diff --git a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts index cd9ec71d83..22f3ac4e08 100644 --- a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts +++ b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts @@ -73,6 +73,43 @@ test("workspace.create worktree source forwards action=checkout + refName into t } }, 180000); +test("checkout.worktrees.list returns git worktrees Paseo did not create", async () => { + const daemon = await createTestPaseoDaemon(); + const { repoDir, tempRoot } = createGitRepoWithBranch(); + const manualPath = path.join(tempRoot, "manual"); + execFileSync("git", ["worktree", "add", "-b", "feature/manual", manualPath], { + cwd: repoDir, + stdio: "pipe", + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.1.82", + }); + + try { + await client.connect(); + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, action: "branch-off", branchName: "feature/paseo" }, + }); + expect(created.error).toBeNull(); + + const worktrees = await client.listCheckoutWorktrees(repoDir); + + expect(worktrees.map(({ branchName, containsCwd }) => ({ branchName, containsCwd }))).toEqual( + expect.arrayContaining([ + { branchName: "main", containsCwd: true }, + { branchName: "feature/manual", containsCwd: false }, + { branchName: "feature/paseo", containsCwd: false }, + ]), + ); + expect(worktrees).toHaveLength(3); + } finally { + await client.close().catch(() => undefined); + await daemon.close(); + await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } +}, 180000); + test.each([false, true])( "workspace.create opens worktree.terminals (setup service: %s)", async (withSetupService) => { diff --git a/packages/server/src/server/worktree-core.posix.test.ts b/packages/server/src/server/worktree-core.posix.test.ts index 7a7a342732..f8417d01ab 100644 --- a/packages/server/src/server/worktree-core.posix.test.ts +++ b/packages/server/src/server/worktree-core.posix.test.ts @@ -379,6 +379,10 @@ function getBranchUpstream(cwd: string): string | null { return result.status === 0 ? result.stdout.trim() : null; } +function git(cwd: string, ...args: string[]): string { + return execFileSync("git", args, { cwd, stdio: "pipe" }).toString().trim(); +} + function getGitConfigValue(cwd: string, key: string): string | null { const result = spawnSync("git", ["config", "--get", key], { cwd, @@ -638,6 +642,36 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { expect(branch).toBe("dev"); }); + test("checks out a branch that only a remote other than origin has", async () => { + const { tempDir, repoDir, paseoHome } = createGitRepo(); + cleanupPaths.push(tempDir); + const upstreamDir = path.join(tempDir, "upstream.git"); + execFileSync("git", ["clone", "--bare", repoDir, upstreamDir], { stdio: "pipe" }); + execFileSync("git", [`--git-dir=${upstreamDir}`, "branch", "feature/upstream-only", "main"], { + stdio: "pipe", + }); + execFileSync("git", ["remote", "add", "upstream", upstreamDir], { + cwd: repoDir, + stdio: "pipe", + }); + execFileSync("git", ["fetch", "upstream"], { cwd: repoDir, stdio: "pipe" }); + + const result = await createCoreWorktree( + { + cwd: repoDir, + action: "checkout", + refName: "feature/upstream-only", + paseoHome, + }, + createCoreDeps(), + ); + + expect(result.worktree.branchName).toBe("feature/upstream-only"); + expect(getBranchUpstream(result.worktree.worktreePath)).toBe( + "upstream/feature/upstream-only", + ); + }); + test("checks out an explicit GitHub PR target", async () => { const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo(); cleanupPaths.push(tempDir); @@ -1450,6 +1484,242 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => { ).rejects.toBeInstanceOf(UnknownBranchError); }); + test("branches off a same-repo pull request's head without checking it out", async () => { + const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + // The head branch has never been fetched, so creation has to fetch it. + execFileSync("git", ["update-ref", "-d", "refs/remotes/origin/daemon-shutdown-diagnostics"], { + cwd: repoDir, + stdio: "pipe", + }); + const github = { + ...createGitHubServiceStub(), + getPullRequestCheckoutTarget: async () => ({ + number: 1790, + baseRefName: "main", + headRefName: "daemon-shutdown-diagnostics", + headOwnerLogin: "getpaseo", + headRepositorySshUrl: remoteDir, + headRepositoryUrl: remoteDir, + isCrossRepository: false, + }), + }; + + const result = await createCoreWorktree( + { + cwd: repoDir, + action: "branch-off", + checkoutSource: { kind: "change_request", forge: "github", number: 1790 }, + branchName: "follow-up", + paseoHome, + }, + createCoreDeps({ github }), + ); + + const prHead = execFileSync("git", [ + `--git-dir=${remoteDir}`, + "rev-parse", + "refs/pull/1790/head", + ]) + .toString() + .trim(); + expect(result.intent).toEqual({ + kind: "branch-off", + baseBranch: "refs/remotes/origin/daemon-shutdown-diagnostics", + startPoint: "refs/paseo/change-requests/1790", + branchName: "follow-up", + }); + expect(result.worktree.branchName).toBe("follow-up"); + expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(prHead); + expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull(); + expect(result.worktree.comparisonBaseRef).toBe( + "refs/remotes/origin/daemon-shutdown-diagnostics", + ); + expect(git(repoDir, "branch", "--list", "daemon-shutdown-diagnostics")).toBe(""); + }); + + test("branches off a same-repo pull request in a clone whose origin is a fork", async () => { + const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + // The layout a fork clone has: upstream is the base repository, origin is the fork, and + // the fork has an older branch with the pull request's branch name. + const forkDir = path.join(tempDir, "fork.git"); + execFileSync("git", ["clone", "--bare", remoteDir, forkDir], { stdio: "pipe" }); + execFileSync("git", [ + `--git-dir=${forkDir}`, + "update-ref", + "refs/heads/daemon-shutdown-diagnostics", + "refs/heads/main", + ]); + execFileSync("git", ["remote", "rename", "origin", "upstream"], { + cwd: repoDir, + stdio: "pipe", + }); + execFileSync("git", ["remote", "add", "origin", forkDir], { cwd: repoDir, stdio: "pipe" }); + const github = { + ...createGitHubServiceStub(), + getPullRequestCheckoutTarget: async () => ({ + number: 1790, + baseRefName: "main", + headRefName: "daemon-shutdown-diagnostics", + headOwnerLogin: "getpaseo", + headRepositorySshUrl: remoteDir, + headRepositoryUrl: remoteDir, + isCrossRepository: false, + // As the GitHub service lists them: origin first, then upstream. + checkoutRefs: [ + { remoteName: "origin", remoteRef: "refs/pull/1790/head" }, + { remoteName: "upstream", remoteRef: "refs/pull/1790/head" }, + ], + }), + }; + + const result = await createCoreWorktree( + { + cwd: repoDir, + action: "branch-off", + checkoutSource: { kind: "change_request", forge: "github", number: 1790 }, + branchName: "follow-up", + paseoHome, + }, + createCoreDeps({ github }), + ); + + const prHead = execFileSync("git", [ + `--git-dir=${remoteDir}`, + "rev-parse", + "refs/pull/1790/head", + ]) + .toString() + .trim(); + expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(prHead); + expect(result.intent).toEqual({ + kind: "branch-off", + baseBranch: "refs/remotes/upstream/daemon-shutdown-diagnostics", + startPoint: "refs/paseo/change-requests/1790", + branchName: "follow-up", + }); + }); + + test("branches off a fork pull request's head without checking it out", async () => { + const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + // The base repository's main moved on since this clone last fetched. + const baseRemoteDir = path.join(tempDir, "base.git"); + const upstreamMain = execFileSync("git", [ + "-c", + "user.name=Test", + "-c", + "user.email=test@test.com", + `--git-dir=${baseRemoteDir}`, + "commit-tree", + "main^{tree}", + "-p", + "main", + "-m", + "upstream commit", + ]) + .toString() + .trim(); + execFileSync("git", [ + `--git-dir=${baseRemoteDir}`, + "update-ref", + "refs/heads/main", + upstreamMain, + ]); + const github = { + ...createGitHubServiceStub(), + getPullRequestCheckoutTarget: async () => ({ + number: 526, + baseRefName: "main", + headRefName: "main", + headOwnerLogin: "therainisme", + headRepositorySshUrl: headRemoteDir, + headRepositoryUrl: headRemoteDir, + isCrossRepository: true, + }), + }; + + const result = await createCoreWorktree( + { + cwd: repoDir, + action: "branch-off", + checkoutSource: { kind: "change_request", forge: "github", number: 526 }, + branchName: "follow-up", + paseoHome, + }, + createCoreDeps({ github }), + ); + + const readme = readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8"); + // The fork's branch is not in this repository, so a pull request from the new branch goes + // into the fork pull request's base, compared as the remote has it now. + expect(result.intent).toEqual({ + kind: "branch-off", + baseBranch: "refs/remotes/origin/main", + startPoint: "refs/paseo/change-requests/526", + branchName: "follow-up", + }); + expect(git(repoDir, "rev-parse", "refs/remotes/origin/main")).toBe(upstreamMain); + expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/origin/main"); + expect(result.worktree.branchName).toBe("follow-up"); + expect(readme.replace(/\r\n/g, "\n")).toBe("fork pr main branch\n"); + expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull(); + expect((await readPaseoWorktreeMetadata(result.worktree.worktreePath))?.baseRefName).toBe( + "main", + ); + expect(git(repoDir, "branch", "--list", "therainisme/main")).toBe(""); + expect(getGitConfigValue(repoDir, "remote.paseo-pr-526.url")).toBeNull(); + // Base branch pickers list remote-tracking refs; the fork's head is not one of them. + expect(git(repoDir, "for-each-ref", "refs/remotes/paseo-pr-526")).toBe(""); + }); + + test("branches off a fork pull request in a clone that calls the base repository upstream", async () => { + const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo(); + cleanupPaths.push(tempDir); + execFileSync("git", ["remote", "rename", "origin", "upstream"], { + cwd: repoDir, + stdio: "pipe", + }); + const github = { + ...createGitHubServiceStub(), + getPullRequestCheckoutTarget: async () => ({ + number: 526, + baseRefName: "main", + headRefName: "main", + headOwnerLogin: "therainisme", + headRepositorySshUrl: headRemoteDir, + headRepositoryUrl: headRemoteDir, + isCrossRepository: true, + // As the GitHub service lists them: origin first, then upstream. + checkoutRefs: [ + { remoteName: "origin", remoteRef: "refs/pull/526/head" }, + { remoteName: "upstream", remoteRef: "refs/pull/526/head" }, + ], + }), + }; + + const result = await createCoreWorktree( + { + cwd: repoDir, + action: "branch-off", + checkoutSource: { kind: "change_request", forge: "github", number: 526 }, + branchName: "follow-up", + paseoHome, + }, + createCoreDeps({ github }), + ); + + // The base comes from the remote that served the pull request. + expect(result.intent).toEqual({ + kind: "branch-off", + baseBranch: "refs/remotes/upstream/main", + startPoint: "refs/paseo/change-requests/526", + branchName: "follow-up", + }); + expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/upstream/main"); + }); + test("creates the agent-create worktree input shape", async () => { const { tempDir, repoDir, paseoHome } = createGitRepo(); cleanupPaths.push(tempDir); diff --git a/packages/server/src/server/worktree-core.ts b/packages/server/src/server/worktree-core.ts index cc6c9fdbd6..41f6363cdd 100644 --- a/packages/server/src/server/worktree-core.ts +++ b/packages/server/src/server/worktree-core.ts @@ -5,6 +5,7 @@ import { createNameId } from "mnemonic-id"; import type { ForgeService } from "../services/forge-service.js"; import { createWorktree, + fetchFirstAvailableRef, resolveDefaultWorktreePath, slugify, validateBranchSlug, @@ -76,7 +77,11 @@ async function createWorktreeCoreWithPriority( githubPrNumber: input.githubPrNumber, worktreeSlug: requestedWorktreeSlug, }; - } else if (input.checkoutSource !== undefined || input.githubPrNumber !== undefined) { + } else if ( + input.action !== "branch-off" && + (input.checkoutSource !== undefined || input.githubPrNumber !== undefined) + ) { + // A change request with no action is checked out, as clients did before `action` existed. intentInput = { checkoutSource: input.checkoutSource, githubPrNumber: input.githubPrNumber, @@ -88,6 +93,8 @@ async function createWorktreeCoreWithPriority( intentInput = { action: "branch-off", refName: input.refName, + checkoutSource: input.checkoutSource, + githubPrNumber: input.githubPrNumber, branchName: requestedBranchName, worktreeSlug, }; @@ -98,6 +105,8 @@ async function createWorktreeCoreWithPriority( forge: forge.forge, forgeService: forge.service, resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps), + fetchRef: ({ repoRoot: cwd, sources, destination }) => + fetchFirstAvailableRef({ cwd, sources, destination }), }); let normalizedSlug: string; @@ -182,7 +191,14 @@ function creationIntentFromRequest( original: WorktreeCreationIntent, ): WorktreeCreationIntent { if (request.kind === "branch-off") { - return { kind: request.kind, branchName: request.branch, baseBranch: request.baseRef }; + // Plugins see the base; where a branch off a fork's change request starts stays Paseo's. + const startPoint = original.kind === "branch-off" ? original.startPoint : undefined; + return { + kind: request.kind, + branchName: request.branch, + baseBranch: request.baseRef, + ...(startPoint ? { startPoint } : {}), + }; } if (request.kind === "checkout-branch") { return { diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 5ee2ec5b1a..46f2519763 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -13,6 +13,7 @@ import { getWorktreeTeardownCommands, isServiceScript, isPaseoOwnedWorktreeCwd, + listGitWorktrees, listPaseoWorktrees, readPaseoConfig, resolveWorktreeRuntimeEnv, @@ -1695,6 +1696,55 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(remaining.map((worktree) => worktree.path)).toEqual([second.worktreePath]); }); + it("lists every git worktree of the repository, not only Paseo's", async () => { + const paseoWorktree = await createLegacyWorktreeForTest({ + branchName: "feature/paseo", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "alpha", + paseoHome, + }); + const manualPath = join(tempDir, "manual"); + execFileSync("git", ["worktree", "add", "-b", "feature/manual", manualPath], { + cwd: repoDir, + }); + const detachedPath = join(tempDir, "detached"); + execFileSync("git", ["worktree", "add", "--detach", detachedPath], { cwd: repoDir }); + const removedPath = join(tempDir, "removed"); + execFileSync("git", ["worktree", "add", "-b", "feature/removed", removedPath], { + cwd: repoDir, + }); + rmSync(removedPath, { recursive: true, force: true }); + // Git reports a locked worktree as neither prunable nor gone after its directory is deleted. + const lockedRemovedPath = join(tempDir, "locked-removed"); + execFileSync( + "git", + ["worktree", "add", "--lock", "-b", "feature/locked", lockedRemovedPath], + { + cwd: repoDir, + }, + ); + rmSync(lockedRemovedPath, { recursive: true, force: true }); + + const fromProject = await listGitWorktrees({ cwd: repoDir }); + const fromPaseoWorktree = await listGitWorktrees({ cwd: paseoWorktree.worktreePath }); + + const [mainWorktree, ...linkedWorktrees] = fromProject.map( + ({ path, branchName, containsCwd }) => ({ path, branchName, containsCwd }), + ); + expect(mainWorktree).toEqual({ path: repoDir, branchName: "main", containsCwd: true }); + expect(linkedWorktrees.sort((a, b) => a.path.localeCompare(b.path))).toEqual( + [ + { path: paseoWorktree.worktreePath, branchName: "feature/paseo", containsCwd: false }, + { path: manualPath, branchName: "feature/manual", containsCwd: false }, + { path: detachedPath, branchName: null, containsCwd: false }, + ].sort((a, b) => a.path.localeCompare(b.path)), + ); + expect( + fromPaseoWorktree.filter((worktree) => worktree.containsCwd).map(({ path }) => path), + ).toEqual([paseoWorktree.worktreePath]); + }); + it("deletes a paseo worktree even when given a subdirectory path", async () => { const created = await createLegacyWorktreeForTest({ branchName: "main", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 98c48e460c..fcde189857 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -192,7 +192,13 @@ export interface WorktreeCheckoutRef { } export type WorktreeSource = - | { kind: "branch-off"; baseBranch: string; branchName: string } + | { + kind: "branch-off"; + baseBranch: string; + branchName: string; + /** Where the new branch starts when that is not `baseBranch`, such as a fork's head. */ + startPoint?: string; + } | { kind: "checkout-branch"; branchName: string } | { kind: "restore"; branchName: string; baseRef: string | null } | { kind: "restore-commit"; commit: string; baseRef: string } @@ -1071,9 +1077,18 @@ async function resolveMetadataOwnedWorktree( type ParsedPaseoWorktreeInfo = Omit; +interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo { + /** A bare repository or a worktree whose directory is gone; nothing can work there. */ + unusable?: true; +} + function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] { - const entries: ParsedPaseoWorktreeInfo[] = []; - let current: ParsedPaseoWorktreeInfo | null = null; + return parseWorktreeEntries(output).map(({ unusable: _unusable, ...entry }) => entry); +} + +function parseWorktreeEntries(output: string): ParsedWorktreeEntry[] { + const entries: ParsedWorktreeEntry[] = []; + let current: ParsedWorktreeEntry | null = null; for (const line of output.split("\n")) { if (line.startsWith("worktree ")) { @@ -1093,6 +1108,8 @@ function parseWorktreeList(output: string): ParsedPaseoWorktreeInfo[] { current.branchName = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref; } else if (line.startsWith("HEAD ")) { current.head = line.slice("HEAD ".length).trim(); + } else if (line === "bare" || line.startsWith("prunable")) { + current.unusable = true; } else if (line.trim().length === 0) { if (current.path) { entries.push(current); @@ -1120,6 +1137,49 @@ async function resolveWorktreeCreatedAtIso(worktreePath: string): Promise { + const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + }); + const { stdout: toplevel } = await runGitCommand(["rev-parse", "--show-toplevel"], { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + }); + const cwdWorktree = await normalizePathForOwnership(toplevel.trim()); + const worktrees: GitWorktree[] = []; + for (const entry of parseWorktreeEntries(stdout)) { + if (entry.unusable) continue; + // A locked worktree whose directory was deleted is neither prunable nor workable. + if (!(await pathExists(entry.path))) continue; + const path = await normalizePathForOwnership(entry.path); + worktrees.push({ + path, + branchName: entry.branchName ?? null, + head: entry.head ?? null, + createdAt: await resolveWorktreeCreatedAtIso(path), + containsCwd: path === cwdWorktree, + }); + } + return worktrees; +} + export async function listPaseoWorktrees({ cwd, paseoHome, @@ -1609,7 +1669,7 @@ async function resolveBranchOffWorktreeSourcePlan( const normalizedBaseBranch = normalizeRequiredBaseBranch(source.baseBranch); const resolvedBaseBranch = await resolveBaseBranchForWorktree(cwd, source.baseBranch); const branchExists = await localBranchExists(cwd, branchName); - const base = branchExists ? branchName : resolvedBaseBranch; + const base = branchExists ? branchName : (source.startPoint ?? resolvedBaseBranch); await refreshRemoteTrackingBaseRef(cwd, base); const candidateBranch = branchExists ? desiredSlug : branchName; const newBranchName = await resolveUniqueLocalBranchName(cwd, candidateBranch); @@ -1675,10 +1735,10 @@ async function resolveWorktreeSourcePlan({ const normalizedBaseRefName = normalizeRequiredBaseBranch(source.baseRefName); const changeRequestNumber = source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber; - await fetchWorktreeCheckoutRefs({ + await fetchFirstAvailableRef({ cwd, - localBranchName, - checkoutRefs: source.checkoutRefs ?? [ + destination: `refs/heads/${localBranchName}`, + sources: source.checkoutRefs ?? [ { remoteName: "origin", remoteRef: `refs/pull/${changeRequestNumber}/head` }, ], }); @@ -1777,23 +1837,23 @@ async function configureWorktreePushRemote(options: { } } -async function fetchWorktreeCheckoutRefs(options: { +/** + * Fetches the first of `sources` a remote serves into the local ref `destination`, and returns + * the name of that remote. + */ +export async function fetchFirstAvailableRef(options: { cwd: string; - localBranchName: string; - checkoutRefs: WorktreeCheckoutRef[]; -}): Promise { + sources: WorktreeCheckoutRef[]; + destination: string; +}): Promise { let lastResult: | Awaited> | { stderr: string; stdout: string; exitCode: number | null } | null = null; - for (const checkoutRef of options.checkoutRefs) { + for (const checkoutRef of options.sources) { + const remoteName = checkoutRef.remoteName ?? "origin"; lastResult = await runGitCommand( - [ - "fetch", - checkoutRef.remoteName ?? "origin", - `+${checkoutRef.remoteRef}:refs/heads/${options.localBranchName}`, - "--force", - ], + ["fetch", remoteName, `+${checkoutRef.remoteRef}:${options.destination}`, "--force"], { cwd: options.cwd, timeout: 120_000, @@ -1801,14 +1861,14 @@ async function fetchWorktreeCheckoutRefs(options: { }, ); if (lastResult.exitCode === 0) { - return; + return remoteName; } } - const attemptedRefs = options.checkoutRefs + const attemptedRefs = options.sources .map((checkoutRef) => `${checkoutRef.remoteName ?? "origin"} ${checkoutRef.remoteRef}`) .join(", "); throw new Error( - `Unable to fetch change request refs for worktree branch ${options.localBranchName}: ${attemptedRefs}${lastResult?.stderr ? `\n${lastResult.stderr}` : ""}`, + `Unable to fetch change request refs into ${options.destination}: ${attemptedRefs}${lastResult?.stderr ? `\n${lastResult.stderr}` : ""}`, ); } @@ -2007,9 +2067,38 @@ async function ensureLocalBranch(cwd: string, branchName: string): Promise cwd, timeout: 120_000, }); + return; } catch { + // Origin does not have it; another remote may. + } + const remoteBranch = await uniqueRemoteTrackingBranch(cwd, branchName); + if (!remoteBranch) { throw new UnknownBranchError({ branchName, cwd }); } + // Tracks the remote it came from, as `git checkout ` does for a branch on one remote. + await runGitCommand(["branch", "--track", branchName, remoteBranch], { cwd }); +} + +/** The one remote-tracking ref named `/`, if exactly one remote has it. */ +async function uniqueRemoteTrackingBranch(cwd: string, branchName: string): Promise { + const { stdout: remotes } = await runGitCommand(["remote"], { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + }); + const candidates: string[] = []; + for (const remote of remotes + .split("\n") + .map((name) => name.trim()) + .filter(Boolean)) { + const ref = `refs/remotes/${remote}/${branchName}`; + try { + await runGitCommand(["show-ref", "--verify", "--quiet", ref], { cwd }); + candidates.push(ref); + } catch { + // This remote does not have the branch. + } + } + return candidates.length === 1 ? candidates[0] : null; } async function localBranchExists(cwd: string, branchName: string): Promise { diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index d0297512b6..cefb4dabb7 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -2228,13 +2228,13 @@ export default function contribute(client: PluginClientContext) { `useNewWorkspace()` returns the setup the item sits in: -| Field or command | Meaning | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `host`, `project` | The user's choices, `{ id, label }` and `{ id, name } \| null`. Read-only: an item cannot switch host or project. | -| `isolation`, `setIsolation` | `"local"` or `"worktree"`. A project that cannot make worktrees reads `"local"`, and `setIsolation("worktree")` rejects. | -| `baseRef`, `setBaseRef` | What a new worktree starts from: `{ type: "branch", name }`, `{ type: "change-request", number }`, or `null` until the default is known. A branch's `name` is the exact ref creation uses, such as `refs/remotes/origin/main`, so `setBaseRef(newWorkspace.baseRef)` changes nothing. `setBaseRef` takes any ref the Base picker offers, or a bare branch name, which Paseo resolves as it does anywhere else. It rejects while no project is chosen. | -| `branch`, `setBranch` | The name of the branch a new worktree is created on. `null` lets Paseo pick one. It is kept while isolation is local or the base is a change request, and it names the new branch of any worktree that cuts one, from the default base or a chosen branch. It does not apply to a worktree that checks out an existing branch or change request. | -| `metadata`, `setMetadata` | The created workspace's [metadata](/docs/plugins/hooks#metadata), not the first agent's. Top-level keys replace; `null` removes a key. Rejects on a host that does not support metadata with "Update the host to use metadata." | +| Field or command | Meaning | +| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `host`, `project` | The user's choices, `{ id, label }` and `{ id, name } \| null`. Read-only: an item cannot switch host or project. | +| `isolation`, `setIsolation` | `"local"` or `"worktree"`. **Existing worktree** reads `"local"`, since the workspace is a local one at the worktree's directory, and `setIsolation` leaves it. A project that cannot make worktrees reads `"local"`, and `setIsolation("worktree")` rejects. | +| `baseRef`, `setBaseRef` | What a new worktree starts from: `{ type: "branch", name }`, `{ type: "change-request", number }`, or `null` until the default is known. A branch's `name` is the exact ref creation uses, such as `refs/remotes/origin/main`, so `setBaseRef(newWorkspace.baseRef)` changes nothing. `setBaseRef` takes any ref the Base picker offers, or a bare branch name, which Paseo resolves as it does anywhere else. The new worktree branches off it, and the Branches list switches to Branch off. It rejects while no project is chosen. | +| `branch`, `setBranch` | The name of the branch a new worktree is created on. `null` lets Paseo pick one. It is kept while isolation is local or the base is a change request, and it names the new branch of any worktree that cuts one, from the default base or a chosen branch. It does not apply to a worktree that checks out an existing branch or change request. | +| `metadata`, `setMetadata` | The created workspace's [metadata](/docs/plugins/hooks#metadata), not the first agent's. Top-level keys replace; `null` removes a key. Rejects on a host that does not support metadata with "Update the host to use metadata." | Commands follow the [composer item](#composer-items) rules: each one acts on the screen's state when it runs, so `await newWorkspace.setBranch(name)` followed by `newWorkspace.setMetadata(patch)` diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 724ce623ae..4ccfa740ee 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -1856,13 +1856,13 @@ export default function contribute(client: PluginClientContext) { `useNewWorkspace()` 返回该项所在的设置: -| 字段或命令 | 含义 | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `host`、`project` | 用户的选择,分别是 `{ id, label }` 和 `{ id, name } \| null`。只读:项不能切换主机或项目。 | -| `isolation`、`setIsolation` | `"local"` 或 `"worktree"`。无法创建 worktree 的项目读取为 `"local"`,此时 `setIsolation("worktree")` 会被拒绝。 | -| `baseRef`、`setBaseRef` | 新 worktree 的起点:`{ type: "branch", name }`、`{ type: "change-request", number }`,默认值未知时为 `null`。分支的 `name` 是创建时实际使用的完整 ref,例如 `refs/remotes/origin/main`,所以 `setBaseRef(newWorkspace.baseRef)` 不会改变任何内容。`setBaseRef` 接受 Base 选择器提供的任何 ref,或一个裸分支名,Paseo 会按其他地方一贯的方式解析。未选择项目时会被拒绝。 | -| `branch`、`setBranch` | 新 worktree 所创建的分支名称。`null` 表示由 Paseo 选择名称。隔离为本地或起点为变更请求时会保留该值,它为任何新建分支的 worktree 命名,起点可以是默认基线或所选分支;检出已有分支或变更请求的 worktree 不适用。 | -| `metadata`、`setMetadata` | 所创建工作区的[元数据](/docs/plugins/hooks#metadata),而不是第一个 Agent 的元数据。顶层键替换,`null` 删除该键。主机不支持元数据时以 “Update the host to use metadata.” 拒绝。 | +| 字段或命令 | 含义 | +| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `host`、`project` | 用户的选择,分别是 `{ id, label }` 和 `{ id, name } \| null`。只读:项不能切换主机或项目。 | +| `isolation`、`setIsolation` | `"local"` 或 `"worktree"`。**已有 worktree** 读取为 `"local"`,因为工作区是该 worktree 目录上的本地工作区;调用 `setIsolation` 会离开它。无法创建 worktree 的项目读取为 `"local"`,此时 `setIsolation("worktree")` 会被拒绝。 | +| `baseRef`、`setBaseRef` | 新 worktree 的起点:`{ type: "branch", name }`、`{ type: "change-request", number }`,默认值未知时为 `null`。分支的 `name` 是创建时实际使用的完整 ref,例如 `refs/remotes/origin/main`,所以 `setBaseRef(newWorkspace.baseRef)` 不会改变任何内容。`setBaseRef` 接受 Base 选择器提供的任何 ref,或一个裸分支名,Paseo 会按其他地方一贯的方式解析。新 worktree 会从它新建分支,分支列表会切换到新建分支。未选择项目时会被拒绝。 | +| `branch`、`setBranch` | 新 worktree 所创建的分支名称。`null` 表示由 Paseo 选择名称。隔离为本地或起点为变更请求时会保留该值,它为任何新建分支的 worktree 命名,起点可以是默认基线或所选分支;检出已有分支或变更请求的 worktree 不适用。 | +| `metadata`、`setMetadata` | 所创建工作区的[元数据](/docs/plugins/hooks#metadata),而不是第一个 Agent 的元数据。顶层键替换,`null` 删除该键。主机不支持元数据时以 “Update the host to use metadata.” 拒绝。 | 命令遵循 [Composer 项](#composer-items)的规则:每个命令都按界面运行时的状态执行,所以 `await newWorkspace.setBranch(name)` 之后再调用 `newWorkspace.setMetadata(patch)` 会同时生效,命令的 Promise 在更改生效后完成。命令从组件的第一个 effect 起即可使用,包括挂载时的 effect。载荷是 JSON 值。你的项针对某一台主机上的某一个项目挂载。用户更改其中任何一个时,Paseo 会重新挂载你的项并清除 `branch` 和 `metadata`,因此上一个项目的状态和 `Combobox` 结果不会保留;在挂载 effect 中做初始化的项会针对新项目再次初始化。在其项目或主机已被离开之后才调用的命令(例如用户切换项目时被放弃的查询最终返回)会以 "The New workspace screen moved to another project or host; this item belongs to the previous one." 拒绝,并且不做任何更改;为新项目挂载的项不受影响。`host`、`project`、`baseRef` 和 `metadata` 是冻结的。界面创建工作区期间会被锁定:你的字段显示为禁用,所有命令都会以 "The New workspace screen is locked while the workspace is being created." 拒绝。返回 Promise 的回调在完成之前会让控件保持禁用,被拒绝时会以错误提示向用户显示。 diff --git a/public-docs/schedules.md b/public-docs/schedules.md index b18804c117..955c4aeb82 100644 --- a/public-docs/schedules.md +++ b/public-docs/schedules.md @@ -40,6 +40,6 @@ Both run on a cadence you set. To start an agent from an external event instead Each new-agent schedule run creates a workspace. **Archive on finish** is on by default: when the run ends, Paseo archives that workspace and its agent. With worktree isolation, archiving also removes the worktree after its last active workspace is archived. -To keep runs available, open the schedule in the app's Schedules view, turn off **Archive on finish**, and save. Paseo keeps each run's workspace and agent active until you archive them; runs that fail before creating an agent are still cleaned up. This option also applies to local isolation; archiving a local workspace leaves the project directory in place. +To keep runs available, open the schedule in the app's Schedules view, turn off **Archive on finish**, and save. Paseo keeps each run's workspace and agent active until you archive them; runs that fail before creating an agent are still cleaned up. This option also applies to **Project directory** isolation; archiving that workspace leaves the project directory in place. The stored option is `target.config.archiveOnFinish`, a boolean that defaults to `true` when omitted. The CLI and MCP schedule tools do not expose this option; use the app to change it. Heartbeats use an existing agent and do not have this option. diff --git a/public-docs/schedules.zh-CN.md b/public-docs/schedules.zh-CN.md index b702d2ea00..f5818fe75d 100644 --- a/public-docs/schedules.zh-CN.md +++ b/public-docs/schedules.zh-CN.md @@ -38,6 +38,6 @@ cron 是标准的节奏表示。CLI 接受 `5m` 或 `1h` 这样的简单预设 新建 Agent 的定时任务每次运行都会创建一个工作区。**Archive on finish** 默认开启:运行结束时,Paseo 会归档该工作区及其 Agent。使用 worktree 隔离时,最后一个使用该 worktree 的活跃工作区被归档后,归档还会删除这个 worktree。 -要保留运行结果,在应用的定时任务视图中打开该定时任务,关闭 **Archive on finish** 并保存。Paseo 会让每次运行的工作区和 Agent 保持活跃,直到你手动归档;在创建 Agent 之前就失败的运行仍会被清理。该选项同样适用于本地隔离;归档本地工作区不会删除项目目录。 +要保留运行结果,在应用的定时任务视图中打开该定时任务,关闭 **Archive on finish** 并保存。Paseo 会让每次运行的工作区和 Agent 保持活跃,直到你手动归档;在创建 Agent 之前就失败的运行仍会被清理。该选项同样适用于 **Project directory** 隔离;归档该工作区不会删除项目目录。 存储的选项是 `target.config.archiveOnFinish`,一个布尔值,省略时默认为 `true`。CLI 和 MCP 的定时任务工具不提供这个选项;请在应用中修改。heartbeat 使用已有的 Agent,没有这个选项。 diff --git a/public-docs/workspaces.md b/public-docs/workspaces.md index 2e74935d54..acf54b337f 100644 --- a/public-docs/workspaces.md +++ b/public-docs/workspaces.md @@ -39,12 +39,13 @@ In Paseo, the workspace is the stable container. The sessions are what you run i ## Choose the isolation -Every workspace has an isolation mode: +When you create a workspace, **Isolation** sets the directory it works in: -- **Local** uses an existing directory, such as your main checkout. Use it when sessions should share the files already on disk. -- **Worktree** creates or opens a managed git worktree. Use it when a task needs its own directory and branch. +- **Project directory** uses the project's own directory, such as your main checkout. Use it when sessions should share the files already on disk. +- **New worktree** creates a git worktree with its own directory and branch. Use it when a task needs its own copy of the files. +- **Existing worktree** uses a git worktree that is already on disk, on the branch it has checked out. Use it to continue work on a branch without a second copy. The list shows every git worktree of the repository, including the ones that Paseo did not create. -The workspace is the product concept; a git worktree is one way to isolate its files. More than one workspace can refer to the same managed worktree, and Paseo removes that worktree after its last workspace is archived. +The workspace is the product concept; a git worktree is one way to isolate its files. More than one workspace can use the same worktree. Paseo removes a worktree that it created after the last workspace that uses it is archived. Paseo does not remove a worktree that it did not create. ## Creating a workspace diff --git a/public-docs/workspaces.zh-CN.md b/public-docs/workspaces.zh-CN.md index 481013095c..e074d2aefb 100644 --- a/public-docs/workspaces.zh-CN.md +++ b/public-docs/workspaces.zh-CN.md @@ -37,12 +37,13 @@ Agent 以会话的形式在工作区中运行。一个工作区可以同时打 ## 选择隔离方式 {#choose-the-isolation} -每个工作区都有一种隔离模式: +创建工作区时,**隔离** 决定它在哪个目录中工作: -- **本地** 使用一个现有目录,例如你的主检出。当会话应该共享磁盘上已有的文件时使用。 -- **新建 worktree** 创建或打开一个受管理的 git worktree。当任务需要自己的目录和分支时使用。 +- **项目目录** 使用项目自己的目录,例如你的主检出。当会话应该共享磁盘上已有的文件时使用。 +- **新建 worktree** 创建一个 git worktree,带有自己的目录和分支。当任务需要一份独立的文件副本时使用。 +- **已有 worktree** 使用磁盘上已有的 git worktree,并沿用它当前检出的分支。想在某个分支上继续工作而不再复制一份时使用。列表显示仓库的所有 git worktree,包括不是 Paseo 创建的。 -工作区是产品概念;git worktree 是隔离其文件的一种方式。多个工作区可以指向同一个受管理的 worktree,Paseo 会在最后一个引用它的工作区被归档后删除该 worktree。 +工作区是产品概念;git worktree 是隔离其文件的一种方式。多个工作区可以使用同一个 worktree。对于 Paseo 创建的 worktree,Paseo 会在最后一个使用它的工作区被归档后删除它。Paseo 不会删除不是它创建的 worktree。 ## 创建工作区 {#creating-a-workspace} diff --git a/public-docs/worktrees/index.md b/public-docs/worktrees/index.md index 55eb4de01b..63cc0975b3 100644 --- a/public-docs/worktrees/index.md +++ b/public-docs/worktrees/index.md @@ -46,6 +46,15 @@ Scheduled runs archive their workspaces when they finish by default. Turn off ** ## Create a worktree-backed workspace +In the app, set **Isolation** to **New worktree**, then pick a branch or a pull request. Next to the list, choose what the new worktree does with your pick: + +- **Branch off** starts a new branch from it. Branches use this by default. +- **Check out** works on the branch itself. Pull requests use this by default. + +When you branch off a pull request, the new branch starts at the pull request's latest commit and has no upstream. A push does not go to the pull request's branch. The workspace's base branch is the pull request's branch. For a pull request from a fork, it is the branch that the pull request merges into. + +Git keeps a branch in one worktree at a time. If you check out a branch that a worktree already has, Paseo selects that worktree under **Existing worktree** instead of making a copy. + The examples below use the current directory as the source checkout. Pass `--path ~/dev/my-app` to create the workspace from another checkout. Branch off from a base branch: @@ -82,6 +91,16 @@ paseo workspace create \ Add `--forge ` when Paseo cannot infer the forge from the source checkout. +## Work in an existing worktree + +To continue in a worktree that is already on disk, set **Isolation** to **Existing worktree** and pick it. The list shows every git worktree of the repository, including worktrees that you made with `git worktree add`. The workspace works on the branch that the worktree has checked out. Paseo does not create a branch or run setup. + +From the CLI, create a local workspace at the worktree's directory: + +```bash +paseo workspace create --isolation local --path ~/dev/my-app-feature +``` + ## Copy local files with .worktreeinclude Use [`.worktreeinclude`](/docs/worktrees/worktreeinclude) to copy selected gitignored files, such as `.env`, from your source checkout before setup runs. diff --git a/public-docs/worktrees/index.zh-CN.md b/public-docs/worktrees/index.zh-CN.md index 59f4342627..583321e699 100644 --- a/public-docs/worktrees/index.zh-CN.md +++ b/public-docs/worktrees/index.zh-CN.md @@ -44,6 +44,15 @@ worktree 默认存放在 `$PASEO_HOME/worktrees/` 下,按源检出路径的哈 ## 创建由 worktree 支撑的工作区 {#create-a-worktree-backed-workspace} +在应用中,将 **隔离** 设为 **新建 worktree**,然后选择一个分支或 Pull Request。在列表旁边选择新 worktree 如何处理你的选择: + +- **新建分支** 从它创建一个新分支。分支默认使用这个选项。 +- **检出** 直接在该分支上工作。Pull Request 默认使用这个选项。 + +从 Pull Request 新建分支时,新分支从 Pull Request 的最新提交开始,并且没有上游分支。推送不会进入 Pull Request 的分支。工作区的基础分支是 Pull Request 的分支。对于来自 fork 的 Pull Request,基础分支是该 Pull Request 要合并进的分支。 + +Git 同一时间只允许一个 worktree 检出某个分支。如果你检出的分支已经在某个 worktree 中,Paseo 会在 **已有 worktree** 下选中那个 worktree,而不是再复制一份。 + 下面的示例以当前目录作为源检出。传入 `--path ~/dev/my-app` 可以从另一个检出创建工作区。 从基础分支分出新分支: @@ -80,6 +89,16 @@ paseo workspace create \ 当 Paseo 无法从源检出推断代码托管平台时,添加 `--forge `。 +## 在已有 worktree 中工作 {#work-in-an-existing-worktree} + +要在磁盘上已有的 worktree 中继续工作,将 **隔离** 设为 **已有 worktree** 并选择它。列表显示仓库的所有 git worktree,包括你用 `git worktree add` 创建的。工作区沿用该 worktree 当前检出的分支。Paseo 不会创建分支,也不会运行 setup。 + +在 CLI 中,在该 worktree 的目录上创建一个本地工作区: + +```bash +paseo workspace create --isolation local --path ~/dev/my-app-feature +``` + ## 使用 .worktreeinclude 复制本地文件 {#copy-local-files-with-worktreeinclude} 使用 [`.worktreeinclude`](/docs/worktrees/worktreeinclude),在 setup 运行前将 `.env` 等选定的 Git 忽略文件从源检出复制到新 worktree。