diff --git a/packages/app/e2e/regression/session-summary.spec.ts b/packages/app/e2e/regression/session-summary.spec.ts
index 55a909baf42..b9b25f978b4 100644
--- a/packages/app/e2e/regression/session-summary.spec.ts
+++ b/packages/app/e2e/regression/session-summary.spec.ts
@@ -261,6 +261,115 @@ test("the details follow the routed session when it moves to another worktree",
await expect(location("feature")).toHaveCount(0)
})
+test("a new worktree that does not receive the session offers Retry and Delete worktree after the menu closes", async ({
+ page,
+}) => {
+ const created = "C:/OpenCode/worktrees/quiet-river"
+ const creates: unknown[] = []
+ const removes: unknown[] = []
+ const moves: unknown[] = []
+ const answers = ["fail", "ok", "fail"]
+
+ const view = await openSession(page, {
+ name: "WorktreeRecovery",
+ onWorktreeCreate: (input) => {
+ creates.push(input)
+
+ return { status: 200, body: { directory: created } }
+ },
+ onWorktreeRemove: (input) => void removes.push(input),
+ })
+
+ await page.route(`**/api/session/${view.session.id}/move`, (route) => {
+ if (route.request().method() !== "POST") return route.fallback()
+ moves.push(route.request().postDataJSON())
+
+ if (answers.shift() === "fail")
+ return route.fulfill({ status: 400, headers: cors, json: { message: "Session is locked" } })
+
+ return route.fulfill({ status: 204, headers: cors })
+ })
+ const dialog = page.getByRole("dialog", { name: "Session not moved", exact: true })
+ const retry = dialog.getByRole("button", { name: "Retry", exact: true })
+
+ // The location menu closes as the item is picked; the move and its recovery outlive it.
+ await moveToNewWorktree(page)
+ await expect(dialog).toContainText("The new worktree quiet-river is ready")
+ await expect(page.locator('[data-slot="session-location-card"]')).toBeHidden()
+ await expect(retry).toBeFocused()
+ expect(moves).toEqual([{ directory: created }])
+ await page.screenshot({ path: test.info().outputPath("worktree-recovery.png"), animations: "disabled" })
+
+ // Retry moves into the worktree already created, without creating another.
+ await retry.click()
+ await expect(dialog).toBeHidden()
+ expect(moves).toEqual([{ directory: created }, { directory: created }])
+ expect(creates).toHaveLength(1)
+
+ await moveToNewWorktree(page)
+ await expect(dialog).toBeVisible()
+ await dialog.getByRole("button", { name: "Delete worktree", exact: true }).click()
+ await expect(dialog).toBeHidden()
+ expect(creates).toHaveLength(2)
+ expect(removes).toEqual([expect.objectContaining({ directory: created, force: true })])
+})
+
+test("a session that starts running while its new worktree is created stays put until Retry", async ({ page }) => {
+ const created = "C:/OpenCode/worktrees/calm-lake"
+ const moves: unknown[] = []
+
+ const view = await openSession(page, {
+ name: "WorktreeRunning",
+ onWorktreeCreate: () => ({ status: 200, body: { directory: created } }),
+ })
+
+ await page.route(`**/api/session/${view.session.id}/move`, (route) => {
+ if (route.request().method() !== "POST") return route.fallback()
+ moves.push(route.request().postDataJSON())
+
+ return route.fulfill({ status: 204, headers: cors })
+ })
+ const create = await holdRoute(page, /\/api\/worktree(?:\?|$)/, { method: "POST" })
+ const dialog = page.getByRole("dialog", { name: "Session not moved", exact: true })
+ const retry = dialog.getByRole("button", { name: "Retry", exact: true })
+ const composer = page.locator('[data-component="session-composer-dock"]')
+
+ await moveToNewWorktree(page)
+ await create.arrived
+ await view.push([
+ {
+ id: "evt_worktree_running",
+ created: 1700000002000,
+ type: "session.execution.started",
+ durable: { aggregateID: view.session.id, seq: 1, version: 1 },
+ data: { sessionID: view.session.id },
+ },
+ ])
+ await expect(composer.getByRole("button", { name: "Stop", exact: true })).toBeEnabled()
+ create.release()
+
+ // The run keeps its checkout: nothing moves, and Retry waits for the run to end.
+ await expect(dialog).toContainText("The session is running. Try again once it finishes.")
+ await expect(retry).toBeDisabled()
+ await expect(dialog.getByRole("button", { name: "Keep worktree", exact: true })).toBeFocused()
+ expect(moves).toEqual([])
+ await page.screenshot({ path: test.info().outputPath("worktree-running.png"), animations: "disabled" })
+
+ await view.push([
+ {
+ id: "evt_worktree_idle",
+ created: 1700000003000,
+ type: "session.execution.succeeded",
+ durable: { aggregateID: view.session.id, seq: 2, version: 1 },
+ data: { sessionID: view.session.id },
+ },
+ ])
+ await expect(retry).toBeEnabled()
+ await retry.click()
+ await expect(dialog).toBeHidden()
+ expect(moves).toEqual([{ directory: created }])
+})
+
for (const direction of ["ltr", "rtl"] as const) {
test(`summary overlays the view and submenus follow ${direction}`, async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
@@ -867,6 +976,21 @@ test("long MCP lists stay in the viewport in a real RTL locale", async ({ page }
await expect(menu).toBeHidden()
})
+// Picks New worktree from the location menu of a session in its project's root checkout.
+async function moveToNewWorktree(page: Page) {
+ const location = page.locator('[data-slot="session-location-card"]').getByRole("menuitem", {
+ name: "Local repository",
+ exact: true,
+ })
+
+ await page.locator('[data-slot="session-location-trigger"]').click()
+ await location.click()
+ await page
+ .getByRole("menu", { name: "Local repository", exact: true })
+ .getByRole("menuitem", { name: "New worktree", exact: true })
+ .click()
+}
+
// Moves the pointer straight across from a submenu's trigger into the open submenu, so it never crosses sibling items.
async function enter(page: Page, trigger: Locator, menu: Locator) {
await expect(menu).toBeVisible()
diff --git a/packages/gui-plugins/src/details/i18n/en.ts b/packages/gui-plugins/src/details/i18n/en.ts
index 9b2969a4746..e69e53dc20b 100644
--- a/packages/gui-plugins/src/details/i18n/en.ts
+++ b/packages/gui-plugins/src/details/i18n/en.ts
@@ -6,6 +6,12 @@ export default {
"move.title": "Move to worktree",
"move.menu": "Move session to",
"move.failed": "Failed to move session",
+ "move.running": "The session is running. Try again once it finishes.",
+ "move.removeFailed": "Failed to delete worktree",
+ "move.recovery.title": "Session not moved",
+ "move.recovery.description": "The new worktree {{name}} is ready, but the session is still in its current location.",
+ "move.recovery.keep": "Keep worktree",
+ "move.recovery.remove": "Delete worktree",
server: "Extensions",
mcp: "MCP",
"mcp.empty": "No MCP servers configured",
diff --git a/packages/gui-plugins/src/details/location-workspace.tsx b/packages/gui-plugins/src/details/location-workspace.tsx
index 7f079197e02..29df5ae64ad 100644
--- a/packages/gui-plugins/src/details/location-workspace.tsx
+++ b/packages/gui-plugins/src/details/location-workspace.tsx
@@ -2,9 +2,11 @@ import { Icon } from "@opencode/ui/icon"
import { Menu } from "@opencode/ui/menu"
import { Show } from "solid-js"
import type { BuiltinSlotMap } from "@opencode/plugin/gui/builtin"
-import { SessionWorkspaceMenu } from "./workspace-menu"
+import { SessionWorkspaceMenu, type WorkspaceMoveControllers } from "./workspace-menu"
-export default function SessionLocationWorkspace(props: BuiltinSlotMap["session.location.workspace"]) {
+export default function SessionLocationWorkspace(
+ props: BuiltinSlotMap["session.location.workspace"] & { moves: WorkspaceMoveControllers },
+) {
const location = () => (
<>
@@ -21,7 +23,13 @@ export default function SessionLocationWorkspace(props: BuiltinSlotMap["session.
when={!props.session.server.data.session.get(props.session.id)?.parentID}
fallback={
{location()}}
>
-
+
{location()}
diff --git a/packages/gui-plugins/src/details/paths.ts b/packages/gui-plugins/src/details/paths.ts
index eb440fbb49e..e99a4b19e06 100644
--- a/packages/gui-plugins/src/details/paths.ts
+++ b/packages/gui-plugins/src/details/paths.ts
@@ -1,5 +1,17 @@
import { sameDirectory } from "@opencode/util/path"
-export function workspaceDirectories(project: { worktree: string; sandboxes?: readonly string[] }) {
- return (project.sandboxes ?? []).filter((directory) => !sameDirectory(project.worktree, directory))
+/** The parts of a project that name its checkouts. */
+export type WorkspaceProject = {
+ readonly worktree: string
+ readonly sandboxes?: readonly string[]
+ readonly worktrees?: readonly { readonly directory: string }[]
+}
+
+/** The project's worktrees other than its root, from its sandboxes and the worktrees found on disk. */
+export function workspaceDirectories(project: WorkspaceProject) {
+ return [...(project.sandboxes ?? []), ...(project.worktrees ?? []).map((item) => item.directory)].filter(
+ (directory, index, all) =>
+ !sameDirectory(project.worktree, directory) &&
+ all.findIndex((candidate) => sameDirectory(candidate, directory)) === index,
+ )
}
diff --git a/packages/gui-plugins/src/details/renderer.tsx b/packages/gui-plugins/src/details/renderer.tsx
index cd6aaf353c7..a125a305a7b 100644
--- a/packages/gui-plugins/src/details/renderer.tsx
+++ b/packages/gui-plugins/src/details/renderer.tsx
@@ -4,6 +4,7 @@ import type Details from "./index"
import { DetailsHeader, type DetailsMenus } from "./popover"
import { BuiltinSlot, onIdle } from "@opencode/plugin/gui/builtin"
import type { McpControllers } from "./server-panel"
+import type { WorkspaceMoveControllers } from "./workspace-menu"
const setup: Plugin.Setup = (ctx) => {
const sessions = ctx.sessions
@@ -11,6 +12,8 @@ const setup: Plugin.Setup = (ctx) => {
const menus: DetailsMenus = new Set()
// MCP toggles and error dialogs outlive the popover or drawer that started them.
const mcp: McpControllers = new Map()
+ // Moves and their recovery dialogs outlive the location menu, which closes when the user picks a destination.
+ const moves: WorkspaceMoveControllers = new Map()
const DetailsPanel = lazy(() =>
Promise.all([import("./panel"), import("./details.css?inline")]).then(([panel, css]) => {
@@ -53,7 +56,7 @@ const setup: Plugin.Setup = (ctx) => {
at: "session.location.workspace",
render: (input) => (
-
+
),
})
diff --git a/packages/gui-plugins/src/details/workspace-menu.tsx b/packages/gui-plugins/src/details/workspace-menu.tsx
index e493a9b029c..38112f2ed84 100644
--- a/packages/gui-plugins/src/details/workspace-menu.tsx
+++ b/packages/gui-plugins/src/details/workspace-menu.tsx
@@ -1,17 +1,49 @@
-import { Menu } from "@opencode/ui/menu"
+import { Button } from "@opencode/ui/button"
+import { Dialog, DialogBody, DialogFooter, DialogHeader, DialogTitleGroup } from "@opencode/ui/dialog"
+import { ErrorDetails } from "@opencode/ui/error-details"
import { Icon } from "@opencode/ui/icon"
+import { Loader } from "@opencode/ui/loader"
+import { Menu } from "@opencode/ui/menu"
import { MenuScroll } from "@opencode/ui/menu-scroll"
-import { showToast } from "@opencode/ui/toast"
-import { comparablePath, containsDirectory, getFilename, sameDirectory } from "@opencode/util/path"
-import { createStore } from "solid-js/store"
-import { For, onCleanup, Show, type ComponentProps, type JSX } from "solid-js"
-import { createKeyed, usePlugin, type Project, type MountedSession } from "@opencode/plugin/gui"
-import { workspaceDirectories } from "./paths"
+import { getFilename } from "@opencode/util/path"
+import {
+ createMemo,
+ createRoot,
+ createSignal,
+ For,
+ onCleanup,
+ Show,
+ untrack,
+ type ComponentProps,
+ type JSX,
+} from "solid-js"
+import {
+ createKeyed,
+ usePlugin,
+ type DialogHandle,
+ type MountedSession,
+ type Project,
+ type ServerRef,
+} from "@opencode/plugin/gui"
+import {
+ createWorkspaceMoveState,
+ transitionWorkspaceMove,
+ workspaceDialogView,
+ workspaceMenuView,
+ type WorkspaceDialogView,
+ type WorkspaceMoveEffect,
+ type WorkspaceMoveEvent,
+ type WorkspaceMoveFailure,
+ type WorkspaceMoveState,
+ type WorkspaceMoveTarget,
+} from "./workspace-move-machine"
export function SessionWorkspaceMenu(props: {
session: MountedSession
project: Project
directory: string
+ /** The plugin's move controllers, so a menu that mounts again finds the move or dialog the last one left running. */
+ moves: WorkspaceMoveControllers
placement?: ComponentProps["placement"]
class?: string
/** Renders as a submenu of an enclosing `Menu`. */
@@ -19,97 +51,37 @@ export function SessionWorkspaceMenu(props: {
children: JSX.Element
}) {
const ctx = usePlugin()
- const data = () => props.session.server.data
-
- const [store, setStore] = createStore<{ selected: string | undefined; directories: string[] }>({
- selected: undefined,
- directories: workspaceDirectories(props.project),
- })
-
- const blocked = () => data().session.status(props.session.id) === "running"
- const currentWorkspace = () => store.directories.find((workspace) => containsDirectory(workspace, props.directory))
-
- const workspaces = () =>
- store.directories.filter(
- (workspace) => comparablePath(workspace) !== comparablePath(currentWorkspace() ?? props.directory),
- )
-
- const update = (items: readonly { directory: string }[]) =>
- setStore(
- "directories",
- items.flatMap((item) => (sameDirectory(props.project.worktree, item.directory) ? [] : [item.directory])),
- )
-
- createKeyed(data, (current) =>
- onCleanup(
- current.on("worktree.updated", (event) => {
- if (event.data.projectID !== props.project.id) return
- void props.session.server.client.worktree
- .list({ projectID: props.project.id })
- .then(update)
- .catch(() => undefined)
- }),
- ),
- )
+ const move = useWorkspaceMoveController(props.moves, props.session, props.project.id)
+ const running = () => props.session.server.data.session.status(props.session.id) === "running"
+ const view = createMemo(() => workspaceMenuView(move.state(), props.directory, props.project, running()))
const onOpenChange = (open: boolean) => {
- if (!open) return
- const client = props.session.server.client
- void client.worktree
- .list({ projectID: props.project.id })
- .then(update)
- .then(() => client.worktree.refresh({ projectID: props.project.id }))
- .catch(() => undefined)
+ if (open) move.dispatch({ type: "menu.opened", projectID: props.project.id })
}
- const createWorktree = async (client: MountedSession["server"]["client"], directory: string) => {
- const project =
- data().location.info({ directory })?.project ?? (await client.location.get({ location: { directory } })).project
-
- const created = await client.worktree.create({ projectID: project.id, from: project.canonical })
- // Populate the client cache before the destination session mounts.
- await data().location.syncInfo({ directory: created.directory })
-
- return created.directory
- }
-
- const move = async (selection: "create" | string) => {
- if (store.selected || blocked()) return
- const client = props.session.server.client
- const sessionID = props.session.id
- setStore("selected", selection)
-
- try {
- const destination = selection === "create" ? await createWorktree(client, props.directory) : selection
-
- if (!destination) return
-
- await client.session.move({ sessionID, directory: destination })
- } catch (error) {
- showToast({
- variant: "error",
- title: ctx.t("move.failed"),
- description: error instanceof Error ? error.message : ctx.t("common.requestFailed"),
- })
- } finally {
- setStore("selected", undefined)
- }
- }
+ const request = (target: WorkspaceMoveTarget) =>
+ move.dispatch({ type: "move.requested", target, running: running() })
const items = () => (
{ctx.t("move.menu")}
-
- void move(props.project.worktree)}>
+
+ request({ type: "existing", directory: props.project.worktree })}
+ >
{ctx.t("workspace.local")}
- void move("create")}>
+ request({ type: "create", sourceDirectory: props.directory })}
+ >
{ctx.t("workspace.new")}
- 0}>
+ 0}>