From d8da34d23f0923049582620c367e99cd1630d91a Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:55:30 +0100 Subject: [PATCH 1/4] fix(stories): let Components Lab load stories that import Navigate (#64229) --- packages/stories/mocks/solid-router.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/stories/mocks/solid-router.tsx b/packages/stories/mocks/solid-router.tsx index f0a23570e70..5291ebc6ffc 100644 --- a/packages/stories/mocks/solid-router.tsx +++ b/packages/stories/mocks/solid-router.tsx @@ -68,6 +68,20 @@ export function useNavigate() { } } +export function Navigate(props: { + href: + | string + | ((args: { navigate: ReturnType; location: ReturnType }) => string) + state?: unknown +}) { + const navigate = useNavigate() + + const path = typeof props.href === "function" ? props.href({ navigate, location: useLocation() }) : props.href + + navigate(path, { replace: true, state: props.state }) + return null +} + export function useSearchParams>() { const ctx = useContext(RouterContext) From 8bd9bdf95d9a506b6b1b408c55fa3b8b987e785c Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:04:30 +0100 Subject: [PATCH 2/4] fix(app): show the base branch for new worktrees and apply branch picks immediately (#64228) --- .../app/e2e/regression/new-session.spec.ts | 458 +++++++++++------- packages/app/e2e/utils/workspace.ts | 19 +- .../new-session/draft.standalone.stories.tsx | 17 +- .../location/dialog.standalone.stories.tsx | 8 +- .../app/src/new-session/location/dialog.tsx | 267 ++-------- .../src/new-session/location/machine.test.ts | 47 -- .../app/src/new-session/location/machine.ts | 162 +------ packages/app/src/new-session/view.tsx | 158 +++--- .../workspace/branch-machine.test.ts | 10 + .../new-session/workspace/branch-machine.ts | 9 +- .../src/new-session/workspace/controller.ts | 13 +- .../src/new-session/workspace/selector.tsx | 240 +++++++-- packages/app/src/runtime/i18n/en.ts | 1 + packages/ui/src/forms/typeahead/typeahead.tsx | 15 +- 14 files changed, 708 insertions(+), 716 deletions(-) diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index 0066e107db0..9ab171fa4dc 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -4,8 +4,9 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { draftHref, expectPath, holdRoute, NO_PROVIDER, project, provider, seed, sessionHref, T0 } from "../utils/app" import { mockOpenCodeServer } from "../utils/mock-server" import { - newSessionBranch, + newSessionBaseBranch, newSessionLocation, + newSessionWorktree, openDraft, openSession, openWorktreeDraft, @@ -60,60 +61,58 @@ test("the new session screen does not show session details", async ({ page }) => }) test("the location shortcuts choose worktrees from every state and keep cycling", async ({ page }) => { - const root = "C:/OpenCode/LocationShortcut" - - const existing = `${root}/.worktrees/quiet-river` + const existing = "C:/OpenCode/LocationShortcut/.worktrees/quiet-river" const view = await openDraft(page, { name: "LocationShortcut", - worktrees: () => [{ directory: root }, { directory: existing, strategy: "git" }], - vcs: (directory) => - directory === existing ? { current: "fix-login", default: "main" } : { current: "main", default: "main" }, + vcs: (directory) => ({ current: directory === existing ? undefined : "dev", default: "main" }), + worktrees: () => [{ directory: "C:/OpenCode/LocationShortcut" }, { directory: existing, strategy: "git" }], }) const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) + const cycle = `${modifier}+Alt+KeyL` + + const worktree = newSessionWorktree(page) + + const base = newSessionBaseBranch(page) + const path = page.locator('[data-slot="new-session-location-path"]') const search = page.getByRole("combobox", { name: "Search worktrees", exact: true }) - const screen = page.locator('[data-component="new-session"]') + await expect(path).toHaveText(view.directory) + await expect(worktree).toHaveText("dev") + await view.editor.press(cycle) + await expect(base).toHaveText("from dev") + await expect(worktree).toHaveCount(0) + await expect(page.locator('[data-component="new-session"]').getByText("New worktree", { exact: true })).toHaveCount(0) + await expect(path).toHaveCount(0) + await view.editor.press(cycle) + await expect(worktree).toHaveText("dev") + await expect(base).toHaveCount(0) + await expect(path).toHaveText(view.directory) - const expectBranchOnly = async () => { - await expect(screen).not.toContainText("Local") - await expect(screen).not.toContainText("New worktree") - await expect(screen).not.toContainText("from ") - await expect(screen.locator('[data-action="prompt-worktree"]')).toHaveCount(0) - } - - await expect(path).toHaveText(root) - await expect(newSessionBranch(page)).toHaveText("main") - await expectBranchOnly() await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() await page.getByRole("option", { name: /^quiet-river / }).click() await expect(view.editor).toBeFocused() await expect(path).toHaveText(existing) - await expect(newSessionBranch(page)).toHaveText("fix-login") - await expectBranchOnly() + await expect(worktree).toHaveText("No branch") await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() - await page.getByRole("option", { name: /LocationShortcut main C:\/OpenCode\/LocationShortcut$/ }).click() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(path).toHaveText(root) - await view.editor.press(`${modifier}+Alt+KeyL`) - await expect(newSessionBranch(page)).toHaveText("main") - await expect(path).toHaveText(root) - await expectBranchOnly() + await page.getByRole("option", { name: /LocationShortcut dev C:\/OpenCode\/LocationShortcut$/ }).click() + await expect(view.editor).toBeFocused() + await view.editor.press(cycle) + await expect(base).toHaveText("from dev") await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() await page.getByRole("option", { name: /^quiet-river / }).click() await expect(path).toHaveText(existing) - await expect(newSessionBranch(page)).toHaveText("fix-login") await expect(view.editor).toBeFocused() }) -test("a draft opened in a worktree starts on the main checkout and targets it", async ({ page }) => { +test("the main checkout shows its branch and is targeted when the draft opened in a worktree", async ({ page }) => { const root = "C:/OpenCode/LocalFromWorktree" const worktree = `${root}/.worktrees/quiet-river` @@ -134,15 +133,15 @@ test("a draft opened in a worktree starts on the main checkout and targets it", const screen = page.locator('[data-component="new-session"]') - await expect(newSessionBranch(page)).toHaveText("checkout-branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(root) + await expect(newSessionWorktree(page)).toHaveText("checkout-branch") + await expect(screen.getByText("checkout-branch", { exact: true })).toHaveCount(1) await expect(screen.getByText("worktree-branch", { exact: true })).toHaveCount(0) await view.editor.fill("Run in the main checkout") await submit(page).click() await expect.poll(() => created).toEqual([{ directory: root }]) }) -test("the branch chip holds a placeholder while the checkout loads, then reads No branch without one", async ({ +test("the main checkout trigger holds a placeholder while its branch loads, then reads No branch without one", async ({ page, }) => { const vcs = Promise.withResolvers>>() @@ -156,13 +155,13 @@ test("the branch chip holds a placeholder while the checkout loads, then reads N }) const held = await vcs.promise - const trigger = newSessionBranch(page) + const trigger = newSessionWorktree(page) await held.arrived await expect(trigger).toHaveAttribute("aria-busy", "true") await expect(trigger).toHaveAccessibleName("Choose worktree") held.release() - await expect(trigger).not.toHaveAttribute("aria-busy", "true") + await expect(trigger).toHaveAttribute("aria-busy", "false") await expect(trigger).toHaveText("No branch") await expect(trigger).toHaveAccessibleName("No branch") await trigger.click() @@ -192,7 +191,7 @@ for (const binding of ["custom", "none"]) { await expect(tooltip).toContainText("Choose project") await expect(keys).toHaveText(binding === "custom" ? [/P$/] : []) - await newSessionBranch(page).hover() + await newSessionWorktree(page).hover() await expect(tooltip).toContainText("Isolate sessions with worktrees") await expect(keys).toHaveText(binding === "custom" ? [/X$/] : []) @@ -202,20 +201,20 @@ for (const binding of ["custom", "none"]) { if (binding === "none") { await view.editor.press(`${modifier}+Alt+o`) await expect(page.getByRole("dialog")).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionWorktree(page)).toHaveText("main") return } await view.editor.press(`${modifier}+Alt+k`) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionBaseBranch(page)).toHaveText("from main") await view.editor.press(`${modifier}+Alt+x`) const search = page.getByRole("combobox", { name: "Search worktrees", exact: true }) await expect(search).toBeFocused() await search.press("Escape") await expect(page.getByRole("dialog")).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(view.editor).toBeFocused() await view.editor.press(`${modifier}+Alt+p`) await expect(page.getByRole("combobox", { name: "Search projects", exact: true })).toBeFocused() @@ -225,37 +224,15 @@ for (const binding of ["custom", "none"]) { test("the worktree picker shortcut is disabled for non-Git projects", async ({ page }) => { const view = await openDraft(page, { name: "NoWorktrees", project: { vcs: undefined } }) - const screen = page.locator('[data-component="new-session"]') - const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) - await expect(newSessionBranch(page)).toHaveCount(0) - await expect(screen.getByText("main", { exact: true })).toHaveCount(0) + await expect(newSessionWorktree(page)).toHaveCount(0) await view.editor.press(`${modifier}+Alt+o`) await expect(page.getByRole("dialog")).toHaveCount(0) - await view.editor.press(`${modifier}+Alt+b`) - await expect(page.getByRole("dialog")).toHaveCount(0) await view.editor.fill("Keep working locally") await expect(view.editor).toHaveText("Keep working locally") -}) - -test("a detached HEAD keeps the branch chip and opens the worktree step", async ({ page }) => { - const view = await openDraft(page, { - name: "DetachedHead", - // SAFETY: the mock reads `current` for the chip; an absent branch is how git reports a detached HEAD. - vcs: () => ({ current: undefined as never, default: "main" }), - }) - - const dialog = page.getByRole("dialog") - const search = dialog.getByRole("combobox", { name: "Search worktrees", exact: true }) - - await expect(newSessionBranch(page)).toHaveText("No branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) - await newSessionBranch(page).click() - await expect(search).toBeFocused() - await expect(dialog.getByRole("option", { name: /^from No branch/ })).toBeVisible() - await page.keyboard.press("Escape") - await expect(dialog).toHaveCount(0) + await newSessionLocation(page).click() + await expect(page.getByRole("combobox", { name: "Search projects", exact: true })).toBeFocused() }) test("picker scrollbars overlay full-width rows and support dragging", async ({ page }) => { @@ -271,7 +248,7 @@ test("picker scrollbars overlay full-width rows and support dragging", async ({ })), ], }) - await newSessionBranch(page).click() + await newSessionWorktree(page).click() await expect(page.getByRole("combobox", { name: "Search worktrees", exact: true })).toBeFocused() const menu = page.locator('[data-component="menu-scroll"]') @@ -347,14 +324,14 @@ for (const row of [ }) } -test("the dialog chooses the base branch for a new worktree", async ({ page }) => { +test("a new worktree uses the base branch chosen in the draft", async ({ page }) => { const listed = Promise.withResolvers() + const searches: { directory: string; search?: string; limit?: number }[] = [] const view = await openWorktreeDraft(page, { name: "BranchContext", - project: { name: "Custom project" }, - vcs: () => ({ current: "timeline-quotes", default: "main" }), + vcs: { current: "timeline-quotes", default: "main" }, branches: (input) => { searches.push(input) @@ -362,45 +339,49 @@ test("the dialog chooses the base branch for a new worktree", async ({ page }) = }, }) - const screen = page.locator('[data-component="new-session"]') - const dialog = page.getByRole("dialog") - const search = dialog.getByRole("combobox", { name: "Search branches", exact: true }) - const options = dialog.getByRole("option") + const base = newSessionBaseBranch(page) - await expect(newSessionBranch(page)).toHaveText("timeline-quotes") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) - await expect(screen).not.toContainText("from ") - await expect(screen).not.toContainText("New worktree") - await expect(screen).not.toContainText("Local") + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) - await newSessionBranch(page).click() - const base = dialog.getByRole("option", { name: /^from timeline-quotes/ }) - await expect(base).toBeVisible() - await base.click() + await expect(base).toHaveText("from timeline-quotes") + await expect.poll(() => searches).toEqual([{ directory: view.directory, search: "", limit: 50 }]) + await base.press("Enter") + await expect(base).toHaveAttribute("aria-expanded", "true") + await expect(search).toHaveCount(0) + listed.resolve(["timeline-quotes", "release/base"]) await expect(search).toBeFocused() - listed.resolve(["timeline-quotes", "release/base", "origin/dev"]) - await expect(search).not.toHaveAttribute("aria-busy", "true") + await expect(search).toHaveAttribute("aria-busy", "false") await expect(page.getByRole("option", { name: "release/base", exact: true })).toBeVisible() await search.fill("release") - await expect(search).not.toHaveAttribute("aria-busy", "true") + await expect(search).toHaveAttribute("aria-busy", "false") await expect(page.getByRole("option")).toHaveText(["release/base"]) await page.getByRole("option", { name: "release/base", exact: true }).click() + await expect(base).toHaveText("from release/base") + await expect(view.editor).toBeFocused() + expect(searches).toEqual([ + { directory: view.directory, search: "", limit: 50 }, + { directory: view.directory, search: "release", limit: 50 }, + ]) - // Choosing a base returns to the worktree step with that branch selected. - await expect(dialog.getByRole("option", { name: /^from release\/base/ })).toBeVisible() - await expect(search).toHaveCount(0) - await dialog.getByRole("option", { name: /^New worktree/ }).click() - await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("release/base") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) + await page.setViewportSize({ width: 390, height: 844 }) + await expect(newSessionLocation(page)).toBeInViewport({ ratio: 1 }) + await expect(base).toBeInViewport({ ratio: 1 }) + // Confirming the current destination keeps the chosen base. + await newSessionLocation(page).click() + const projects = page.getByRole("combobox", { name: "Search projects", exact: true }) + await expect(projects).toBeFocused() + await expect(page.getByRole("option", { selected: true })).toContainText("BranchContext") + await projects.press("ArrowRight") + await page.getByRole("option", { name: /^New worktree/, selected: true }).click() + await expect(base).toHaveText("from release/base") + await expect(view.editor).toBeFocused() await view.editor.fill("Use the selected base") await submit(page).click() await expect .poll(() => view.worktreeRequests.map((request) => request.body)) .toEqual([expect.objectContaining({ from: view.directory, branch: "release/base" })]) - expect(searches).toContainEqual({ directory: view.directory, search: "release", limit: 50 }) - view.worktree.resolve({ status: 200, json: { directory: "C:/OpenCode/BranchContext/.worktrees/stellar-orchid" } }) + view.worktree.resolve({ status: 200, json: { directory: `${view.directory}/.worktrees/stellar-orchid` } }) await expect .poll(() => view.prompts) .toEqual([expect.objectContaining({ body: expect.objectContaining({ text: "Use the selected base" }) })]) @@ -411,36 +392,43 @@ test("the checkout branch opens the current project's worktree step", async ({ p const view = await openDraft(page, { name: "BranchWorktrees", + project: { name: "Custom project" }, vcs: (directory) => ({ current: directory === existing ? "quiet-river-branch" : "dev", default: "main" }), worktrees: () => [{ directory: "C:/OpenCode/BranchWorktrees" }, { directory: existing, strategy: "git" }], }) const screen = page.locator('[data-component="new-session"]') - // The checkout branch is the worktree control; once a worktree is chosen its trigger shows the name. - const branch = newSessionBranch(page) + + const local = newSessionWorktree(page) + const dialog = page.getByRole("dialog") + const search = dialog.getByRole("combobox", { name: "Search worktrees", exact: true }) + const options = dialog.getByRole("option") + + const selected = dialog.getByRole("option", { selected: true }) + + const main = /Custom project dev C:\/OpenCode\/BranchWorktrees$/ + + const create = dialog.getByRole("option", { name: /^New worktree/ }) + const back = dialog.getByRole("button", { name: "Back to projects", exact: true }) - await expect(screen.getByText("Local", { exact: true })).toHaveCount(0) - await branch.click() + await expect(local).toHaveText("dev") + await local.click() await expect(search).toBeFocused() await expect(back).toHaveText("Run session in") - await expect(options.locator(".command-palette-title")).toHaveText([ - "BranchWorktrees", - "New worktree", - "from dev", - "quiet-river", - ]) - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.locator(".command-palette-title")).toHaveText(["Custom project", "New worktree", "quiet-river"]) + await search.press("ArrowDown") + await expect(create).toHaveAttribute("data-active") + await expect(selected).toHaveAccessibleName(main) // Stepping back lands on the projects step with the drilled project active, as after drilling in with →. - await search.press("Backspace") + await back.click() const projects = dialog.getByRole("combobox", { name: "Search projects", exact: true }) await expect(projects).toBeFocused() - await expect(back).toHaveCount(0) - await expect(options.filter({ hasText: "BranchWorktrees" })).toHaveAttribute("aria-selected", "true") + await expect(selected).toContainText("Custom project") await projects.press("ArrowRight") await expect(search).toBeFocused() await search.press("Escape") @@ -450,72 +438,213 @@ test("the checkout branch opens the current project's worktree step", async ({ p await expect(view.editor).toBeFocused() // A directly opened worktree picker closes on Escape without showing projects first. - await branch.focus() - await page.keyboard.press("Enter") + await local.press("Enter") await expect(search).toBeFocused() await search.press("Escape") await expect(dialog).toHaveCount(0) await expect(view.editor).toBeFocused() - // Drilling in from the project picker still makes Escape step back. - await newSessionLocation(page).click() - await expect(projects).toBeFocused() - await projects.press("ArrowRight") - await expect(search).toBeFocused() - await search.press("Escape") - await expect(projects).toBeFocused() - await projects.press("Escape") - await expect(dialog).toHaveCount(0) - - await branch.click() + await view.editor.fill("Keep this draft on the main checkout") + await local.click() await options.filter({ hasText: "quiet-river" }).click() await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("quiet-river-branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(existing) + await expect(local).toHaveText("quiet-river-branch") + await expect(screen.getByText("quiet-river", { exact: true })).toHaveCount(0) + await expect(screen.locator('[data-slot="new-session-location-path"]')).toHaveText(existing) + await local.click() + await expect(selected).toHaveAccessibleName(/^quiet-river /) + await search.fill("Custom project") + await expect(options).toHaveCount(1) + await dialog.getByRole("option", { name: main }).click() + await expect(local).toHaveText("dev") + await expect(screen.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) await expect(view.editor).toBeFocused() - - // Reopening from the worktree starts New worktree from the checkout's branch, not the worktree's. - await newSessionBranch(page).click() - await expect(dialog.getByRole("option", { name: /^from dev/ })).toBeVisible() - await page.keyboard.press("Escape") - await expect(dialog).toHaveCount(0) + await expect(view.editor).toHaveText("Keep this draft on the main checkout") }) -test("the branch shortcut opens the base branch step", async ({ page }) => { - const view = await openDraft(page, { +test("the branch shortcut chooses a base branch and stays inactive on the main checkout", async ({ page }) => { + const view = await openWorktreeDraft(page, { name: "BranchShortcut", - vcs: () => ({ current: "dev", default: "dev" }), + vcs: { default: "dev" }, branches: () => ["dev", "release/base"], }) const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) - const dialog = page.getByRole("dialog") + const shortcut = `${modifier}+Alt+KeyB` + + const base = newSessionBaseBranch(page) + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) - await view.editor.press(`${modifier}+Alt+KeyB`) + await expect(base).toHaveAccessibleName("Choose base branch") + await base.hover() + await expect(page.getByRole("tooltip")).toContainText("Choose base branch") + await expect(page.getByRole("tooltip").locator('[data-component="keybind-v2"]')).toContainText("B") + await expect(view.editor).toBeFocused() + await view.editor.press(shortcut) await expect(search).toBeFocused() - await expect(page.getByRole("option")).toHaveText(["dev", "release/base"]) - await search.press("Escape") - await expect(dialog).toHaveCount(0) + await search.fill("release/base") + await expect(page.getByRole("option")).toHaveText(["release/base"]) + await search.press("Enter") + await expect(base).toHaveText("from release/base") await expect(view.editor).toBeFocused() - await view.editor.press(`${modifier}+Alt+KeyB`) - await page.getByRole("option", { name: "release/base", exact: true }).click() - - // Choosing a base returns to the worktree step; selecting New worktree applies it to the row. - await expect(dialog.getByRole("option", { name: /^from release\/base/ })).toBeVisible() - await dialog.getByRole("option", { name: /^New worktree/ }).click() - await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("release/base") - await expect(view.editor).toBeFocused() - - await view.editor.press(`${modifier}+Alt+KeyB`) + await view.editor.press(shortcut) await expect(search).toBeFocused() - await expect(search).toHaveValue("") - await search.press("Escape") - await expect(dialog).toHaveCount(0) + await search.press(shortcut) + await expect(search).toHaveCount(0) await expect(view.editor).toBeFocused() + + await base.click() + await page.getByRole("option", { name: "Use main checkout", exact: true }).click() + await expect(newSessionWorktree(page)).toHaveText("No branch") + await view.editor.press(shortcut) + await expect(search).toHaveCount(0) + await expect(view.editor).toBeFocused() +}) + +test("a pending branch picker can be dismissed before its results arrive", async ({ page }) => { + const listed = Promise.withResolvers() + + const view = await openWorktreeDraft(page, { + name: "BranchDismiss", + branches: () => listed.promise, + }) + + const base = newSessionBaseBranch(page) + + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + await base.click() + await expect(base).toHaveAttribute("aria-expanded", "true") + await expect(search).toHaveCount(0) + await view.editor.click() + await expect(base).toHaveAttribute("aria-expanded", "false") + await base.click() + await base.press("Escape") + await expect(base).toHaveAttribute("aria-expanded", "false") + await base.click() + await base.click() + await expect(base).toHaveAttribute("aria-expanded", "false") + listed.resolve(["main", "origin/dev"]) + await expect(base).toHaveAttribute("aria-busy", "false") + await expect(search).toHaveCount(0) + await base.click() + await expect(search).toBeFocused() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main", "origin/dev"]) +}) + +test("reopening the branch picker shows branches created since it last opened", async ({ page }) => { + let created = false + + await openWorktreeDraft(page, { + name: "BranchRefresh", + branches: () => (created ? ["main", "feature/new"] : ["main"]), + }) + + const base = newSessionBaseBranch(page) + await base.click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main"]) + await base.click() + await expect(page.getByRole("combobox", { name: "Search branches", exact: true })).toHaveCount(0) + created = true + await base.click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main", "feature/new"]) +}) + +test("branch search keeps results on screen while a query is pending", async ({ page }) => { + const held = Promise.withResolvers() + + await openWorktreeDraft(page, { + name: "BranchPending", + branches: (input) => (input.search ? held.promise : ["release/base", "release/next", "timeline-quotes"]), + }) + + await newSessionBaseBranch(page).click() + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + + const options = page.getByRole("option") + await expect(options).toHaveCount(4) + // Record any moment the list renders without rows, however brief. + await page.getByRole("listbox").evaluate((list) => { + const observer = new MutationObserver(() => { + if (!list.querySelector('[role="option"]')) list.setAttribute("data-emptied", "") + }) + + observer.observe(list, { childList: true, subtree: true }) + }) + + const next = page.getByRole("option", { name: "release/next", exact: true }) + await search.press("ArrowDown") + await search.press("ArrowDown") + await expect(next).toHaveAttribute("aria-selected", "true") + await search.pressSequentially("release") + await expect(search).toHaveAttribute("aria-busy", "true") + await expect(options).toHaveText(["release/base", "release/next"]) + await expect(next).toHaveAttribute("aria-selected", "true") + await search.fill("") + await expect(options).toHaveCount(4) + await search.pressSequentially("quotes") + await expect(options).toHaveText(["timeline-quotes"]) + await search.pressSequentially("-missing") + await expect(options).toHaveText(["timeline-quotes"]) + await expect(page.getByRole("listbox")).not.toHaveAttribute("data-emptied") + + held.resolve([]) + await expect(page.getByText("No results found", { exact: true })).toBeVisible() + await expect(search).toHaveAttribute("aria-busy", "false") +}) + +test("the empty branch search state is as tall as a single result", async ({ page }) => { + await openWorktreeDraft(page, { + name: "BranchEmptyHeight", + branches: () => [], + }) + + await newSessionBaseBranch(page).click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/]) + const panel = page.getByRole("dialog") + // Measured on open, before any search animates the panel. + const single = await panel.evaluate((element) => element.getBoundingClientRect().height) + + await page.getByRole("combobox", { name: "Search branches", exact: true }).fill("missing") + await expect(page.getByText("No results found", { exact: true })).toBeVisible() + await expect.poll(() => panel.evaluate((element) => element.getBoundingClientRect().height)).toBe(single) +}) + +test("backspacing keeps confirmed branch results until the broader search answers", async ({ page }) => { + const broader = Promise.withResolvers() + + const closed = ["closed-search-beta", "closed-session-search", "reopen-closed-tab", "recently-closed-projects"] + + await openWorktreeDraft(page, { + name: "BranchBackspace", + branches: (input) => { + if (input.search === "clo") return broader.promise + + if (input.search) return closed + + return [...closed, "origin/cloudflare-run-images", "origin/cloudflare-run-functions"] + }, + }) + + await newSessionBaseBranch(page).click() + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + + const options = page.getByRole("option") + await expect(options).toHaveCount(7) + await search.fill("closed") + await expect(search).toHaveAttribute("aria-busy", "false") + await expect(options).toHaveText(closed) + await search.press("Backspace") + await search.press("Backspace") + await search.press("Backspace") + await expect(search).toHaveValue("clo") + await expect(search).toHaveAttribute("aria-busy", "true") + await expect(options).toHaveText(closed) + broader.resolve([...closed, "clover-fix"]) + await expect(search).toHaveAttribute("aria-busy", "false") + await expect(options).toHaveText([...closed, "clover-fix"]) }) test("the dark new session panel exposes no lighter background at its rounded corners", async ({ page }) => { @@ -827,8 +956,7 @@ for (const row of [ if (row.followUp) return await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(directory) + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(pending.message).toHaveCount(0) await expect(tabLink(page, pending.sessionID)).toHaveCount(0) expect(mock.creates).toEqual([]) @@ -845,7 +973,6 @@ test("retains the draft and reuses the created workspace after session creation await expect(page.getByText("Failed to create session", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(text) await expect(submit(page)).toBeEnabled() - await expect(newSessionBranch(page)).toHaveText("main") await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(workspace) await expect(pending.shimmer).toHaveCount(0) await expect(pending.message).toHaveCount(0) @@ -1020,8 +1147,7 @@ test("restores the draft after closing and revisiting a pending session that fai await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(`${text}\n\n${followUp}`) await expect(submit(page)).toBeEnabled() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(directory) + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(page.locator(`[data-titlebar-tab-link][href="${draftHref(draftID)}"]`)).toHaveCount(1) await expect(tab).toHaveCount(0) await expect(pending.message).toHaveCount(0) @@ -1099,6 +1225,7 @@ test("the location dialog separates added projects from server projects and tags server: apollo, directory: remote.worktree, project: remote, + vcs: { current: "apollo-release", default: "main" }, projects: () => [remote, entry("proj_apollo_sst", "/home/dax/sst", 3)], worktrees: () => [{ directory: remote.worktree }, { directory: "/home/dax/opencode-beta", strategy: "git" }], provider: NO_PROVIDER, @@ -1115,6 +1242,7 @@ test("the location dialog separates added projects from server projects and tags usedProjects: { [apollo]: [remote.id] }, }) const local = entry("proj_opencode", "C:/work/opencode", 2) + await openDraft(page, { name: "opencode", hostname: "hailmary", @@ -1219,12 +1347,11 @@ test("the location dialog separates added projects from server projects and tags await expect(add).toHaveCount(0) await expect(back).toHaveText("Run session in") await expect(options.nth(0).locator('[data-component="tag"]')).toHaveText("apollo") - await expect(options.locator(".command-palette-title")).toHaveText([ - "opencode", - "New worktree", - "from main", - "opencode-beta", - ]) + await expect(dialog.getByRole("option", { selected: true })).toHaveCount(0) + await search.fill("apollo-release") + await expect(options).toHaveText([/opencode.*apollo-release.*\/home\/dax\/opencode/]) + await search.fill("") + await expect(options.locator(".command-palette-title")).toHaveText(["opencode", "New worktree", "opencode-beta"]) await expect(dialog.getByRole("separator")).toHaveCount(1) await search.fill("opencode-beta") await expect(options).toHaveCount(1) @@ -1242,15 +1369,10 @@ test("the location dialog separates added projects from server projects and tags await page.keyboard.press("Escape") await expect(back).toHaveText("Run session in") await expect(search).toHaveValue("open") - await expect(options.locator(".command-palette-title")).toHaveText([ - "opencode", - "New worktree", - "from main", - "opencode-beta", - ]) - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.locator(".command-palette-title")).toHaveText(["opencode", "New worktree", "opencode-beta"]) + await expect(options.nth(0)).toHaveAttribute("data-active") await search.fill("") - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.nth(0)).toHaveAttribute("data-active") await page.keyboard.press("Backspace") await expect(search).toHaveValue("opencode") await expect(rows.nth(0)).toHaveAttribute("aria-selected", "true") diff --git a/packages/app/e2e/utils/workspace.ts b/packages/app/e2e/utils/workspace.ts index 6c3edfb2512..96e738e63c2 100644 --- a/packages/app/e2e/utils/workspace.ts +++ b/packages/app/e2e/utils/workspace.ts @@ -88,19 +88,23 @@ export async function openDraft( return { ...workspace, draftID, editor } } -// Opens a draft on the local project with "New worktree" selected. Worktree creation stays pending until the test -// resolves `worktree`; POST order (`worktree`, `session`, `prompt`), worktree requests, session creates and prompts are -// recorded. The draft tab comes first, then a tab per session. // The new-session trigger that shows the draft's project and opens the location dialog on its projects. export function newSessionLocation(page: Page) { return page.locator('[data-component="new-session"] [data-action="prompt-project"]') } -// The new-session branch chip for the selected branch. It opens the project's worktree step. -export function newSessionBranch(page: Page) { - return page.locator('[data-component="new-session"] [data-action="prompt-branch"]') +// The selected checkout's branch opens the project's worktree step. +export function newSessionWorktree(page: Page) { + return page.locator('[data-component="new-session"] [data-action="prompt-worktree"]') } +export function newSessionBaseBranch(page: Page) { + return page.locator('[data-component="new-session"] button[aria-description="Choose base branch"]') +} + +// Opens a draft on the local project with "New worktree" selected. Worktree creation stays pending until the test +// resolves `worktree`; POST order (`worktree`, `session`, `prompt`), worktree requests, session creates and prompts are +// recorded. The draft tab comes first, then a tab per session. export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { draftID?: string }) { const worktree = Promise.withResolvers<{ status: number; json: unknown }>() const calls: string[] = [] @@ -148,9 +152,10 @@ export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { dr await page.goto(draftHref(draftID)) const editor = page.locator('[data-component="composer-editor"]') await expect(editor).toBeVisible({ timeout: APP_READY_TIMEOUT }) - await newSessionBranch(page).click() + await newSessionWorktree(page).click() await expect(page.getByRole("combobox", { name: "Search worktrees", exact: true })).toBeFocused() await page.getByRole("option", { name: /^New worktree/ }).click() + await expect(newSessionBaseBranch(page)).toBeVisible() await expect(editor).toBeEditable() return { ...workspace, draftID, editor, worktree, calls, worktreeRequests, creates, prompts } diff --git a/packages/app/src/new-session/draft.standalone.stories.tsx b/packages/app/src/new-session/draft.standalone.stories.tsx index 7fbd5abe055..d9c0c885bfc 100644 --- a/packages/app/src/new-session/draft.standalone.stories.tsx +++ b/packages/app/src/new-session/draft.standalone.stories.tsx @@ -17,9 +17,16 @@ import { createPromptProjectController, type PromptProject } from "./project/sel import { NewSessionView } from "./view" import { createNewSessionWorkspaceController } from "./workspace/controller" -const locations = ["main", "existing worktree", "checkout loading", "detached HEAD", "no project"] as const +const worktrees = { + main: "main", + "new worktree": "create", + "existing worktree": STORY_PROJECTS[0].sandboxes[0], + "checkout loading": "main", + "detached HEAD": "main", + "no project": "main", +} -type DraftArgs = { location: (typeof locations)[number]; prompt: string } +type DraftArgs = { location: keyof typeof worktrees; prompt: string } const projects = STORY_PROJECTS.map((project) => ({ ...project, @@ -66,7 +73,7 @@ function DraftLanding(props: DraftArgs & { directory: string; setDirectory: (dir setState({ location: value, available: value === "no project" ? [] : projects, - worktree: value === "existing worktree" ? STORY_PROJECTS[0].sandboxes[0] : "main", + worktree: worktrees[value], branch: undefined, activity: "", }) @@ -184,7 +191,7 @@ export default { id: "app-new-session-draft", parameters: { layout: "fullscreen" }, args: { location: "main", prompt: "" }, - argTypes: { location: { control: "select", options: locations }, prompt: { control: "text" } }, + argTypes: { location: { control: "select", options: Object.keys(worktrees) }, prompt: { control: "text" } }, render: (args: DraftArgs) => ( @@ -198,6 +205,8 @@ export const PreparedPrompt = { args: { prompt: "Review the recent changes to se export const ExistingWorktree = { args: { location: "existing worktree" } } +export const NewWorktree = { args: { location: "new worktree" } } + export const CheckoutLoading = { args: { location: "checkout loading" } } export const DetachedHead = { args: { location: "detached HEAD" } } diff --git a/packages/app/src/new-session/location/dialog.standalone.stories.tsx b/packages/app/src/new-session/location/dialog.standalone.stories.tsx index 07127cdfefc..9c23378c56c 100644 --- a/packages/app/src/new-session/location/dialog.standalone.stories.tsx +++ b/packages/app/src/new-session/location/dialog.standalone.stories.tsx @@ -26,7 +26,7 @@ const sshServer: PromptServer = { label: "SSH", } -type LocationScenario = { multipleServers?: boolean; step?: "branches" | "worktrees" } +type LocationScenario = { multipleServers?: boolean; worktrees?: boolean } function LocationDialogStory(props: LocationScenario) { const [store, setStore] = createStore<{ @@ -91,7 +91,7 @@ function LocationDialogStory(props: LocationScenario) { onDone: () => {}, }) - const open = () => openLocation(props.step ? { step: props.step, project: project.selected() } : undefined) + const open = () => openLocation(props.worktrees ? { project: project.selected() } : undefined) onMount(open) @@ -119,6 +119,4 @@ export const Default = story() export const MultipleServers = story({ multipleServers: true }) -export const Worktrees = story({ step: "worktrees" }) - -export const BaseBranch = story({ step: "branches" }) +export const Worktrees = story({ worktrees: true }) diff --git a/packages/app/src/new-session/location/dialog.tsx b/packages/app/src/new-session/location/dialog.tsx index cc2f2531bbf..c51db90e554 100644 --- a/packages/app/src/new-session/location/dialog.tsx +++ b/packages/app/src/new-session/location/dialog.tsx @@ -15,37 +15,16 @@ import { TextInput } from "@opencode/ui/text-input" import { Tooltip } from "@opencode/ui/tooltip" import { createTypeahead } from "@opencode/ui/typeahead" import { createEventListener } from "@solid-primitives/event-listener" -import { getFilename } from "@opencode/util/path" -import { - createEffect, - createMemo, - createResource, - createSignal, - For, - Match, - onCleanup, - Show, - Switch, - untrack, -} from "solid-js" +import { getFilename, sameDirectory } from "@opencode/util/path" +import { createEffect, createMemo, createResource, createSignal, For, Match, onCleanup, Show, Switch } from "solid-js" import type { PromptProject, PromptProjectController, PromptServer } from "@/new-session/project/selector" import type { NewSessionWorkspaceController } from "@/new-session/workspace/controller" import { useLanguage } from "@/runtime/i18n/language" import { useServerSDK } from "@/runtime/server/client" -import { useData } from "@/runtime/server/current" import { ServerConnection, useServers } from "@/runtime/server/registry" import { useGlobal } from "@/runtime/server/runtime" import { useCommand } from "@/shell/commands/command" import { workspaceSelectionDirectories } from "@/workspaces/paths" -import { - BRANCH_PRELOAD_TIMEOUT_MS, - INITIAL_BRANCH_PICKER_STATE, - selectBranchBusy, - selectBranchInitial, - transitionBranchPicker, - type BranchPickerEffect, - type BranchPickerEvent, -} from "@/new-session/workspace/branch-machine" import "@/shell/commands/dialog.css" import "@/shell/palette-menu.css" import "./dialog.css" @@ -70,20 +49,13 @@ export function useNewSessionLocationDialog(input: { const dialog = useDialog() /** Pass `project` to open straight on that project's worktree step; stepping back still reaches the projects. */ - return (options?: { - project?: PromptProject - step?: "worktrees" | "branches" - base?: string - onWorkspace?: (value: string) => void - }) => { + return (options?: { project?: PromptProject; onWorkspace?: (value: string) => void }) => { void dialog.show( () => ( ), @@ -96,8 +68,6 @@ function NewSessionLocationDialog(props: { project: PromptProjectController workspace: NewSessionWorkspaceController drilled?: PromptProject - step?: "worktrees" | "branches" - base?: string onWorkspace?: (value: string) => void }) { const dialog = useDialog() @@ -106,18 +76,23 @@ function NewSessionLocationDialog(props: { const global = useGlobal() const servers = useServers() const serverSDK = useServerSDK() - const data = useData() - - const [step, setStep] = createSignal( - createLocationDialogState(props.drilled, { - step: props.step === "branches" ? "branches" : undefined, - base: props.base, - }), - ) + const [step, setStep] = createSignal(createLocationDialogState(props.drilled)) const view = createMemo(() => locationDialogView(step())) const drilled = createMemo(() => view().drilled) + const currentDestination = createMemo(() => { + const project = drilled() + + if (project && props.project.isSelected(project)) return props.workspace.selection.value() + }) + + const current = (entry: LocationEntry) => { + const destination = currentDestination() + + return entry.type === "workspace" && destination !== undefined && sameDirectory(entry.value, destination) + } + const connection = (project: PromptProject) => project.server ? servers.list.find((item) => ServerConnection.key(item) === project.server!.key) : serverSDK.server @@ -158,117 +133,18 @@ function NewSessionLocationDialog(props: { return !query || values.some((value) => value?.toLowerCase().includes(query)) } - // Only the current server's checkouts have a synced branch. const checkout = (project: PromptProject) => - tagged(project.server) ? undefined : data.location.vcs.info({ directory: project.worktree })?.branch.current - - const projectBranch = (project: PromptProject) => context(project)?.data.location.vcs.info({ directory: project.worktree })?.branch.current - const baseBranch = (project: PromptProject) => { - const state = step() - - return (state.type === "worktrees" ? state.base : undefined) ?? projectBranch(project) - } - - // Load the drilled project's branch for its base-branch row; the worktree step can show it before a list loads. createEffect(() => { const project = drilled() - const target = project && context(project) - if (!project?.id || !target) return - void target.data.location.vcs.sync({ directory: project.worktree }).catch(() => undefined) + if (project?.vcs === "git") + void context(project) + ?.data.location.vcs.sync({ directory: project.worktree }) + .catch(() => undefined) }) - const [picker, setPicker] = createSignal(INITIAL_BRANCH_PICKER_STATE) - - const requests = new Map }>() - - const dispatchPicker = (event: BranchPickerEvent) => - untrack(() => { - const next = transitionBranchPicker(picker(), event) - setPicker(next.state) - next.effects.forEach(runPicker) - }) - - const runPicker = (effect: BranchPickerEffect) => { - if (effect.type === "focus.composer" || effect.type === "branch.choose") return - - if (effect.type === "branches.abort") { - const request = requests.get(effect.attempt) - requests.delete(effect.attempt) - clearTimeout(request?.timer) - request?.controller.abort() - - return - } - - const state = step() - const target = state.type === "branches" ? context(state.project) : undefined - const directory = state.type === "branches" ? state.project.worktree : undefined - - if (!target || !directory) return - - const attempt = effect.attempt - const controller = new AbortController() - const timer = setTimeout(() => dispatchPicker({ type: "branches.timed-out", attempt }), BRANCH_PRELOAD_TIMEOUT_MS) - requests.set(attempt, { controller, timer }) - target.sdk.api.vcs.branch - .list({ location: { directory }, search: "", limit: 50 }, { signal: controller.signal }) - .then( - (response) => settlePicker(attempt, controller, { type: "branches.loaded", attempt, items: response.data }), - () => settlePicker(attempt, controller, { type: "branches.failed", attempt }), - ) - } - - const settlePicker = (attempt: number, controller: AbortController, event: BranchPickerEvent) => { - if (controller.signal.aborted) return - clearTimeout(requests.get(attempt)?.timer) - requests.delete(attempt) - dispatchPicker(event) - } - - // The branch step is always open; entering it preloads the list and leaving drops any request. - createEffect(() => { - const state = step() - dispatchPicker({ - type: "target.changed", - directory: state.type === "branches" ? state.project.worktree : undefined, - }) - }) - - createEffect(() => { - if (step().type !== "branches") return - dispatchPicker({ type: "open.change", open: true }) - }) - - // A query searches the drilled project on the server; the previous search aborts as soon as it changes. - createEffect(() => { - const state = step() - - if (state.type !== "branches") return - const target = context(state.project) - - if (!target) return - - const controller = new AbortController() - onCleanup(() => controller.abort()) - target.sdk.api.vcs.branch - .list( - { location: { directory: state.project.worktree }, search: state.query, limit: 50 }, - { signal: controller.signal }, - ) - .then( - (response) => { - if (controller.signal.aborted) return - dispatchPicker({ type: "branches.synced", directory: state.project.worktree, items: response.data }) - }, - () => undefined, - ) - }) - - onCleanup(() => dispatchPicker({ type: "disposed" })) - const otherCount = createMemo(() => props.project.projects().filter((project) => !project.used).length) const projectEntries = createMemo(() => { @@ -308,47 +184,30 @@ function NewSessionLocationDialog(props: { if (!project) return [] const directories = workspaceSelectionDirectories(project, listedItems(project)) - return ( - [ - { id: "main", type: "workspace" as const, project, value: "main", directory: project.worktree }, - { id: "create", type: "workspace" as const, project, value: "create", directory: project.worktree }, - ...(project.vcs === "git" ? [{ id: "base", type: "base" as const, project, directory: project.worktree }] : []), - ...directories.map((directory) => ({ - id: `worktree:${directory}`, - type: "workspace" as const, - project, - value: directory, - directory, - })), - ] satisfies LocationEntry[] - ).filter((entry) => - entry.type === "base" - ? matches(baseBranch(project) ?? language.t("session.location.noBranch"), entry.directory) - : matches( - workspaceTitle(project, entry.value), - entry.directory, - entry.value === "main" ? checkout(project) : undefined, - ), + return [ + { id: "main", type: "workspace" as const, project, value: "main", directory: project.worktree }, + { id: "create", type: "workspace" as const, project, value: "create", directory: project.worktree }, + ...directories.map((directory) => ({ + id: `worktree:${directory}`, + type: "workspace" as const, + project, + value: directory, + directory, + })), + ].filter((entry) => + matches( + workspaceTitle(project, entry.value), + entry.directory, + entry.value === "main" ? checkout(project) : undefined, + ), ) }) - const branchEntries = createMemo(() => { - const initial = selectBranchInitial(picker()) - - if (!initial) return [] - - return initial.items - .filter((branch) => matches(branch)) - .map((branch) => ({ id: `branch:${branch}`, type: "branch" as const, branch })) - }) - const entries = () => { const type = step().type if (type === "worktrees") return workspaceEntries() - if (type === "branches") return branchEntries() - if (type === "servers") return serverEntries() return projectEntries() @@ -440,8 +299,6 @@ function NewSessionLocationDialog(props: { if (props.project.isSelected(effect.project)) props.workspace.selection.set(effect.value) if (!props.project.isSelected(effect.project)) props.project.select(effect.project, effect.value) - - if (effect.branch) props.workspace.selection.branch(effect.branch) props.onWorkspace?.(effect.value) } @@ -512,7 +369,6 @@ function NewSessionLocationDialog(props: { } role="combobox" aria-expanded="true" - aria-busy={step().type === "branches" && selectBranchBusy(picker()) ? "true" : undefined} data-owns-escape={view().ownsEscape ? "" : undefined} aria-controls={typeahead.listID} aria-activedescendant={typeahead.activeID()} @@ -544,13 +400,7 @@ function NewSessionLocationDialog(props: { when={entries().length > 0} fallback={ // The worktree list may still be loading; hold the row's height without flashing a label. -
+
{language.t("palette.empty")}
} @@ -570,7 +420,7 @@ function NewSessionLocationDialog(props: { (entry.type === "workspace" && entry.value !== "main" && entry.value !== "create" && - ["main", "create", "base"].includes(entries()[index() - 1]!.id))) + ["main", "create"].includes(entries()[index() - 1]!.id))) } > )} - - {(item) => ( -
- -
- - {language.t("session.new.workspace.fromBranch", { - branch: baseBranch(item().project) ?? language.t("session.location.noBranch"), - })} - - - {language.t("command.session.branch.choose")} - -
- - - -
- )} -
- - {(item) => ( -
- -
- - {item().branch} - -
-
- )} -
{(item) => ( + + + )} diff --git a/packages/app/src/new-session/location/machine.test.ts b/packages/app/src/new-session/location/machine.test.ts index cc9c5b65760..0e4b8bc487b 100644 --- a/packages/app/src/new-session/location/machine.test.ts +++ b/packages/app/src/new-session/location/machine.test.ts @@ -163,53 +163,6 @@ describe("location dialog steps", () => { ).toMatchObject({ effects: [{ type: "project.add" }] }) }) - test("the base-branch row opens the branch list and keeps the chosen branch for New worktree", () => { - const start = createLocationDialogState(opencode) - const base: LocationEntry = { id: "base", type: "base", project: opencode, directory: opencode.worktree } - - const branches = transitionLocationDialog(start, { - type: "chosen", - entry: base, - active: "base", - choosesServer: false, - }) - - expect(branches.state).toMatchObject({ type: "branches", project: opencode, direct: false }) - expect(branches.effects).toEqual([{ type: "focus", active: undefined }]) - - const chosen = transitionLocationDialog(branches.state, { type: "branch.chosen", branch: "release/base" }) - expect(chosen.state).toMatchObject({ type: "worktrees", project: opencode, direct: true, base: "release/base" }) - expect(chosen.effects).toEqual([{ type: "focus", active: "base" }]) - - const created = transitionLocationDialog(chosen.state, { - type: "chosen", - entry: { id: "create", type: "workspace", project: opencode, value: "create", directory: opencode.worktree }, - active: "create", - choosesServer: true, - }) - - expect(created.effects).toEqual([ - { type: "workspace.select", project: opencode, value: "create", branch: "release/base" }, - ]) - }) - - test("a dialog opened on the branch step closes on Escape and returns to the worktree step after a choice", () => { - const direct = createLocationDialogState(opencode, { step: "branches" }) - expect(locationDialogView(direct)).toMatchObject({ - drilled: opencode, - placeholderKey: "session.new.workspace.branch.search.placeholder", - }) - - const escape = transitionLocationDialog(direct, key("Escape")) - expect(escape).toMatchObject({ state: direct, effects: [{ type: "close" }], handled: true, stop: true }) - - const chosen = transitionLocationDialog(direct, { type: "branch.chosen", branch: "release/base" }) - expect(chosen.state).toMatchObject({ type: "worktrees", project: opencode, direct: true, base: "release/base" }) - - const projects = transitionLocationDialog(direct, back) - expect(projects.state).toEqual({ type: "projects", query: "", history: [] }) - }) - test("an unchanged query and a back with nowhere to go keep the state", () => { const state = createLocationDialogState() expect(transitionLocationDialog(state, query("")).state).toBe(state) diff --git a/packages/app/src/new-session/location/machine.ts b/packages/app/src/new-session/location/machine.ts index 12812c6beb9..e1903067537 100644 --- a/packages/app/src/new-session/location/machine.ts +++ b/packages/app/src/new-session/location/machine.ts @@ -12,9 +12,6 @@ export type LocationEntry = readonly value: string readonly directory: string } - /** The base-branch row of the worktree step; choosing it opens the branch list. */ - | { readonly id: string; readonly type: "base"; readonly project: PromptProject; readonly directory: string } - | { readonly id: string; readonly type: "branch"; readonly branch: string } /** A step to return to, with the row that was active on it. */ export type LocationHistoryItem = @@ -26,18 +23,8 @@ export type LocationHistoryItem = readonly direct: boolean readonly query: string readonly active: string | undefined - readonly base: string | undefined - } - | { - readonly type: "branches" - readonly project: PromptProject - readonly direct: boolean - readonly query: string - readonly active: string | undefined } -// One step of the location dialog. `history` holds the steps to step back through, so a step entered from any other -// step returns to it intact. `direct` marks a step the dialog opened on, where Escape closes the dialog. export type LocationDialogState = | { readonly type: "projects"; readonly query: string; readonly history: readonly LocationHistoryItem[] } | { readonly type: "others"; readonly query: string; readonly history: readonly LocationHistoryItem[] } @@ -45,15 +32,7 @@ export type LocationDialogState = | { readonly type: "worktrees" readonly project: PromptProject - readonly direct: boolean - readonly query: string - readonly history: readonly LocationHistoryItem[] - /** A base branch chosen for the new worktree; omitted means the project root's current branch. */ - readonly base: string | undefined - } - | { - readonly type: "branches" - readonly project: PromptProject + /** Escape closes a dialog opened directly on the worktree step. */ readonly direct: boolean readonly query: string readonly history: readonly LocationHistoryItem[] @@ -62,7 +41,6 @@ export type LocationDialogState = export type LocationDialogEvent = | { readonly type: "query.changed"; readonly query: string } | { readonly type: "drilled"; readonly project: PromptProject } - | { readonly type: "branch.chosen"; readonly branch: string } /** `active` is the row active on the current step, restored when the user steps back to it. */ | { readonly type: "chosen" @@ -86,12 +64,7 @@ export type LocationDialogEffect = | { readonly type: "focus"; readonly active: string | undefined } | { readonly type: "project.add"; readonly server?: string } | { readonly type: "project.select"; readonly project: PromptProject } - | { - readonly type: "workspace.select" - readonly project: PromptProject - readonly value: string - readonly branch?: string - } + | { readonly type: "workspace.select"; readonly project: PromptProject; readonly value: string } | { readonly type: "close" } export type LocationDialogTransition = { @@ -102,23 +75,15 @@ export type LocationDialogTransition = { readonly stop: boolean } -export function createLocationDialogState( - drilled?: PromptProject, - options?: { readonly step?: "branches"; readonly base?: string }, -): LocationDialogState { +export function createLocationDialogState(drilled?: PromptProject): LocationDialogState { if (!drilled) return { type: "projects", query: "", history: [] } - const history = [{ type: "projects", query: "", active: projectEntryID(drilled) }] as const - - if (options?.step === "branches") return { type: "branches", project: drilled, direct: true, query: "", history } - return { type: "worktrees", project: drilled, direct: true, query: "", - history, - base: options?.base, + history: [{ type: "projects", query: "", active: projectEntryID(drilled) }], } } @@ -137,12 +102,9 @@ export function transitionLocationDialog( project: event.project, direct: false, query: "", - base: undefined, }) } - if (event.type === "branch.chosen") return chooseBranch(state, event.branch) - if (event.type === "chosen") return choose(state, event) if (event.type === "back") return back(state) @@ -169,79 +131,16 @@ function choose( if (entry.type === "project") return to(state, [{ type: "project.select", project: entry.project }]) - if (entry.type === "base") - return state.type === "worktrees" - ? enter(state, entry.id, { type: "branches", project: entry.project, direct: false, query: "" }) - : same(state) - - if (entry.type === "branch") return chooseBranch(state, entry.branch) - - return to(state, [ - { - type: "workspace.select", - project: entry.project, - value: entry.value, - branch: entry.value === "create" && state.type === "worktrees" ? state.base : undefined, - }, - ]) -} - -function chooseBranch(state: LocationDialogState, branch: string): LocationDialogTransition { - if (state.type !== "branches") return same(state) - - const previous = state.history.at(-1) - - // Choosing a base branch returns to the worktree step it came from, with the branch selected there. - if (previous?.type === "worktrees") - return to( - { - type: "worktrees", - project: previous.project, - direct: previous.direct, - query: previous.query, - history: state.history.slice(0, -1), - base: branch, - }, - [{ type: "focus", active: previous.active }], - ) - - return to( - { - type: "worktrees", - project: state.project, - direct: state.direct, - query: "", - history: state.history, - base: branch, - }, - [{ type: "focus", active: undefined }], - ) + return to(state, [{ type: "workspace.select", project: entry.project, value: entry.value }]) } function back(state: LocationDialogState): LocationDialogTransition { const top = state.history.at(-1) if (!top) return same(state) - const history = state.history.slice(0, -1) - const effects = [{ type: "focus", active: top.active }] as const + const { active, ...previous } = top - if (top.type === "worktrees") - return to( - { - type: "worktrees", - project: top.project, - direct: top.direct, - query: top.query, - history, - base: top.base, - }, - effects, - ) - - if (top.type === "branches") - return to({ type: "branches", project: top.project, direct: top.direct, query: top.query, history }, effects) - - return to({ type: top.type, query: top.query, history }, effects) + return to({ ...previous, history: state.history.slice(0, -1) }, [{ type: "focus", active }]) } function key(state: LocationDialogState, event: Extract) { @@ -258,12 +157,9 @@ function key(state: LocationDialogState, event: Extract, active: string | undefined, next: | { type: "others" | "servers"; query: string } - | { type: "worktrees"; project: PromptProject; direct: boolean; query: string; base: string | undefined } - | { type: "branches"; project: PromptProject; direct: boolean; query: string }, + | { type: "worktrees"; project: PromptProject; direct: boolean; query: string }, ): LocationDialogTransition { - const frame = historyFrame(state, active) + const { history, ...previous } = state - return to({ ...next, history: [...state.history, frame] }, [{ type: "focus", active: undefined }]) -} - -// Leaves the current step for `next`, remembering the current step and its active row to return to. -function historyFrame(state: LocationDialogState, active: string | undefined): LocationHistoryItem { - if (state.type === "worktrees") - return { - type: "worktrees", - project: state.project, - direct: state.direct, - query: state.query, - active, - base: state.base, - } - - if (state.type === "branches") - return { - type: "branches", - project: state.project, - direct: state.direct, - query: state.query, - active, - } - - return { type: state.type === "others" ? "others" : "projects", query: state.query, active } + return to({ ...next, history: [...history, { ...previous, active }] }, [{ type: "focus", active: undefined }]) } function to(state: LocationDialogState, effects: readonly LocationDialogEffect[] = []): LocationDialogTransition { diff --git a/packages/app/src/new-session/view.tsx b/packages/app/src/new-session/view.tsx index 107df2cb240..5ccff1e8ab2 100644 --- a/packages/app/src/new-session/view.tsx +++ b/packages/app/src/new-session/view.tsx @@ -3,7 +3,7 @@ import { Tooltip } from "@opencode/ui/tooltip" import { Icon } from "@opencode/ui/icon" import { Keybind } from "@opencode/ui/keybind" import { useCommand } from "@/shell/commands/command" -import { Show, createComputed, createMemo, createSignal, onCleanup, untrack } from "solid-js" +import { Match, Show, Switch, createComputed, createMemo, createSignal, onCleanup, untrack } from "solid-js" import { createStore } from "solid-js/store" import { createResizeObserver } from "@solid-primitives/resize-observer" import { @@ -39,7 +39,7 @@ import { transitionCheckoutLabel, type CheckoutLabelEvent, } from "./workspace/checkout-machine" -import { NewSessionBranch } from "./workspace/selector" +import { BaseBranchPicker } from "./workspace/selector" import { NewSessionBrickBreaker } from "./brick-breaker" import { NewSessionPinBoard } from "./pin-board" import { NewSessionWordmark } from "./wordmark" @@ -86,19 +86,14 @@ export function NewSessionView(props: { if (next.effects.some((effect) => effect.type === "focus.composer")) props.composer.restoreFocus() }) - const location = (project?: PromptProject, step?: "worktrees" | "branches") => + const location = (project?: PromptProject) => props.location({ project, - step, - // Only a selected base survives into the dialog; otherwise it starts from the drilled project's own branch. - base: project && props.workspace.selection.value() === "create" ? props.workspace.bar.branch() : undefined, onWorkspace: (value) => { if (value !== "main") setOnboarding("used", true) }, }) - const onboardingVisible = () => onboardingReady() && !onboarding.used && props.workspace.bar.visible() - let panel!: HTMLDivElement return ( @@ -130,18 +125,11 @@ export function NewSessionView(props: { {(project) => ( location()} - onOpen={ - project().id && project().vcs === "git" ? () => location(project(), "worktrees") : undefined - } - onBase={ - project().id && project().vcs === "git" ? () => location(project(), "branches") : undefined - } + workspace={props.workspace} + onDone={props.composer.restoreFocus} + onboarding={onboardingReady() && !onboarding.used && props.workspace.bar.visible()} + onProjects={() => location()} + onWorktree={project().id && project().vcs === "git" ? () => location(project()) : undefined} /> )} @@ -290,21 +278,13 @@ function fitPath(value: string, width: number, font: string) { const TRIGGER = "flex h-7 items-center gap-1.5 rounded-sm text-start ps-1.5 pe-2 text-v2-text-text-muted transition-colors hover:bg-v2-overlay-simple-overlay-hover hover:text-v2-text-text-base focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:text-v2-text-text-base focus-visible:outline-none" -/** The composer tray: the project picker, the checkout branch, and the session's directory. */ function NewSessionLocation(props: { project: PromptProject - /** "main", "create", or a worktree directory. */ - workspace: string - root: string - /** Missing while the main checkout's Git info loads. */ - checkout?: { branch?: string } - branch?: string + workspace: NewSessionWorkspaceController + onDone: () => void onboarding: boolean - onClick: () => void - /** Opens the project's worktree step; without it the project has no worktrees to choose. */ - onOpen?: () => void - /** Opens the project's base-branch step; without it the project has no branches to choose. */ - onBase?: () => void + onProjects: () => void + onWorktree?: () => void }) { const language = useLanguage() const command = useCommand() @@ -316,16 +296,8 @@ function NewSessionLocation(props: { title: language.t("session.location.worktree"), category: language.t("command.category.workspace"), keybind: "mod+alt+o", - disabled: !props.onOpen, - onSelect: props.onOpen, - }, - { - id: "session.branch.choose", - title: language.t("command.session.branch.choose"), - category: language.t("command.category.workspace"), - keybind: "mod+alt+b", - disabled: !props.onBase, - onSelect: props.onBase, + disabled: !props.onWorktree, + onSelect: props.onWorktree, }, ]) @@ -355,18 +327,31 @@ function NewSessionLocation(props: { }) }) + const path = () => { + const selection = props.workspace.selection.value() + + if (selection === "create") return + + return selection === "main" ? props.workspace.project.root() : selection + } + createComputed(() => - dispatchCheckout({ type: "checkout.changed", directory: props.root, loaded: props.checkout !== undefined }), + dispatchCheckout({ + type: "checkout.changed", + directory: path() ?? props.workspace.project.root(), + loaded: props.workspace.bar.checkout() !== undefined, + }), ) onCleanup(() => dispatchCheckout({ type: "disposed" })) - // The checkout placeholder only covers a branch that is still loading; a loaded checkout without one says "No branch". - const branchLoading = () => !props.branch && selectCheckoutSkeleton(checkoutLabel()) + const label = () => { + const checkout = props.workspace.bar.checkout() - const path = () => (props.workspace === "main" || props.workspace === "create" ? props.root : props.workspace) + return checkout && (checkout.branch || language.t("session.location.noBranch")) + } - const fitted = createMemo(() => fitPath(path(), layout.width, layout.font)) + const fitted = createMemo(() => fitPath(path() ?? "", layout.width, layout.font)) return (
@@ -391,7 +376,7 @@ function NewSessionLocation(props: { aria-haspopup="dialog" aria-description={language.t("session.new.project.trigger.tooltip")} class={`${TRIGGER} min-w-0`} - onClick={props.onClick} + onClick={props.onProjects} > {displayName(props.project)} + - - {(onOpen) => ( - + + {(onWorktree) => ( + } + > + + +
+ + {language.t("workspace.onboarding.title")} +
+ + {language.t("workspace.onboarding.description")} + +
+ + {language.t("session.location.worktree")} + + + + +
+ } + contentClass={props.onboarding ? "max-w-[280px]" : undefined} + class="flex min-w-0 max-w-[220px]" + > + + + )}
diff --git a/packages/app/src/new-session/workspace/branch-machine.test.ts b/packages/app/src/new-session/workspace/branch-machine.test.ts index 882b89e6381..180d3dc87d9 100644 --- a/packages/app/src/new-session/workspace/branch-machine.test.ts +++ b/packages/app/src/new-session/workspace/branch-machine.test.ts @@ -210,6 +210,16 @@ describe("branch picker", () => { expect(selectBranchPopoverOpen(outside.state)).toBe(false) }) + test("selecting the main checkout closes the picker and ignores a repeated selection", () => { + const opened = replay([target("/repo"), loaded(1), open]) + const select = { type: "checkout.selected" } as const + + const chosen = transitionBranchPicker(opened.state, select) + expect(chosen.effects).toEqual([{ type: "checkout.use" }, focus]) + expect(selectBranchPopoverOpen(chosen.state)).toBe(false) + expect(transitionBranchPicker(chosen.state, select).effects).toEqual([]) + }) + test("leaving worktree creation drops the request and stays inactive", () => { const pending = replay([target("/repo-a"), open]) const inactive = transitionBranchPicker(pending.state, target(undefined)) diff --git a/packages/app/src/new-session/workspace/branch-machine.ts b/packages/app/src/new-session/workspace/branch-machine.ts index b67cf4e1a08..b7d7d05a732 100644 --- a/packages/app/src/new-session/workspace/branch-machine.ts +++ b/packages/app/src/new-session/workspace/branch-machine.ts @@ -33,6 +33,7 @@ export type BranchPickerEvent = /** A pointer, focus, blur or Escape outside the trigger while the popover waits for branches. */ | { readonly type: "pending.dismiss" } | { readonly type: "interact.outside" } + | { readonly type: "checkout.selected" } | { readonly type: "branch.selected"; readonly branch: string } | { readonly type: "branches.loaded"; readonly attempt: number; readonly items: string[] } | { readonly type: "branches.failed"; readonly attempt: number } @@ -45,6 +46,7 @@ export type BranchPickerEffect = | { readonly type: "branches.fetch"; readonly attempt: number; readonly directory: string } | { readonly type: "branches.abort"; readonly attempt: number } | { readonly type: "branch.choose"; readonly branch: string } + | { readonly type: "checkout.use" } | { readonly type: "focus.composer" } export type BranchPickerTransition = { @@ -103,10 +105,13 @@ export function transitionBranchPicker(state: BranchPickerState, event: BranchPi if (event.type === "interact.outside") return state.popover === "open" ? { state: { ...state, popover: "outside" }, effects: NONE } : unchanged(state) - if (event.type === "branch.selected") { + if (event.type === "branch.selected" || event.type === "checkout.selected") { if (state.popover === "closed") return unchanged(state) - return closed(state, [{ type: "branch.choose", branch: event.branch }, FOCUS]) + return closed(state, [ + event.type === "checkout.selected" ? { type: "checkout.use" } : { type: "branch.choose", branch: event.branch }, + FOCUS, + ]) } if (event.directory !== state.directory) return unchanged(state) diff --git a/packages/app/src/new-session/workspace/controller.ts b/packages/app/src/new-session/workspace/controller.ts index 395a20dfd42..5f1438db972 100644 --- a/packages/app/src/new-session/workspace/controller.ts +++ b/packages/app/src/new-session/workspace/controller.ts @@ -24,6 +24,10 @@ export function resolveNewSessionWorktree(input: { enabled: boolean; selected?: return input.fallback ?? "main" } +function checkoutDirectory(worktree: string, root: string) { + return worktree === "main" || worktree === "create" ? root : worktree +} + export function resolveNewSessionBranch(input: { worktree: string root: string @@ -31,9 +35,8 @@ export function resolveNewSessionBranch(input: { worktreeBranch: (worktree: string) => string | undefined }) { if (input.worktree === "create" && input.createBranch) return input.createBranch - const directory = input.worktree === "main" || input.worktree === "create" ? input.root : input.worktree - return input.worktreeBranch(directory) + return input.worktreeBranch(checkoutDirectory(input.worktree, input.root)) } export function resolveNewSessionGit(input: { projectVcs?: string; branch?: string }) { @@ -208,9 +211,9 @@ export function createNewSessionWorkspaceController(input: { }), ) - // Missing until the main checkout's Git info loads; a detached HEAD loads without a branch. + // A missing checkout is loading; a loaded checkout may have a detached HEAD. const checkout = createMemo(() => { - const info = data.location.vcs.info({ directory: projectRoot() }) + const info = data.location.vcs.info({ directory: checkoutDirectory(value(), projectRoot()) }) return info ? { branch: info.branch.current } : undefined }) @@ -225,7 +228,7 @@ export function createNewSessionWorkspaceController(input: { } const select = (worktree: string) => { - input.setSelectedBranch(undefined) + if (worktree !== "create" || value() !== "create") input.setSelectedBranch(undefined) input.setSelectedWorktree(worktree) remember(worktree) } diff --git a/packages/app/src/new-session/workspace/selector.tsx b/packages/app/src/new-session/workspace/selector.tsx index 0820e41e8c8..c675d10d585 100644 --- a/packages/app/src/new-session/workspace/selector.tsx +++ b/packages/app/src/new-session/workspace/selector.tsx @@ -1,70 +1,222 @@ -import { Show } from "solid-js" +import { createComputed, createEffect, createSignal, onCleanup, Show, untrack } from "solid-js" +import { createStore } from "solid-js/store" +import { Popover } from "@kobalte/core/popover" +import { makeEventListener } from "@solid-primitives/event-listener" +import { createResizeObserver } from "@solid-primitives/resize-observer" import { Icon } from "@opencode/ui/icon" import { Keybind } from "@opencode/ui/keybind" import { Tooltip } from "@opencode/ui/tooltip" +import { Typeahead } from "@opencode/ui/typeahead" import { useLanguage } from "@/runtime/i18n/language" import { useCommand } from "@/shell/commands/command" +import { + BRANCH_PRELOAD_TIMEOUT_MS, + INITIAL_BRANCH_PICKER_STATE, + selectBranchBusy, + selectBranchInitial, + selectBranchPending, + selectBranchPopoverOpen, + transitionBranchPicker, + type BranchPickerEffect, + type BranchPickerEvent, +} from "./branch-machine" +import type { NewSessionWorkspaceController } from "./controller" -/** The branch of the checkout the session will use. It is the row's one control: it opens the location dialog. */ -export function NewSessionBranch(props: { - branch?: string - /** The branch is still loading; show the checkout placeholder instead of "No branch". */ - loading: boolean - onboarding: boolean - onOpen: () => void -}) { +const MAIN_CHECKOUT = Symbol("main checkout") + +export function BaseBranchPicker(props: { workspace: NewSessionWorkspaceController; onDone: () => void }) { const language = useLanguage() + const command = useCommand() + const [layout, setLayout] = createStore({ truncated: false }) + + const [picker, setPicker] = createSignal(INITIAL_BRANCH_PICKER_STATE) + + const requests = new Map }>() + + let trigger: HTMLButtonElement | undefined + + const dispatch = (event: BranchPickerEvent) => + untrack(() => { + const next = transitionBranchPicker(picker(), event) + setPicker(next.state) + next.effects.forEach(run) + }) + + const run = (effect: BranchPickerEffect) => { + if (effect.type === "focus.composer") return props.onDone() + + if (effect.type === "branch.choose") return props.workspace.selection.branch(effect.branch) + + if (effect.type === "checkout.use") return props.workspace.selection.set("main") + + if (effect.type === "branches.abort") { + const request = requests.get(effect.attempt) + requests.delete(effect.attempt) + clearTimeout(request?.timer) + request?.controller.abort() + + return + } + + const attempt = effect.attempt + const controller = new AbortController() + const timer = setTimeout(() => dispatch({ type: "branches.timed-out", attempt }), BRANCH_PRELOAD_TIMEOUT_MS) + + const settle = (event: BranchPickerEvent) => { + clearTimeout(timer) + requests.delete(attempt) + dispatch(event) + } + + requests.set(attempt, { controller, timer }) + props.workspace.branches("", controller.signal).then( + (items) => settle({ type: "branches.loaded", attempt, items }), + () => settle({ type: "branches.failed", attempt }), + ) + } + + createComputed(() => dispatch({ type: "target.changed", directory: props.workspace.project.root() })) + + onCleanup(() => dispatch({ type: "disposed" })) + + command.register("new-session-branch", () => [ + { + id: "session.branch.choose", + title: language.t("command.session.branch.choose"), + category: language.t("command.category.workspace"), + keybind: "mod+alt+b", + onSelect: (source) => dispatch({ type: "command.select", source }), + }, + ]) + + // Until content mounts, Kobalte has no dismissable layer to cancel a pending open. + createEffect(() => { + if (!selectBranchPending(picker())) return + + const close = (event: Event) => { + if (event.target instanceof Node && trigger?.contains(event.target)) return + dispatch({ type: "pending.dismiss" }) + } + + makeEventListener(document, "pointerdown", close, { capture: true }) + makeEventListener(document, "focusin", close) + makeEventListener(window, "blur", close) + makeEventListener( + window, + "keydown", + (event) => { + if (event.key === "Escape") dispatch({ type: "pending.dismiss" }) + }, + { capture: true }, + ) + }) + + const label = () => { + const branch = props.workspace.bar.branch() + + return branch + ? language.t("session.new.workspace.fromBranch", { branch }) + : language.t("command.session.branch.choose") + } + + const observe = (element: HTMLSpanElement) => + createResizeObserver(element, () => setLayout("truncated", element.scrollWidth > element.clientWidth)) + return ( - -
- - {language.t("workspace.onboarding.title")} -
- {language.t("workspace.onboarding.description")} -
- - {language.t("session.location.worktree")} - - +
+ + {language.t("command.session.branch.choose")} + + + {label()}
} - contentClass={props.onboarding ? "max-w-[280px]" : undefined} class="flex min-w-0 max-w-[220px]" + contentClass="max-w-[calc(100vw-32px)] break-all" > - + + + + + {(initial) => ( + { + if (!event.defaultPrevented) dispatch({ type: "interact.outside" }) + }} + // The machine returns focus to the composer, unless the user moved it outside. + onCloseAutoFocus={(event) => event.preventDefault()} + > + + initial={initial()} + emptyQueryItem={MAIN_CHECKOUT} + placeholder={language.t("session.new.workspace.branch.search.placeholder")} + emptyLabel={language.t("palette.empty")} + retryLabel={language.t("common.retry")} + source={async (query, signal) => { + const directory = props.workspace.project.root() + const items = await props.workspace.branches(query, signal) + + if (!query) dispatch({ type: "branches.synced", directory, items }) + + return items + }} + match={(item, query) => item !== MAIN_CHECKOUT && item.toLowerCase().includes(query.toLowerCase())} + delay={100} + key={(item) => (item === MAIN_CHECKOUT ? "checkout" : `branch:${item}`)} + selected={`branch:${props.workspace.bar.branch() ?? ""}`} + onSelect={(item) => + dispatch( + item === MAIN_CHECKOUT + ? { type: "checkout.selected" } + : { type: "branch.selected", branch: item }, + ) + } + > + {(item) => + item === MAIN_CHECKOUT ? ( + <> + {language.t("session.new.workspace.useMainCheckout")} + + {props.workspace.bar.checkout()?.branch} + + + ) : ( + + {item} + + ) + } + + + )} + + +
) } diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 4f663af872d..ebd463acf27 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -733,6 +733,7 @@ export const dict = { "session.new.workspace.local": "Local repository", "session.new.workspace.existingLabel": "Worktree", "session.new.workspace.fromBranch": "from {{branch}}", + "session.new.workspace.useMainCheckout": "Use main checkout", "session.new.workspace.branch.search.placeholder": "Search branches", "session.new.git.none": "No Git", diff --git a/packages/ui/src/forms/typeahead/typeahead.tsx b/packages/ui/src/forms/typeahead/typeahead.tsx index 87071879c2e..9382b774452 100644 --- a/packages/ui/src/forms/typeahead/typeahead.tsx +++ b/packages/ui/src/forms/typeahead/typeahead.tsx @@ -1,5 +1,5 @@ import { createResizeObserver } from "@solid-primitives/resize-observer" -import { createEffect, createSignal, For, type JSX, on, onCleanup, Show, untrack } from "solid-js" +import { createEffect, createMemo, createSignal, For, type JSX, on, onCleanup, Show, untrack } from "solid-js" import { Icon } from "@opencode/ui/icon" import { abort } from "@opencode/util/abort" import { useI18n } from "../../context/i18n" @@ -28,6 +28,8 @@ export function Typeahead(props: { source: (query: string, signal: AbortSignal) => Promise /** Preloaded opening results, including a failed request that the user can retry. */ initial?: { items: T[]; failed?: boolean } + /** A local option placed before the remote results while the search is empty. */ + emptyQueryItem?: T /** Narrows earlier results while the request for the current query is pending. */ match: (item: T, query: string) => boolean key: (item: T) => string @@ -99,7 +101,14 @@ export function Typeahead(props: { const changeInput = (value: string) => dispatch({ type: "input.changed", input: value, delayMs: props.delay, match: props.match }) - const items = () => selectTypeaheadItems(machine()) + const items = createMemo(() => { + const results = selectTypeaheadItems(machine()) + + return props.emptyQueryItem !== undefined && !selectTypeaheadInput(machine()).trim() + ? [props.emptyQueryItem, ...results] + : results + }) + const stale = () => selectTypeaheadStale(machine()) const pending = () => selectTypeaheadPending(machine()) const animateHeight = () => selectTypeaheadAnimateHeight(machine()) @@ -206,7 +215,7 @@ export function Typeahead(props: { {/* Stays mounted while a retry or a newer query is pending, so the list never collapses to nothing. */} - +
Date: Mon, 16 Nov 2026 09:21:33 -0500 Subject: [PATCH 3/4] test(app): use the locale's labels in the background activity alignment e2e (#64221) Co-authored-by: opencodejr[bot] <348916617+opencodejr[bot]@users.noreply.github.com> Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com> --- packages/app/e2e/regression/settings.spec.ts | 28 ++++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 455f6750791..dd32980d220 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -6,6 +6,8 @@ import { mockRemoteServer, mockWorkspace, openSession, openSettings, type Worksp import { CONSOLE_URL, consoleGateway, consoleSignIn } from "../utils/console" import { recordNotifications } from "../utils/notifications" import { installSseTransport } from "../utils/sse-transport" +import { dict as ar } from "../../src/runtime/i18n/ar" +import { dict as en } from "../../src/runtime/i18n/en" const directory = "C:/Projects/settings-demo" @@ -274,8 +276,20 @@ test("request events use real Questions settings without disabling Permissions a .toEqual([...previews, expect.stringContaining("alert-01"), expect.stringContaining("alert-01")]) }) -for (const locale of ["en", "ar"]) { +for (const [locale, dict] of [ + ["en", en], + ["ar", ar], +] as const) { test(`background activity alignment stays physical and persists (${locale})`, async ({ page }) => { + const label = dict["settings.timeline.row.backgroundActivity.title"] + + const names = { + Hidden: dict["settings.timeline.row.backgroundActivity.off"], + Left: dict["settings.timeline.row.backgroundActivity.left"], + Center: dict["settings.timeline.row.backgroundActivity.center"], + Right: dict["settings.timeline.row.backgroundActivity.right"], + } + const id = "ses_activity_settings" const childID = "ses_activity_settings_child" const stopped: string[] = [] @@ -352,13 +366,13 @@ for (const locale of ["en", "ar"]) { for (const value of ["Center", "Right", "Hidden", "Left", "Right"] as const) { await page.keyboard.press("Control+,") const settings = page.getByTestId("settings-screen") - const control = settings.getByLabel("Background activity", { exact: true }) + const control = settings.getByLabel(label, { exact: true }) await expect(control).toBeVisible() await control.click() const options = page.getByRole("listbox") - await expect(options.getByRole("option")).toHaveText(["Hidden", "Left", "Center", "Right"]) - await options.getByRole("option", { name: value, exact: true }).click() - await expect(control).toHaveText(value) + await expect(options.getByRole("option")).toHaveText([names.Hidden, names.Left, names.Center, names.Right]) + await options.getByRole("option", { name: names[value], exact: true }).click() + await expect(control).toHaveText(names[value]) await page.goBack() if (value === "Hidden") { @@ -413,9 +427,7 @@ for (const locale of ["en", "ar"]) { .toBe("right") await page.keyboard.press("Control+,") await page.reload() - await expect(page.getByTestId("settings-screen").getByLabel("Background activity", { exact: true })).toHaveText( - "Right", - ) + await expect(page.getByTestId("settings-screen").getByLabel(label, { exact: true })).toHaveText(names.Right) }) } From e4606463e7d18fd126ecfac3ec04602f1e44814b Mon Sep 17 00:00:00 2001 From: Aarav Sareen <96787824+arvsrn@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:01:05 +0530 Subject: [PATCH 4/4] fix(app): show every provider as a card in Manage models (#64235) --- packages/app/src/providers/models/manage.css | 32 +++------- packages/app/src/providers/models/manage.tsx | 14 +---- .../src/providers/models/provider-group.tsx | 60 +++++++++++++++---- .../src/providers/models/select-dialog.css | 2 +- packages/app/src/settings/settings.css | 31 +++++++++- 5 files changed, 86 insertions(+), 53 deletions(-) diff --git a/packages/app/src/providers/models/manage.css b/packages/app/src/providers/models/manage.css index 3e2f97e3896..d9bc9b4f304 100644 --- a/packages/app/src/providers/models/manage.css +++ b/packages/app/src/providers/models/manage.css @@ -5,27 +5,28 @@ .settings-manage-models-dialog .settings-panel.settings-models { height: 100%; - gap: 0; + gap: 8px; padding: 0 8px 8px; } .settings-manage-models-dialog .settings-models .settings-section { - gap: 4px; - padding-block: 8px; + gap: 8px; + padding-block: 0 8px; } .settings-manage-models-dialog .settings-models .settings-section[data-expanded] { padding-bottom: 8px; } -.settings-manage-models-dialog .settings-models .settings-section + .settings-section { - border-top: 0.5px solid var(--v2-border-border-base); -} - .settings-manage-models-dialog .provider-model-groups { gap: 8px; } +.settings-manage-models-dialog .provider-model-group { + flex-shrink: 0; + margin: 0; +} + .settings-manage-models-dialog .provider-model-group-header { padding: 4px; border-radius: 0; @@ -76,33 +77,16 @@ .manage-models-rows { display: flex; flex-direction: column; - gap: 1px; } .manage-models-rows .search-list-row { - position: relative; height: 36px; padding-inline: 8px; border-radius: 6px; } -.manage-models-rows .search-list-row:not(:last-child)::after { - content: ""; - position: absolute; - inset-inline: 8px; - bottom: -0.75px; - height: 0.5px; - background: var(--v2-border-border-base); - pointer-events: none; -} - @media (hover: hover) { .manage-models-rows .search-list-row:hover { background: var(--v2-overlay-simple-overlay-hover); } - - .manage-models-rows .search-list-row:hover::after, - .manage-models-rows .search-list-row:has(+ .search-list-row:hover)::after { - opacity: 0; - } } diff --git a/packages/app/src/providers/models/manage.tsx b/packages/app/src/providers/models/manage.tsx index 90d3c4833d0..e6df6d9004d 100644 --- a/packages/app/src/providers/models/manage.tsx +++ b/packages/app/src/providers/models/manage.tsx @@ -32,9 +32,6 @@ export const DialogManageModels: Component = () => { const providerList = (providerID: string) => local.model.list().filter((x) => x.provider.id === providerID) - const providerVisible = (providerID: string) => - providerList(providerID).every((x) => local.model.visible({ modelID: x.id, providerID: x.provider.id })) - const setProviderVisibility = (providerID: string, checked: boolean) => { providerList(providerID).forEach((x) => { local.model.setVisibility({ modelID: x.id, providerID: x.provider.id }, checked) @@ -160,16 +157,7 @@ export const DialogManageModels: Component = () => { disabled={searching()} onExpandedChange={(key, value) => setStore("collapsed", key, !value)} onSetVisibility={setProviderVisibility} - action={(group) => ( - setProviderVisibility(group.category, checked)} - hideLabel - > - {group.items[0].provider.name} - - )} + cards rows={(items) => } /> diff --git a/packages/app/src/providers/models/provider-group.tsx b/packages/app/src/providers/models/provider-group.tsx index 3429e0bf7d2..de48556c733 100644 --- a/packages/app/src/providers/models/provider-group.tsx +++ b/packages/app/src/providers/models/provider-group.tsx @@ -25,6 +25,7 @@ function CustomManagedProviderIcon(props: { class?: string }) { } export function ProviderModelIcon(props: { provider: ModelProvider; class?: string }) { + // SAFETY: the cast only lets `includes` look up any string; the type guard narrows on the result. const icon = () => [ props.provider.canonical, @@ -62,6 +63,8 @@ export function ProviderModelSections(props: { rows: (items: T[]) => JSX.Element /** Trailing control in a direct provider's header. */ action?: (group: ModelGroup) => JSX.Element + /** Shows direct providers as cards like the Console's providers, instead of section headers. */ + cards?: boolean onSetVisibility?: (providerID: string, visible: boolean) => void ref?: (providerID: string, element: HTMLElement) => void }) { @@ -127,20 +130,41 @@ export function ProviderModelSections(props: { fallback={ {(group) => ( -
props.ref?.(group().category, element)} - class="settings-section" - data-component="settings-models-provider" - data-expanded={props.expanded(group().category) ? "" : undefined} + props.ref?.(group().category, element)} + class="settings-section" + data-component="settings-models-provider" + data-expanded={props.expanded(group().category) ? "" : undefined} + > +
} + title={name(group())} + action={props.action?.(group())} + /> + {props.rows(group().items)} +
+ } > -
} - title={name(group())} - action={props.action?.(group())} - /> - {props.rows(group().items)} - + props.ref?.(group().category, element)} + provider={group().items[0].provider} + name={name(group())} + expanded={props.expanded(group().category)} + disabled={props.disabled} + onSetVisibility={ + props.onSetVisibility + ? (visible) => props.onSetVisibility?.(group().category, visible) + : undefined + } + onExpandedChange={(value) => props.onExpandedChange(group().category, value)} + > + {props.rows(group().items)} + + )} } @@ -159,6 +183,16 @@ export function ProviderModelSections(props: { />
+ {/* The header button already collapses the Console for the keyboard and screen readers. */} +