mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(app): move sessions to new worktrees through one state machine and recover orphan worktrees (#61948)
This commit is contained in:
parent
438ca536a0
commit
3fa4f63ae5
8 changed files with 1712 additions and 93 deletions
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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 = () => (
|
||||
<>
|
||||
<Icon name={props.icon} class="text-v2-icon-icon-muted" />
|
||||
|
|
@ -21,7 +23,13 @@ export default function SessionLocationWorkspace(props: BuiltinSlotMap["session.
|
|||
when={!props.session.server.data.session.get(props.session.id)?.parentID}
|
||||
fallback={<Menu.Item disabled>{location()}</Menu.Item>}
|
||||
>
|
||||
<SessionWorkspaceMenu sub session={props.session} project={project()} directory={props.session.directory}>
|
||||
<SessionWorkspaceMenu
|
||||
sub
|
||||
session={props.session}
|
||||
project={project()}
|
||||
directory={props.session.directory}
|
||||
moves={props.moves}
|
||||
>
|
||||
{location()}
|
||||
</SessionWorkspaceMenu>
|
||||
</Show>
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<typeof Details> = (ctx) => {
|
||||
const sessions = ctx.sessions
|
||||
|
|
@ -11,6 +12,8 @@ const setup: Plugin.Setup<typeof Details> = (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<typeof Details> = (ctx) => {
|
|||
at: "session.location.workspace",
|
||||
render: (input) => (
|
||||
<Suspense>
|
||||
<LocationWorkspace {...input} />
|
||||
<LocationWorkspace {...input} moves={moves} />
|
||||
</Suspense>
|
||||
),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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<typeof Menu>["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 = () => (
|
||||
<Menu.Group>
|
||||
<Menu.GroupLabel>{ctx.t("move.menu")}</Menu.GroupLabel>
|
||||
<Show when={comparablePath(props.directory) !== comparablePath(props.project.worktree)}>
|
||||
<Menu.Item disabled={!!store.selected || blocked()} onSelect={() => void move(props.project.worktree)}>
|
||||
<Show when={view().showLocal}>
|
||||
<Menu.Item
|
||||
disabled={view().disabled}
|
||||
onSelect={() => request({ type: "existing", directory: props.project.worktree })}
|
||||
>
|
||||
<Icon name="monitor" class="text-v2-icon-icon-muted" />
|
||||
{ctx.t("workspace.local")}
|
||||
</Menu.Item>
|
||||
</Show>
|
||||
<Menu.Item disabled={!!store.selected || blocked()} onSelect={() => void move("create")}>
|
||||
<Menu.Item
|
||||
disabled={view().disabled}
|
||||
onSelect={() => request({ type: "create", sourceDirectory: props.directory })}
|
||||
>
|
||||
<Icon name="plus" class="text-v2-icon-icon-muted" />
|
||||
{ctx.t("workspace.new")}
|
||||
</Menu.Item>
|
||||
<Show when={workspaces().length > 0}>
|
||||
<Show when={view().workspaces.length > 0}>
|
||||
<Menu.Sub gutter={0} overlap overflowPadding={24}>
|
||||
<Menu.SubTrigger class="[&_[data-slot=menu-v2-item-chevron]]:text-v2-icon-icon-muted">
|
||||
<Icon name="outline-worktree" class="text-v2-icon-icon-muted" />
|
||||
|
|
@ -118,9 +90,12 @@ export function SessionWorkspaceMenu(props: {
|
|||
<Menu.Portal>
|
||||
<Menu.SubContent class="max-h-[66.667dvh] w-[200px] !p-0 [@media(max-height:600px)]:max-h-[calc(100dvh-48px)]">
|
||||
<MenuScroll viewportClass="p-0.5">
|
||||
<For each={workspaces()}>
|
||||
<For each={view().workspaces}>
|
||||
{(workspace) => (
|
||||
<Menu.Item disabled={!!store.selected || blocked()} onSelect={() => void move(workspace)}>
|
||||
<Menu.Item
|
||||
disabled={view().disabled}
|
||||
onSelect={() => request({ type: "existing", directory: workspace })}
|
||||
>
|
||||
<Icon name="outline-worktree" class="text-v2-icon-icon-muted" />
|
||||
<span class="min-w-0 flex-1 truncate">{getFilename(workspace)}</span>
|
||||
</Menu.Item>
|
||||
|
|
@ -137,7 +112,10 @@ export function SessionWorkspaceMenu(props: {
|
|||
if (props.sub)
|
||||
return (
|
||||
<Menu.Sub gutter={4} overflowPadding={24} onOpenChange={onOpenChange}>
|
||||
<Menu.SubTrigger class="[&_[data-slot=menu-v2-item-chevron]]:text-v2-icon-icon-muted" disabled={blocked()}>
|
||||
<Menu.SubTrigger
|
||||
class="[&_[data-slot=menu-v2-item-chevron]]:text-v2-icon-icon-muted"
|
||||
disabled={view().disabled}
|
||||
>
|
||||
{props.children}
|
||||
</Menu.SubTrigger>
|
||||
<Menu.Portal>
|
||||
|
|
@ -154,7 +132,7 @@ export function SessionWorkspaceMenu(props: {
|
|||
modal={false}
|
||||
onOpenChange={onOpenChange}
|
||||
>
|
||||
<Menu.Trigger class={props.class} disabled={blocked()}>
|
||||
<Menu.Trigger class={props.class} disabled={view().disabled}>
|
||||
{props.children}
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
|
|
@ -163,3 +141,350 @@ export function SessionWorkspaceMenu(props: {
|
|||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
type WorkspaceMoveController = {
|
||||
readonly state: () => WorkspaceMoveState
|
||||
dispatch: (event: WorkspaceMoveEvent) => void
|
||||
/** Closes the recovery dialog of `attempt`, if it still shows, and reports that it closed. */
|
||||
dismiss: (attempt: number) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin instance's move controllers, by `MountedSession.key`, so the location menu, which unmounts as soon as
|
||||
* the user picks a destination, finds the move or recovery dialog it left running when it mounts again.
|
||||
*/
|
||||
export type WorkspaceMoveControllers = Map<string, WorkspaceMoveController>
|
||||
|
||||
// The session's controller, shared with every other menu and the recovery dialog, for as long as this menu lives.
|
||||
function useWorkspaceMoveController(
|
||||
controllers: WorkspaceMoveControllers,
|
||||
session: Pick<MountedSession, "key" | "id" | "server">,
|
||||
projectID: string,
|
||||
) {
|
||||
const key = session.key
|
||||
const current = controllers.get(key)
|
||||
|
||||
const move =
|
||||
current && untrack(current.state).status !== "disposed"
|
||||
? current
|
||||
: createWorkspaceMoveController(session.server, session.id, projectID, () => {
|
||||
if (controllers.get(key) === move) controllers.delete(key)
|
||||
})
|
||||
|
||||
controllers.set(key, move)
|
||||
move.dispatch({ type: "mounted" })
|
||||
onCleanup(() => move.dispatch({ type: "unmounted" }))
|
||||
|
||||
return move
|
||||
}
|
||||
|
||||
// Moves one session to an existing or a new worktree. A new worktree that does not receive the session (a failed or
|
||||
// timed-out move, or a session that started running meanwhile) opens a dialog that retries the move or deletes the
|
||||
// worktree. It ends once no menu is mounted and nothing runs or shows, or with the plugin.
|
||||
function createWorkspaceMoveController(
|
||||
server: ServerRef,
|
||||
sessionID: string,
|
||||
projectID: string,
|
||||
release: () => void,
|
||||
): WorkspaceMoveController {
|
||||
const ctx = usePlugin()
|
||||
const [moveState, setMoveState] = createSignal(createWorkspaceMoveState(projectID))
|
||||
const ops = new Map<number, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>()
|
||||
const lists = new Map<number, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>()
|
||||
const dialogs = new Map<number, DialogHandle>()
|
||||
// Events an effect raises synchronously (a dialog that closes and reports it) wait behind the current one.
|
||||
const queue: WorkspaceMoveEvent[] = []
|
||||
const dispose = () => dispatch({ type: "disposed" })
|
||||
|
||||
const dispatch = (event: WorkspaceMoveEvent) => {
|
||||
queue.push(event)
|
||||
|
||||
if (queue.length === 1) drain()
|
||||
}
|
||||
|
||||
const drain = () => {
|
||||
const event = queue[0]
|
||||
|
||||
if (!event) return
|
||||
|
||||
try {
|
||||
const previous = untrack(moveState)
|
||||
const next = transitionWorkspaceMove(previous, event)
|
||||
|
||||
if (next.state !== previous) setMoveState(next.state)
|
||||
|
||||
if (next.state.status === "disposed" && previous.status !== "disposed") {
|
||||
ctx.signal.removeEventListener("abort", dispose)
|
||||
stop()
|
||||
release()
|
||||
}
|
||||
|
||||
// One effect that throws must not skip the others.
|
||||
next.effects.forEach(
|
||||
(effect) =>
|
||||
void Promise.try(() => run(effect)).catch((cause: unknown) => console.error("[details] workspace move", cause)),
|
||||
)
|
||||
} finally {
|
||||
queue.shift()
|
||||
drain()
|
||||
}
|
||||
}
|
||||
|
||||
const move: WorkspaceMoveController = {
|
||||
state: moveState,
|
||||
dispatch,
|
||||
dismiss: (attempt) => {
|
||||
const handle = dialogs.get(attempt)
|
||||
dialogs.delete(attempt)
|
||||
handle?.close()
|
||||
dispatch({ type: "dialog.dismissed", attempt })
|
||||
},
|
||||
}
|
||||
|
||||
const failed = (cause: unknown) =>
|
||||
cause instanceof Error && cause.message ? cause.message : ctx.t("common.requestFailed")
|
||||
|
||||
const start = (
|
||||
handles: typeof ops,
|
||||
attempt: number,
|
||||
timeoutMs: number,
|
||||
timedOut: WorkspaceMoveEvent,
|
||||
): AbortSignal => {
|
||||
const controller = new AbortController()
|
||||
handles.set(attempt, { controller, timer: setTimeout(() => dispatch(timedOut), timeoutMs) })
|
||||
|
||||
return AbortSignal.any([ctx.signal, controller.signal])
|
||||
}
|
||||
|
||||
const end = (handles: typeof ops, attempt: number) => {
|
||||
const handle = handles.get(attempt)
|
||||
handles.delete(attempt)
|
||||
clearTimeout(handle?.timer)
|
||||
handle?.controller.abort()
|
||||
}
|
||||
|
||||
const run = (effect: WorkspaceMoveEffect) => {
|
||||
if (effect.type === "list-worktrees") {
|
||||
const attempt = effect.attempt
|
||||
const signal = start(lists, attempt, effect.timeoutMs, { type: "list.failed", attempt })
|
||||
|
||||
return void server.client.worktree.list({ projectID: effect.projectID }, { signal }).then(
|
||||
(items) => dispatch({ type: "list.loaded", attempt, items }),
|
||||
() => dispatch({ type: "list.failed", attempt }),
|
||||
)
|
||||
}
|
||||
|
||||
if (effect.type === "abort-list") return end(lists, effect.attempt)
|
||||
|
||||
if (effect.type === "refresh-worktrees")
|
||||
return void server.client.worktree
|
||||
.refresh({ projectID: effect.projectID }, { signal: ctx.signal })
|
||||
.catch(() => undefined)
|
||||
|
||||
if (effect.type === "run-create") {
|
||||
const attempt = effect.attempt
|
||||
const signal = start(ops, attempt, effect.timeoutMs, { type: "op.timed-out", attempt })
|
||||
|
||||
return void create(effect, signal).then(dispatch, (cause: unknown) =>
|
||||
dispatch({ type: "create.failed", attempt, error: failed(cause) }),
|
||||
)
|
||||
}
|
||||
|
||||
if (effect.type === "run-move") {
|
||||
const attempt = effect.attempt
|
||||
const signal = start(ops, attempt, effect.timeoutMs, { type: "op.timed-out", attempt })
|
||||
|
||||
return void moveTo(effect, signal).then(dispatch, (cause: unknown) =>
|
||||
dispatch({ type: "move.failed", attempt, error: failed(cause) }),
|
||||
)
|
||||
}
|
||||
|
||||
if (effect.type === "run-remove") {
|
||||
const attempt = effect.attempt
|
||||
const signal = start(ops, attempt, effect.timeoutMs, { type: "op.timed-out", attempt })
|
||||
|
||||
// Forced: the project's start command may have left untracked files in the new checkout.
|
||||
return void server.client.worktree
|
||||
.remove({ projectID: effect.projectID, directory: effect.directory, force: true }, { signal })
|
||||
.then(
|
||||
() => dispatch({ type: "remove.succeeded", attempt }),
|
||||
(cause: unknown) => dispatch({ type: "remove.failed", attempt, error: failed(cause) }),
|
||||
)
|
||||
}
|
||||
|
||||
if (effect.type === "abort-op") return end(ops, effect.attempt)
|
||||
|
||||
if (effect.type === "open-dialog")
|
||||
return void dialogs.set(
|
||||
effect.attempt,
|
||||
ctx.dialogs.open(() => (
|
||||
<WorkspaceMoveDialog move={move} attempt={effect.attempt} server={server} sessionID={sessionID} />
|
||||
)),
|
||||
)
|
||||
|
||||
if (effect.type === "close-dialog") {
|
||||
const handle = dialogs.get(effect.attempt)
|
||||
dialogs.delete(effect.attempt)
|
||||
|
||||
return handle?.close()
|
||||
}
|
||||
|
||||
ctx.toast.show({
|
||||
variant: "error",
|
||||
title: ctx.t(effect.kind === "move" ? "move.failed" : "move.removeFailed"),
|
||||
description: reasonText(ctx.t, effect.reason),
|
||||
})
|
||||
}
|
||||
|
||||
const create = async (
|
||||
effect: Extract<WorkspaceMoveEffect, { type: "run-create" }>,
|
||||
signal: AbortSignal,
|
||||
): Promise<WorkspaceMoveEvent> => {
|
||||
const directory = effect.sourceDirectory
|
||||
|
||||
const project =
|
||||
server.data.location.info({ directory })?.project ??
|
||||
(await server.client.location.get({ location: { directory } }, { signal })).project
|
||||
|
||||
const created = await server.client.worktree.create({ projectID: project.id, from: project.canonical }, { signal })
|
||||
|
||||
return {
|
||||
type: "worktree.created",
|
||||
attempt: effect.attempt,
|
||||
projectID: project.id,
|
||||
directory: created.directory,
|
||||
running: server.data.session.status(sessionID) === "running",
|
||||
}
|
||||
}
|
||||
|
||||
const moveTo = async (
|
||||
effect: Extract<WorkspaceMoveEffect, { type: "run-move" }>,
|
||||
signal: AbortSignal,
|
||||
): Promise<WorkspaceMoveEvent> => {
|
||||
// Populate the client cache before the destination session mounts.
|
||||
if (effect.syncLocation) await server.data.location.syncInfo({ directory: effect.directory })
|
||||
signal.throwIfAborted()
|
||||
|
||||
// The session may have started running since the user picked the destination.
|
||||
if (server.data.session.status(sessionID) === "running") return { type: "move.blocked", attempt: effect.attempt }
|
||||
|
||||
await server.client.session.move({ sessionID, directory: effect.directory }, { signal })
|
||||
|
||||
return { type: "move.succeeded", attempt: effect.attempt }
|
||||
}
|
||||
|
||||
// What the controller follows while it lives, with or without a menu: the server's worktree inventory and the
|
||||
// session's directory. The root ends with the controller.
|
||||
const stop = createRoot((disposeRoot) => {
|
||||
createKeyed(
|
||||
() => server.data,
|
||||
(data) =>
|
||||
onCleanup(
|
||||
data.on("worktree.updated", (event) => dispatch({ type: "worktree.updated", projectID: event.data.projectID })),
|
||||
),
|
||||
)
|
||||
createKeyed(
|
||||
() => server.data.session.get(sessionID)?.location.directory,
|
||||
(directory) => dispatch({ type: "session.moved", directory }),
|
||||
)
|
||||
|
||||
return disposeRoot
|
||||
})
|
||||
|
||||
// The plugin's end ends the move, the list and the dialog that outlived the menu.
|
||||
ctx.signal.addEventListener("abort", dispose, { once: true })
|
||||
|
||||
return move
|
||||
}
|
||||
|
||||
// The recovery dialog for a worktree this controller created that does not have the session. Its controller outlives
|
||||
// the menu that started the move.
|
||||
function WorkspaceMoveDialog(props: {
|
||||
move: WorkspaceMoveController
|
||||
attempt: number
|
||||
server: ServerRef
|
||||
sessionID: string
|
||||
}) {
|
||||
const ctx = usePlugin()
|
||||
const running = () => props.server.data.session.status(props.sessionID) === "running"
|
||||
|
||||
// Keeps the last content while the dialog plays its exit animation after the controller closed it.
|
||||
const view = createMemo<WorkspaceDialogView | undefined>(
|
||||
(previous) => workspaceDialogView(props.move.state(), props.attempt, running()) ?? previous,
|
||||
)
|
||||
|
||||
onCleanup(() => props.move.dismiss(props.attempt))
|
||||
|
||||
return (
|
||||
<Show when={view()}>
|
||||
{(current) => {
|
||||
const error = () => {
|
||||
const reason = current().reason
|
||||
|
||||
return reason.type === "failed" ? reason.error : undefined
|
||||
}
|
||||
|
||||
// Focus starts on Retry, or on Keep worktree while Retry waits for the run, never on Delete worktree.
|
||||
const actions = () => (
|
||||
<>
|
||||
<Button variant="ghost" autofocus={current().running} onClick={() => props.move.dismiss(props.attempt)}>
|
||||
{ctx.t("move.recovery.keep")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost-danger"
|
||||
disabled={current().removeDisabled}
|
||||
onClick={() => props.move.dispatch({ type: "recovery.remove", attempt: props.attempt })}
|
||||
>
|
||||
<Show when={current().removing}>
|
||||
<Loader class="size-4 shrink-0" />
|
||||
</Show>
|
||||
{ctx.t("move.recovery.remove")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contrast"
|
||||
autofocus={!current().running}
|
||||
disabled={current().retryDisabled}
|
||||
onClick={() =>
|
||||
props.move.dispatch({ type: "recovery.retry", attempt: props.attempt, running: running() })
|
||||
}
|
||||
>
|
||||
<Show when={current().retrying}>
|
||||
<Loader class="size-4 shrink-0" />
|
||||
</Show>
|
||||
{ctx.t("retry")}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<Dialog fit>
|
||||
<DialogHeader>
|
||||
<DialogTitleGroup
|
||||
title={ctx.t("move.recovery.title")}
|
||||
description={
|
||||
<>
|
||||
{ctx.t("move.recovery.description", { name: getFilename(current().directory) })}
|
||||
<Show when={!error()}> {reasonText(ctx.t, current().reason)}</Show>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</DialogHeader>
|
||||
<Show when={error()} fallback={<DialogFooter>{actions()}</DialogFooter>}>
|
||||
{(message) => (
|
||||
<DialogBody>
|
||||
<ErrorDetails error={message()}>{actions()}</ErrorDetails>
|
||||
</DialogBody>
|
||||
)}
|
||||
</Show>
|
||||
</Dialog>
|
||||
)
|
||||
}}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function reasonText(t: ReturnType<typeof usePlugin>["t"], reason: WorkspaceMoveFailure) {
|
||||
if (reason.type === "failed") return reason.error
|
||||
|
||||
return t(reason.type === "running" ? "move.running" : "timedOut")
|
||||
}
|
||||
|
|
|
|||
498
packages/gui-plugins/src/details/workspace-move-machine.test.ts
Normal file
498
packages/gui-plugins/src/details/workspace-move-machine.test.ts
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
WORKSPACE_CREATE_TIMEOUT_MS,
|
||||
WORKSPACE_LIST_TIMEOUT_MS,
|
||||
WORKSPACE_MOVE_TIMEOUT_MS,
|
||||
WORKSPACE_REMOVE_TIMEOUT_MS,
|
||||
createWorkspaceMoveState,
|
||||
transitionWorkspaceMove,
|
||||
workspaceDialogView,
|
||||
workspaceMenuView,
|
||||
type WorkspaceMoveEvent,
|
||||
type WorkspaceMoveState,
|
||||
type WorkspaceMoveTransition,
|
||||
} from "./workspace-move-machine"
|
||||
|
||||
const root = "C:/OpenCode/repo"
|
||||
|
||||
const created = "C:/OpenCode/worktrees/quiet-river"
|
||||
|
||||
const project = { id: "proj_repo", worktree: root, sandboxes: [`${root}-feature`] }
|
||||
|
||||
// The state once a menu shows the session's destinations, as every controller starts.
|
||||
const mounted = transitionWorkspaceMove(createWorkspaceMoveState(project.id), { type: "mounted" }).state
|
||||
|
||||
// Folds the events in order and returns the last transition.
|
||||
const replay = (events: readonly WorkspaceMoveEvent[], state: WorkspaceMoveState = mounted) =>
|
||||
events.reduce<WorkspaceMoveTransition>((last, event) => transitionWorkspaceMove(last.state, event), {
|
||||
state,
|
||||
effects: [],
|
||||
})
|
||||
|
||||
const createRequested: WorkspaceMoveEvent = {
|
||||
type: "move.requested",
|
||||
target: { type: "create", sourceDirectory: root },
|
||||
running: false,
|
||||
}
|
||||
|
||||
const worktreeCreated = (attempt: number, running = false): WorkspaceMoveEvent => ({
|
||||
type: "worktree.created",
|
||||
attempt,
|
||||
projectID: project.id,
|
||||
directory: created,
|
||||
running,
|
||||
})
|
||||
|
||||
// New worktree, then a move that fails: attempt 1 creates, 2 moves, 3 is the recovery dialog.
|
||||
const failedMove = [
|
||||
createRequested,
|
||||
worktreeCreated(1),
|
||||
{ type: "move.failed", attempt: 2, error: "Session is locked" },
|
||||
] satisfies WorkspaceMoveEvent[]
|
||||
|
||||
describe("transitionWorkspaceMove", () => {
|
||||
test("a move that fails after the worktree exists offers to retry or delete it instead of forgetting it", () => {
|
||||
const create = transitionWorkspaceMove(mounted, createRequested)
|
||||
|
||||
expect(create.effects).toEqual([
|
||||
{ type: "run-create", attempt: 1, sourceDirectory: root, timeoutMs: WORKSPACE_CREATE_TIMEOUT_MS },
|
||||
])
|
||||
|
||||
const move = transitionWorkspaceMove(create.state, worktreeCreated(1))
|
||||
|
||||
expect(move.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "run-move", attempt: 2, directory: created, syncLocation: true, timeoutMs: WORKSPACE_MOVE_TIMEOUT_MS },
|
||||
])
|
||||
|
||||
const failed = transitionWorkspaceMove(move.state, failedMove[2])
|
||||
|
||||
expect(failed.state).toMatchObject({
|
||||
status: "recovering",
|
||||
dialog: 3,
|
||||
created: { projectID: project.id, directory: created },
|
||||
reason: { type: "failed", error: "Session is locked" },
|
||||
})
|
||||
expect(failed.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 2 },
|
||||
{ type: "open-dialog", attempt: 3 },
|
||||
])
|
||||
expect(workspaceDialogView(failed.state, 3, false)).toEqual({
|
||||
directory: created,
|
||||
reason: { type: "failed", error: "Session is locked" },
|
||||
running: false,
|
||||
retrying: false,
|
||||
removing: false,
|
||||
retryDisabled: false,
|
||||
removeDisabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
test("Retry moves into the worktree already created, keeps the error shown, and closes the dialog once moved", () => {
|
||||
const retry = replay([...failedMove, { type: "recovery.retry", attempt: 3, running: false }])
|
||||
|
||||
expect(retry.effects).toEqual([
|
||||
{ type: "run-move", attempt: 4, directory: created, syncLocation: true, timeoutMs: WORKSPACE_MOVE_TIMEOUT_MS },
|
||||
])
|
||||
expect(workspaceDialogView(retry.state, 3, false)).toMatchObject({
|
||||
reason: { type: "failed", error: "Session is locked" },
|
||||
retrying: true,
|
||||
retryDisabled: true,
|
||||
removeDisabled: true,
|
||||
})
|
||||
|
||||
const moved = transitionWorkspaceMove(retry.state, { type: "move.succeeded", attempt: 4 })
|
||||
|
||||
expect(moved.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 4 },
|
||||
{ type: "close-dialog", attempt: 3 },
|
||||
])
|
||||
expect(moved.state).toMatchObject({ status: "idle", mounts: 1 })
|
||||
})
|
||||
|
||||
test("Delete worktree force-removes the created worktree and closes the dialog", () => {
|
||||
const remove = replay([...failedMove, { type: "recovery.remove", attempt: 3 }])
|
||||
|
||||
expect(remove.effects).toEqual([
|
||||
{
|
||||
type: "run-remove",
|
||||
attempt: 4,
|
||||
projectID: project.id,
|
||||
directory: created,
|
||||
timeoutMs: WORKSPACE_REMOVE_TIMEOUT_MS,
|
||||
},
|
||||
])
|
||||
expect(workspaceDialogView(remove.state, 3, false)).toMatchObject({ removing: true, retryDisabled: true })
|
||||
|
||||
const removed = transitionWorkspaceMove(remove.state, { type: "remove.succeeded", attempt: 4 })
|
||||
|
||||
expect(removed.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 4 },
|
||||
{ type: "close-dialog", attempt: 3 },
|
||||
])
|
||||
expect(removed.state.status).toBe("idle")
|
||||
})
|
||||
|
||||
test("a retry or removal that fails in the open dialog shows the new failure there, without a toast", () => {
|
||||
const retried = replay([
|
||||
...failedMove,
|
||||
{ type: "recovery.retry", attempt: 3, running: false },
|
||||
{ type: "op.timed-out", attempt: 4 },
|
||||
])
|
||||
|
||||
expect(retried.effects).toEqual([{ type: "abort-op", attempt: 4 }])
|
||||
expect(retried.state).toMatchObject({ status: "recovering", dialog: 3, reason: { type: "timed-out" } })
|
||||
|
||||
const removed = replay(
|
||||
[
|
||||
{ type: "recovery.remove", attempt: 3 },
|
||||
{ type: "remove.failed", attempt: 5, error: "Directory busy" },
|
||||
],
|
||||
retried.state,
|
||||
)
|
||||
|
||||
expect(removed.effects).toEqual([{ type: "abort-op", attempt: 5 }])
|
||||
expect(removed.state).toMatchObject({
|
||||
status: "recovering",
|
||||
dialog: 3,
|
||||
reason: { type: "failed", error: "Directory busy" },
|
||||
})
|
||||
})
|
||||
|
||||
test("closing the dialog keeps the worktree and ends the controller once no menu is mounted", () => {
|
||||
const closed = replay([...failedMove, { type: "dialog.dismissed", attempt: 3 }])
|
||||
|
||||
expect(closed.state).toMatchObject({ status: "idle", mounts: 1 })
|
||||
expect(closed.effects).toEqual([])
|
||||
|
||||
const unmounted = replay([{ type: "unmounted" }, ...failedMove, { type: "dialog.dismissed", attempt: 3 }])
|
||||
|
||||
expect(unmounted.state).toEqual({ status: "disposed" })
|
||||
})
|
||||
|
||||
test("a retry or removal the user stopped watching finishes, and a late failure toasts", () => {
|
||||
const retry = replay([
|
||||
...failedMove,
|
||||
{ type: "recovery.retry", attempt: 3, running: false },
|
||||
{ type: "dialog.dismissed", attempt: 3 },
|
||||
])
|
||||
|
||||
expect(retry.state).toMatchObject({ status: "moving", attempt: 4, dialog: { status: "dismissed" } })
|
||||
expect(workspaceDialogView(retry.state, 3, false)).toBeUndefined()
|
||||
|
||||
const failed = transitionWorkspaceMove(retry.state, { type: "move.failed", attempt: 4, error: "Offline" })
|
||||
|
||||
expect(failed.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 4 },
|
||||
{ type: "toast", kind: "move", reason: { type: "failed", error: "Offline" } },
|
||||
])
|
||||
expect(failed.state.status).toBe("idle")
|
||||
|
||||
const remove = replay([
|
||||
...failedMove,
|
||||
{ type: "recovery.remove", attempt: 3 },
|
||||
{ type: "dialog.dismissed", attempt: 3 },
|
||||
{ type: "op.timed-out", attempt: 4 },
|
||||
])
|
||||
|
||||
expect(remove.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 4 },
|
||||
{ type: "toast", kind: "remove", reason: { type: "timed-out" } },
|
||||
])
|
||||
expect(remove.state.status).toBe("idle")
|
||||
|
||||
const removed = replay([
|
||||
...failedMove,
|
||||
{ type: "recovery.remove", attempt: 3 },
|
||||
{ type: "dialog.dismissed", attempt: 3 },
|
||||
{ type: "remove.succeeded", attempt: 4 },
|
||||
])
|
||||
|
||||
expect(removed.effects).toEqual([{ type: "abort-op", attempt: 4 }])
|
||||
})
|
||||
|
||||
test("a session that starts running while the worktree is created stays put, and Retry waits for the run", () => {
|
||||
const running = replay([createRequested, worktreeCreated(1, true)])
|
||||
|
||||
expect(running.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "open-dialog", attempt: 2 },
|
||||
])
|
||||
expect(running.state).toMatchObject({ status: "recovering", dialog: 2, reason: { type: "running" } })
|
||||
expect(workspaceDialogView(running.state, 2, true)).toMatchObject({ running: true, retryDisabled: true })
|
||||
expect(workspaceDialogView(running.state, 2, false)).toMatchObject({ running: false, retryDisabled: false })
|
||||
|
||||
const early = transitionWorkspaceMove(running.state, { type: "recovery.retry", attempt: 2, running: true })
|
||||
|
||||
expect(early.state).toBe(running.state)
|
||||
expect(early.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a session that starts running before session.move is sent is not moved", () => {
|
||||
const created = replay([createRequested, worktreeCreated(1), { type: "move.blocked", attempt: 2 }])
|
||||
|
||||
expect(created.state).toMatchObject({ status: "recovering", reason: { type: "running" } })
|
||||
expect(created.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 2 },
|
||||
{ type: "open-dialog", attempt: 3 },
|
||||
])
|
||||
|
||||
const existing = replay([
|
||||
{ type: "move.requested", target: { type: "existing", directory: `${root}-feature` }, running: false },
|
||||
{ type: "move.blocked", attempt: 1 },
|
||||
])
|
||||
|
||||
expect(existing.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "toast", kind: "move", reason: { type: "running" } },
|
||||
])
|
||||
expect(existing.state.status).toBe("idle")
|
||||
})
|
||||
|
||||
test("a move survives the menu that started it and blocks a second move from the next menu", () => {
|
||||
const closed = replay([createRequested, { type: "unmounted" }])
|
||||
|
||||
expect(closed.state).toMatchObject({ status: "creating", mounts: 0 })
|
||||
|
||||
const reopened = transitionWorkspaceMove(closed.state, { type: "mounted" }).state
|
||||
|
||||
expect(workspaceMenuView(reopened, root, project, false).disabled).toBe(true)
|
||||
|
||||
const second = transitionWorkspaceMove(reopened, createRequested)
|
||||
|
||||
expect(second.state).toBe(reopened)
|
||||
expect(second.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("an older worktree list never replaces a newer one, and the menu's refresh still runs once", () => {
|
||||
const opened = transitionWorkspaceMove(mounted, { type: "menu.opened", projectID: project.id })
|
||||
|
||||
expect(opened.effects).toEqual([
|
||||
{ type: "list-worktrees", attempt: 1, projectID: project.id, timeoutMs: WORKSPACE_LIST_TIMEOUT_MS },
|
||||
])
|
||||
|
||||
const updated = transitionWorkspaceMove(opened.state, { type: "worktree.updated", projectID: project.id })
|
||||
|
||||
expect(updated.effects).toEqual([
|
||||
{ type: "abort-list", attempt: 1 },
|
||||
{ type: "list-worktrees", attempt: 2, projectID: project.id, timeoutMs: WORKSPACE_LIST_TIMEOUT_MS },
|
||||
])
|
||||
|
||||
const stale = transitionWorkspaceMove(updated.state, {
|
||||
type: "list.loaded",
|
||||
attempt: 1,
|
||||
items: [{ directory: root }, { directory: `${root}/stale` }],
|
||||
})
|
||||
|
||||
expect(stale.state).toBe(updated.state)
|
||||
|
||||
const fresh = transitionWorkspaceMove(updated.state, {
|
||||
type: "list.loaded",
|
||||
attempt: 2,
|
||||
items: [{ directory: root }, { directory: `${root}/fresh` }],
|
||||
})
|
||||
|
||||
expect(fresh.effects).toEqual([
|
||||
{ type: "abort-list", attempt: 2 },
|
||||
{ type: "refresh-worktrees", projectID: project.id },
|
||||
])
|
||||
expect(workspaceMenuView(fresh.state, root, project, false).workspaces).toEqual([`${root}/fresh`])
|
||||
})
|
||||
|
||||
test("a failed list keeps the worktrees the menu already shows", () => {
|
||||
const listed = replay([
|
||||
{ type: "menu.opened", projectID: project.id },
|
||||
{ type: "list.loaded", attempt: 1, items: [{ directory: `${root}/kept` }] },
|
||||
{ type: "worktree.updated", projectID: project.id },
|
||||
{ type: "list.failed", attempt: 2 },
|
||||
])
|
||||
|
||||
expect(listed.effects).toEqual([{ type: "abort-list", attempt: 2 }])
|
||||
expect(workspaceMenuView(listed.state, root, project, false).workspaces).toEqual([`${root}/kept`])
|
||||
})
|
||||
|
||||
test("another project's worktree changes and a list for another project are ignored or reset the inventory", () => {
|
||||
const listed = replay([
|
||||
{ type: "menu.opened", projectID: project.id },
|
||||
{ type: "list.loaded", attempt: 1, items: [{ directory: `${root}/kept` }] },
|
||||
])
|
||||
|
||||
const other = transitionWorkspaceMove(listed.state, { type: "worktree.updated", projectID: "proj_other" })
|
||||
|
||||
expect(other.state).toBe(listed.state)
|
||||
|
||||
const switched = transitionWorkspaceMove(listed.state, { type: "menu.opened", projectID: "proj_other" })
|
||||
|
||||
expect(switched.state).toMatchObject({ projectID: "proj_other", directories: undefined })
|
||||
// The project the menu shows now falls back to its own worktrees until its list arrives.
|
||||
expect(
|
||||
workspaceMenuView(switched.state, "D:/other", { id: "proj_other", worktree: "D:/other" }, false).workspaces,
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
test("the dialog closes when the session reaches the worktree or the worktree goes away elsewhere", () => {
|
||||
const recovering = replay(failedMove).state
|
||||
|
||||
const moved = transitionWorkspaceMove(recovering, { type: "session.moved", directory: created.toUpperCase() })
|
||||
|
||||
expect(moved.effects).toEqual([{ type: "close-dialog", attempt: 3 }])
|
||||
expect(moved.state.status).toBe("idle")
|
||||
expect(transitionWorkspaceMove(recovering, { type: "session.moved", directory: root }).state).toBe(recovering)
|
||||
|
||||
const gone = replay(
|
||||
[
|
||||
{ type: "worktree.updated", projectID: project.id },
|
||||
{ type: "list.loaded", attempt: 4, items: [{ directory: root }] },
|
||||
],
|
||||
recovering,
|
||||
)
|
||||
|
||||
expect(gone.effects).toEqual([
|
||||
{ type: "abort-list", attempt: 4 },
|
||||
{ type: "close-dialog", attempt: 3 },
|
||||
])
|
||||
expect(gone.state.status).toBe("idle")
|
||||
})
|
||||
|
||||
test("a list issued before the dialog opened cannot close it, as it may predate the worktree", () => {
|
||||
const listing = replay([{ type: "menu.opened", projectID: project.id }, ...failedMove.map(shift)])
|
||||
|
||||
expect(listing.state).toMatchObject({ status: "recovering", dialog: 4 })
|
||||
|
||||
const old = transitionWorkspaceMove(listing.state, { type: "list.loaded", attempt: 1, items: [{ directory: root }] })
|
||||
|
||||
expect(old.state).toMatchObject({ status: "recovering", directories: [root] })
|
||||
expect(old.effects).toEqual([
|
||||
{ type: "abort-list", attempt: 1 },
|
||||
{ type: "refresh-worktrees", projectID: project.id },
|
||||
])
|
||||
})
|
||||
|
||||
test("creating, moving and removing each time out into a state the user can act on", () => {
|
||||
const create = replay([createRequested, { type: "op.timed-out", attempt: 1 }])
|
||||
|
||||
expect(create.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "toast", kind: "move", reason: { type: "timed-out" } },
|
||||
])
|
||||
expect(create.state.status).toBe("idle")
|
||||
|
||||
const failedCreate = replay([createRequested, { type: "create.failed", attempt: 1, error: "No git" }])
|
||||
|
||||
expect(failedCreate.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "toast", kind: "move", reason: { type: "failed", error: "No git" } },
|
||||
])
|
||||
|
||||
const existing = replay([
|
||||
{ type: "move.requested", target: { type: "existing", directory: root }, running: false },
|
||||
{ type: "op.timed-out", attempt: 1 },
|
||||
])
|
||||
|
||||
expect(existing.effects).toEqual([
|
||||
{ type: "abort-op", attempt: 1 },
|
||||
{ type: "toast", kind: "move", reason: { type: "timed-out" } },
|
||||
])
|
||||
|
||||
const createdMove = replay([createRequested, worktreeCreated(1), { type: "op.timed-out", attempt: 2 }])
|
||||
|
||||
expect(createdMove.state).toMatchObject({ status: "recovering", reason: { type: "timed-out" } })
|
||||
})
|
||||
|
||||
test("results of attempts the state no longer holds change nothing", () => {
|
||||
const moving = replay([createRequested, worktreeCreated(1)]).state
|
||||
const recovering = replay(failedMove).state
|
||||
|
||||
for (const [state, event] of [
|
||||
[moving, worktreeCreated(1)],
|
||||
[moving, { type: "create.failed", attempt: 1, error: "late" }],
|
||||
[moving, { type: "op.timed-out", attempt: 1 }],
|
||||
[moving, { type: "move.succeeded", attempt: 9 }],
|
||||
[recovering, { type: "move.failed", attempt: 2, error: "late" }],
|
||||
[recovering, { type: "move.succeeded", attempt: 2 }],
|
||||
[recovering, { type: "remove.succeeded", attempt: 2 }],
|
||||
[recovering, { type: "dialog.dismissed", attempt: 9 }],
|
||||
[recovering, { type: "recovery.retry", attempt: 9, running: false }],
|
||||
[recovering, createRequested],
|
||||
[mounted, { type: "list.loaded", attempt: 9, items: [] }],
|
||||
[mounted, { type: "move.requested", target: { type: "existing", directory: root }, running: true }],
|
||||
] satisfies [WorkspaceMoveState, WorkspaceMoveEvent][]) {
|
||||
const next = transitionWorkspaceMove(state, event)
|
||||
|
||||
expect(next.state).toBe(state)
|
||||
expect(next.effects).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
test("the plugin's end aborts the work in flight and closes the dialog", () => {
|
||||
const retrying = replay([
|
||||
...failedMove,
|
||||
{ type: "worktree.updated", projectID: project.id },
|
||||
{ type: "recovery.retry", attempt: 3, running: false },
|
||||
])
|
||||
|
||||
expect(transitionWorkspaceMove(retrying.state, { type: "disposed" })).toEqual({
|
||||
state: { status: "disposed" },
|
||||
effects: [
|
||||
{ type: "abort-op", attempt: 5 },
|
||||
{ type: "abort-list", attempt: 4 },
|
||||
{ type: "close-dialog", attempt: 3 },
|
||||
],
|
||||
})
|
||||
|
||||
const disposed = transitionWorkspaceMove(retrying.state, { type: "disposed" }).state
|
||||
|
||||
expect(transitionWorkspaceMove(disposed, { type: "move.succeeded", attempt: 5 }).state).toBe(disposed)
|
||||
})
|
||||
|
||||
test("the last menu to unmount while idle ends the controller and its list", () => {
|
||||
const listing = replay([{ type: "menu.opened", projectID: project.id }, { type: "unmounted" }])
|
||||
|
||||
expect(listing).toEqual({ state: { status: "disposed" }, effects: [{ type: "abort-list", attempt: 1 }] })
|
||||
})
|
||||
})
|
||||
|
||||
describe("workspaceMenuView", () => {
|
||||
test("names the destinations other than the root and the worktree that holds the session", () => {
|
||||
const listed = replay([
|
||||
{ type: "menu.opened", projectID: project.id },
|
||||
{
|
||||
type: "list.loaded",
|
||||
attempt: 1,
|
||||
items: [
|
||||
{ directory: root },
|
||||
{ directory: "C:/OpenCode/repo-feature" },
|
||||
{ directory: "c:/opencode/REPO-FEATURE" },
|
||||
{ directory: "C:/OpenCode/repo-other" },
|
||||
],
|
||||
},
|
||||
]).state
|
||||
|
||||
expect(workspaceMenuView(listed, "C:/OpenCode/repo-feature/packages/app", project, false)).toEqual({
|
||||
disabled: false,
|
||||
showLocal: true,
|
||||
workspaces: ["C:/OpenCode/repo-other"],
|
||||
})
|
||||
expect(workspaceMenuView(listed, "c:/opencode/repo", project, false)).toMatchObject({
|
||||
showLocal: false,
|
||||
workspaces: ["C:/OpenCode/repo-feature", "C:/OpenCode/repo-other"],
|
||||
})
|
||||
expect(workspaceMenuView(listed, root, project, true).disabled).toBe(true)
|
||||
})
|
||||
|
||||
test("falls back to the project's worktrees until a list settles", () => {
|
||||
expect(
|
||||
workspaceMenuView(
|
||||
mounted,
|
||||
root,
|
||||
{ ...project, sandboxes: [root], worktrees: [{ directory: `${root}-feature` }, { directory: `${root}-disk` }] },
|
||||
false,
|
||||
).workspaces,
|
||||
).toEqual([`${root}-feature`, `${root}-disk`])
|
||||
})
|
||||
})
|
||||
|
||||
// Shifts each attempt by one, for a sequence replayed after a list took the first attempt.
|
||||
function shift(event: WorkspaceMoveEvent): WorkspaceMoveEvent {
|
||||
return "attempt" in event ? { ...event, attempt: event.attempt + 1 } : event
|
||||
}
|
||||
643
packages/gui-plugins/src/details/workspace-move-machine.ts
Normal file
643
packages/gui-plugins/src/details/workspace-move-machine.ts
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
import { containsDirectory, sameDirectory } from "@opencode/util/path"
|
||||
import { workspaceDirectories, type WorkspaceProject } from "./paths"
|
||||
|
||||
/** How long `worktree.list` may run before the menu keeps the worktrees it already shows. */
|
||||
export const WORKSPACE_LIST_TIMEOUT_MS = 15_000
|
||||
|
||||
/** How long `worktree.create` may run, including the project's start command (often a dependency install). */
|
||||
export const WORKSPACE_CREATE_TIMEOUT_MS = 5 * 60_000
|
||||
|
||||
/** How long `location.syncInfo` plus `session.move` may run. */
|
||||
export const WORKSPACE_MOVE_TIMEOUT_MS = 30_000
|
||||
|
||||
/** How long `worktree.remove` may run; a forced removal deletes every file in the checkout. */
|
||||
export const WORKSPACE_REMOVE_TIMEOUT_MS = 2 * 60_000
|
||||
|
||||
/** A worktree this controller created that has not received the session yet. */
|
||||
export type CreatedWorktree = {
|
||||
readonly projectID: string
|
||||
readonly directory: string
|
||||
}
|
||||
|
||||
/** Why the session did not move into a created worktree, or why deleting that worktree failed. */
|
||||
export type WorkspaceMoveFailure =
|
||||
| { readonly type: "failed"; readonly error: string }
|
||||
| { readonly type: "timed-out" }
|
||||
/** The session started running, so moving it would pull its checkout away mid-run. */
|
||||
| { readonly type: "running" }
|
||||
|
||||
export type WorkspaceMoveTarget =
|
||||
| { readonly type: "existing"; readonly directory: string }
|
||||
| { readonly type: "create"; readonly sourceDirectory: string }
|
||||
|
||||
type WorkspaceMoveBase = {
|
||||
/** The workspace menus that show this session's destinations. */
|
||||
readonly mounts: number
|
||||
/** The last attempt number handed out to a list, create, move, remove or recovery dialog. */
|
||||
readonly issued: number
|
||||
/** The project `directories` and `listing` belong to. */
|
||||
readonly projectID: string
|
||||
/** The server's worktrees for `projectID`, or undefined before a list settled. */
|
||||
readonly directories: readonly string[] | undefined
|
||||
/** The `worktree.list` in flight; `refresh` runs `worktree.refresh` once it settles. */
|
||||
readonly listing: { readonly attempt: number; readonly refresh: boolean } | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Moving one session to another worktree, shared by every workspace menu of the session. It lives while a menu is
|
||||
* mounted, a create, move or remove runs, or the recovery dialog shows. Results carry the attempt they answer, so a
|
||||
* result whose attempt the state no longer holds is stale.
|
||||
*/
|
||||
export type WorkspaceMoveState =
|
||||
| (WorkspaceMoveBase & { readonly status: "idle" })
|
||||
| (WorkspaceMoveBase & { readonly status: "creating"; readonly attempt: number })
|
||||
| (WorkspaceMoveBase & {
|
||||
readonly status: "moving"
|
||||
readonly attempt: number
|
||||
readonly destination: string
|
||||
/** Set when the destination is a worktree this controller created. */
|
||||
readonly created: CreatedWorktree | undefined
|
||||
/** The recovery dialog a retry runs from; undefined for the first move. */
|
||||
readonly dialog: RecoveryDialog | undefined
|
||||
})
|
||||
/** The recovery dialog offers to retry the move or delete the created worktree. */
|
||||
| (WorkspaceMoveBase & {
|
||||
readonly status: "recovering"
|
||||
readonly dialog: number
|
||||
readonly created: CreatedWorktree
|
||||
readonly reason: WorkspaceMoveFailure
|
||||
})
|
||||
| (WorkspaceMoveBase & {
|
||||
readonly status: "removing"
|
||||
readonly attempt: number
|
||||
readonly created: CreatedWorktree
|
||||
readonly dialog: RecoveryDialog
|
||||
})
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
/** The recovery dialog a retry or removal runs from. */
|
||||
export type RecoveryDialog =
|
||||
/** It keeps showing `reason` until the action settles. */
|
||||
| { readonly status: "open"; readonly attempt: number; readonly reason: WorkspaceMoveFailure }
|
||||
/** The user closed it while the action kept running; a late failure toasts instead. */
|
||||
| { readonly status: "dismissed" }
|
||||
|
||||
export type WorkspaceMoveEvent =
|
||||
/** A workspace menu mounted or unmounted. */
|
||||
| { readonly type: "mounted" }
|
||||
| { readonly type: "unmounted" }
|
||||
/** The destinations submenu opened: list the worktrees again, then let the server discover new ones. */
|
||||
| { readonly type: "menu.opened"; readonly projectID: string }
|
||||
/** The server reported that a project's worktrees changed. */
|
||||
| { readonly type: "worktree.updated"; readonly projectID: string }
|
||||
| { readonly type: "list.loaded"; readonly attempt: number; readonly items: readonly { readonly directory: string }[] }
|
||||
/** The list failed or timed out. */
|
||||
| { readonly type: "list.failed"; readonly attempt: number }
|
||||
/** `running` is the session's status when the user picked the destination. */
|
||||
| { readonly type: "move.requested"; readonly target: WorkspaceMoveTarget; readonly running: boolean }
|
||||
/** `running` is the session's status when the worktree was created. */
|
||||
| {
|
||||
readonly type: "worktree.created"
|
||||
readonly attempt: number
|
||||
readonly projectID: string
|
||||
readonly directory: string
|
||||
readonly running: boolean
|
||||
}
|
||||
| { readonly type: "create.failed"; readonly attempt: number; readonly error: string }
|
||||
| { readonly type: "move.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "move.failed"; readonly attempt: number; readonly error: string }
|
||||
/** The session started running before `session.move` was sent, so it was not sent. */
|
||||
| { readonly type: "move.blocked"; readonly attempt: number }
|
||||
/** The recovery dialog's Retry; `running` is the session's status at the click. */
|
||||
| { readonly type: "recovery.retry"; readonly attempt: number; readonly running: boolean }
|
||||
/** The recovery dialog's Delete worktree. */
|
||||
| { readonly type: "recovery.remove"; readonly attempt: number }
|
||||
| { readonly type: "remove.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "remove.failed"; readonly attempt: number; readonly error: string }
|
||||
/** The create, move or remove of `attempt` ran out of time. */
|
||||
| { readonly type: "op.timed-out"; readonly attempt: number }
|
||||
/** The recovery dialog closed, by the user or by the controller. */
|
||||
| { readonly type: "dialog.dismissed"; readonly attempt: number }
|
||||
/** The session's directory, as the server reports it; it changes when the session moves, from here or elsewhere. */
|
||||
| { readonly type: "session.moved"; readonly directory: string }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type WorkspaceMoveEffect =
|
||||
/** Starts the list's controller and timeout, then lists the project's worktrees. */
|
||||
| { readonly type: "list-worktrees"; readonly attempt: number; readonly projectID: string; readonly timeoutMs: number }
|
||||
/** Ends the list's controller and timeout. */
|
||||
| { readonly type: "abort-list"; readonly attempt: number }
|
||||
| { readonly type: "refresh-worktrees"; readonly projectID: string }
|
||||
/** Starts the attempt's controller and timeout, then creates a worktree from the session's project. */
|
||||
| {
|
||||
readonly type: "run-create"
|
||||
readonly attempt: number
|
||||
readonly sourceDirectory: string
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
/** Starts the attempt's controller and timeout, then moves the session unless it started running. */
|
||||
| {
|
||||
readonly type: "run-move"
|
||||
readonly attempt: number
|
||||
readonly directory: string
|
||||
/** Loads the destination's location first, as a newly created worktree is not in the client's cache yet. */
|
||||
readonly syncLocation: boolean
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
/** Starts the attempt's controller and timeout, then force-removes the created worktree. */
|
||||
| {
|
||||
readonly type: "run-remove"
|
||||
readonly attempt: number
|
||||
readonly projectID: string
|
||||
readonly directory: string
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
/** Ends the attempt's controller and timeout. */
|
||||
| { readonly type: "abort-op"; readonly attempt: number }
|
||||
| { readonly type: "open-dialog"; readonly attempt: number }
|
||||
| { readonly type: "close-dialog"; readonly attempt: number }
|
||||
/** Reports a failure no dialog shows: a move into an existing worktree, or one the user stopped watching. */
|
||||
| { readonly type: "toast"; readonly kind: "move" | "remove"; readonly reason: WorkspaceMoveFailure }
|
||||
|
||||
export type WorkspaceMoveTransition = {
|
||||
readonly state: WorkspaceMoveState
|
||||
readonly effects: readonly WorkspaceMoveEffect[]
|
||||
}
|
||||
|
||||
/** A fresh state per controller: never shared, so no two controllers can write into one object. */
|
||||
export function createWorkspaceMoveState(projectID: string): WorkspaceMoveState {
|
||||
return { status: "idle", mounts: 0, issued: 0, projectID, directories: undefined, listing: undefined }
|
||||
}
|
||||
|
||||
const NONE: readonly WorkspaceMoveEffect[] = []
|
||||
|
||||
const DISMISSED: RecoveryDialog = { status: "dismissed" }
|
||||
|
||||
type Live = Exclude<WorkspaceMoveState, { status: "disposed" }>
|
||||
|
||||
type Step = Exclude<WorkspaceMoveEvent, { type: "disposed" }>
|
||||
|
||||
export function transitionWorkspaceMove(state: WorkspaceMoveState, event: WorkspaceMoveEvent): WorkspaceMoveTransition {
|
||||
if (state.status === "disposed") return { state, effects: NONE }
|
||||
|
||||
if (event.type === "disposed") {
|
||||
const dialog = openDialog(state)
|
||||
|
||||
return {
|
||||
state: { status: "disposed" },
|
||||
effects: [
|
||||
...(state.status === "creating" || state.status === "moving" || state.status === "removing"
|
||||
? [{ type: "abort-op", attempt: state.attempt } as const]
|
||||
: NONE),
|
||||
...abortList(state.listing),
|
||||
...(dialog === undefined ? NONE : [{ type: "close-dialog", attempt: dialog } as const]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const next = step(state, event)
|
||||
|
||||
return next.state === state ? next : release(next)
|
||||
}
|
||||
|
||||
/** What a workspace menu shows. */
|
||||
export type WorkspaceMenuView = {
|
||||
/** The trigger and every item take no input while a move runs, the dialog shows, or the session runs. */
|
||||
readonly disabled: boolean
|
||||
/** Offer the project's root checkout: the session is somewhere else. */
|
||||
readonly showLocal: boolean
|
||||
/** The project's other worktrees, without the one that holds the session's directory. */
|
||||
readonly workspaces: readonly string[]
|
||||
}
|
||||
|
||||
export function workspaceMenuView(
|
||||
state: WorkspaceMoveState,
|
||||
directory: string,
|
||||
project: WorkspaceProject & { readonly id: string },
|
||||
running: boolean,
|
||||
): WorkspaceMenuView {
|
||||
const listed =
|
||||
state.status !== "disposed" && state.projectID === project.id && state.directories !== undefined
|
||||
? state.directories
|
||||
: workspaceDirectories(project)
|
||||
|
||||
const others = listed.filter(
|
||||
(item, index) =>
|
||||
!sameDirectory(project.worktree, item) &&
|
||||
listed.findIndex((candidate) => sameDirectory(candidate, item)) === index,
|
||||
)
|
||||
|
||||
const current = others.find((item) => containsDirectory(item, directory)) ?? directory
|
||||
|
||||
return {
|
||||
disabled: state.status !== "idle" || running,
|
||||
showLocal: !sameDirectory(directory, project.worktree),
|
||||
workspaces: others.filter((item) => !sameDirectory(item, current)),
|
||||
}
|
||||
}
|
||||
|
||||
/** What the recovery dialog shows. */
|
||||
export type WorkspaceDialogView = {
|
||||
/** The created worktree. */
|
||||
readonly directory: string
|
||||
/** The latest failure, kept while a retry or removal runs. */
|
||||
readonly reason: WorkspaceMoveFailure
|
||||
readonly running: boolean
|
||||
readonly retrying: boolean
|
||||
readonly removing: boolean
|
||||
/** Retry waits for the session to stop running and for the action in flight. */
|
||||
readonly retryDisabled: boolean
|
||||
readonly removeDisabled: boolean
|
||||
}
|
||||
|
||||
/** What the recovery dialog of `attempt` shows, or undefined once it closed. */
|
||||
export function workspaceDialogView(
|
||||
state: WorkspaceMoveState,
|
||||
attempt: number,
|
||||
running: boolean,
|
||||
): WorkspaceDialogView | undefined {
|
||||
if (state.status === "recovering" && state.dialog === attempt)
|
||||
return view(state.created.directory, state.reason, running, { retrying: false, removing: false })
|
||||
|
||||
if (state.status !== "moving" && state.status !== "removing") return
|
||||
const dialog = state.dialog
|
||||
|
||||
if (dialog?.status !== "open" || dialog.attempt !== attempt) return
|
||||
|
||||
if (state.status === "removing")
|
||||
return view(state.created.directory, dialog.reason, running, { retrying: false, removing: true })
|
||||
|
||||
return view(state.destination, dialog.reason, running, { retrying: true, removing: false })
|
||||
}
|
||||
|
||||
function view(
|
||||
directory: string,
|
||||
reason: WorkspaceMoveFailure,
|
||||
running: boolean,
|
||||
busy: { readonly retrying: boolean; readonly removing: boolean },
|
||||
): WorkspaceDialogView {
|
||||
const pending = busy.retrying || busy.removing
|
||||
|
||||
return {
|
||||
directory,
|
||||
reason,
|
||||
running,
|
||||
retrying: busy.retrying,
|
||||
removing: busy.removing,
|
||||
retryDisabled: pending || running,
|
||||
removeDisabled: pending,
|
||||
}
|
||||
}
|
||||
|
||||
function step(state: Live, event: Step): WorkspaceMoveTransition {
|
||||
if (event.type === "mounted") return { state: { ...state, mounts: state.mounts + 1 }, effects: NONE }
|
||||
|
||||
if (event.type === "unmounted") return { state: { ...state, mounts: Math.max(0, state.mounts - 1) }, effects: NONE }
|
||||
|
||||
if (event.type === "menu.opened") {
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
issued: attempt,
|
||||
projectID: event.projectID,
|
||||
directories: event.projectID === state.projectID ? state.directories : undefined,
|
||||
listing: { attempt, refresh: true },
|
||||
},
|
||||
effects: [
|
||||
...abortList(state.listing),
|
||||
{ type: "list-worktrees", attempt, projectID: event.projectID, timeoutMs: WORKSPACE_LIST_TIMEOUT_MS },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "worktree.updated") {
|
||||
if (event.projectID !== state.projectID) return { state, effects: NONE }
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: { ...state, issued: attempt, listing: { attempt, refresh: state.listing?.refresh ?? false } },
|
||||
effects: [
|
||||
...abortList(state.listing),
|
||||
{ type: "list-worktrees", attempt, projectID: state.projectID, timeoutMs: WORKSPACE_LIST_TIMEOUT_MS },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "list.loaded" || event.type === "list.failed") return listed(state, event)
|
||||
|
||||
if (event.type === "session.moved") {
|
||||
// The session reached the created worktree some other way, e.g. from another window.
|
||||
if (state.status !== "recovering" || !sameDirectory(state.created.directory, event.directory))
|
||||
return { state, effects: NONE }
|
||||
|
||||
return { state: idle(state), effects: [{ type: "close-dialog", attempt: state.dialog }] }
|
||||
}
|
||||
|
||||
if (state.status === "idle") return requested(state, event)
|
||||
|
||||
if (state.status === "creating") return creating(state, event)
|
||||
|
||||
if (state.status === "moving") return moving(state, event)
|
||||
|
||||
if (state.status === "recovering") return recovering(state, event)
|
||||
|
||||
return removing(state, event)
|
||||
}
|
||||
|
||||
function listed(
|
||||
state: Live,
|
||||
event: Extract<WorkspaceMoveEvent, { type: "list.loaded" | "list.failed" }>,
|
||||
): WorkspaceMoveTransition {
|
||||
const listing = state.listing
|
||||
|
||||
if (listing?.attempt !== event.attempt) return { state, effects: NONE }
|
||||
const effects: WorkspaceMoveEffect[] = [{ type: "abort-list", attempt: event.attempt }]
|
||||
|
||||
if (event.type === "list.failed") return { state: { ...state, listing: undefined }, effects }
|
||||
|
||||
if (listing.refresh) effects.push({ type: "refresh-worktrees", projectID: state.projectID })
|
||||
const next = { ...state, listing: undefined, directories: event.items.map((item) => item.directory) }
|
||||
|
||||
// The created worktree is gone, e.g. deleted from Settings. Only a list issued after the dialog opened can say so: an
|
||||
// older one may predate the worktree.
|
||||
const gone =
|
||||
state.status === "recovering" &&
|
||||
event.attempt > state.dialog &&
|
||||
state.created.projectID === state.projectID &&
|
||||
!event.items.some((item) => sameDirectory(item.directory, state.created.directory))
|
||||
|
||||
if (!gone) return { state: next, effects }
|
||||
|
||||
return { state: idle(next), effects: [...effects, { type: "close-dialog", attempt: state.dialog }] }
|
||||
}
|
||||
|
||||
function requested(state: Extract<Live, { status: "idle" }>, event: Step): WorkspaceMoveTransition {
|
||||
if (event.type !== "move.requested" || event.running) return { state, effects: NONE }
|
||||
const attempt = state.issued + 1
|
||||
const target = event.target
|
||||
|
||||
if (target.type === "create")
|
||||
return {
|
||||
state: { ...state, status: "creating", issued: attempt, attempt },
|
||||
effects: [
|
||||
{
|
||||
type: "run-create",
|
||||
attempt,
|
||||
sourceDirectory: target.sourceDirectory,
|
||||
timeoutMs: WORKSPACE_CREATE_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
status: "moving",
|
||||
issued: attempt,
|
||||
attempt,
|
||||
destination: target.directory,
|
||||
created: undefined,
|
||||
dialog: undefined,
|
||||
},
|
||||
effects: [
|
||||
{
|
||||
type: "run-move",
|
||||
attempt,
|
||||
directory: target.directory,
|
||||
syncLocation: false,
|
||||
timeoutMs: WORKSPACE_MOVE_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function creating(state: Extract<Live, { status: "creating" }>, event: Step): WorkspaceMoveTransition {
|
||||
if (!("attempt" in event) || event.attempt !== state.attempt) return { state, effects: NONE }
|
||||
const abort: WorkspaceMoveEffect = { type: "abort-op", attempt: state.attempt }
|
||||
|
||||
if (event.type === "worktree.created") {
|
||||
const attempt = state.issued + 1
|
||||
const created = { projectID: event.projectID, directory: event.directory }
|
||||
|
||||
// The session started running while the worktree was created: keep it where it runs, and offer the worktree.
|
||||
if (event.running)
|
||||
return {
|
||||
state: {
|
||||
...base(state),
|
||||
status: "recovering",
|
||||
issued: attempt,
|
||||
dialog: attempt,
|
||||
created,
|
||||
reason: { type: "running" },
|
||||
},
|
||||
effects: [abort, { type: "open-dialog", attempt }],
|
||||
}
|
||||
|
||||
return {
|
||||
state: {
|
||||
...base(state),
|
||||
status: "moving",
|
||||
issued: attempt,
|
||||
attempt,
|
||||
destination: event.directory,
|
||||
created,
|
||||
dialog: undefined,
|
||||
},
|
||||
effects: [
|
||||
abort,
|
||||
{
|
||||
type: "run-move",
|
||||
attempt,
|
||||
directory: event.directory,
|
||||
syncLocation: true,
|
||||
timeoutMs: WORKSPACE_MOVE_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "create.failed")
|
||||
return {
|
||||
state: idle(state),
|
||||
effects: [abort, { type: "toast", kind: "move", reason: { type: "failed", error: event.error } }],
|
||||
}
|
||||
|
||||
if (event.type === "op.timed-out")
|
||||
return { state: idle(state), effects: [abort, { type: "toast", kind: "move", reason: { type: "timed-out" } }] }
|
||||
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
|
||||
function moving(state: Extract<Live, { status: "moving" }>, event: Step): WorkspaceMoveTransition {
|
||||
const dialog = state.dialog
|
||||
|
||||
if (event.type === "dialog.dismissed") {
|
||||
if (dialog?.status !== "open" || event.attempt !== dialog.attempt) return { state, effects: NONE }
|
||||
|
||||
// The retry keeps running; a late failure toasts instead of opening the dialog again.
|
||||
return { state: { ...state, dialog: DISMISSED }, effects: NONE }
|
||||
}
|
||||
|
||||
if (!("attempt" in event) || event.attempt !== state.attempt) return { state, effects: NONE }
|
||||
const abort: WorkspaceMoveEffect = { type: "abort-op", attempt: state.attempt }
|
||||
|
||||
if (event.type === "move.succeeded") return { state: idle(state), effects: [abort, ...closeDialog(dialog)] }
|
||||
|
||||
const reason = failure(event)
|
||||
|
||||
if (!reason) return { state, effects: NONE }
|
||||
|
||||
if (!state.created || dialog?.status === "dismissed")
|
||||
return { state: idle(state), effects: [abort, { type: "toast", kind: "move", reason }] }
|
||||
|
||||
// A retry from the open dialog shows its failure in place.
|
||||
if (dialog?.status === "open")
|
||||
return {
|
||||
state: { ...base(state), status: "recovering", dialog: dialog.attempt, created: state.created, reason },
|
||||
effects: [abort],
|
||||
}
|
||||
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: { ...base(state), status: "recovering", issued: attempt, dialog: attempt, created: state.created, reason },
|
||||
effects: [abort, { type: "open-dialog", attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
function recovering(state: Extract<Live, { status: "recovering" }>, event: Step): WorkspaceMoveTransition {
|
||||
if (!("attempt" in event) || event.attempt !== state.dialog) return { state, effects: NONE }
|
||||
|
||||
// Keep worktree, Escape, or the dialog closing for any other reason: the worktree stays, the session stays.
|
||||
if (event.type === "dialog.dismissed") return { state: idle(state), effects: NONE }
|
||||
|
||||
if (event.type === "recovery.retry") {
|
||||
if (event.running) return { state, effects: NONE }
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
...base(state),
|
||||
status: "moving",
|
||||
issued: attempt,
|
||||
attempt,
|
||||
destination: state.created.directory,
|
||||
created: state.created,
|
||||
dialog: { status: "open", attempt: state.dialog, reason: state.reason },
|
||||
},
|
||||
effects: [
|
||||
{
|
||||
type: "run-move",
|
||||
attempt,
|
||||
directory: state.created.directory,
|
||||
syncLocation: true,
|
||||
timeoutMs: WORKSPACE_MOVE_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type !== "recovery.remove") return { state, effects: NONE }
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
...base(state),
|
||||
status: "removing",
|
||||
issued: attempt,
|
||||
attempt,
|
||||
created: state.created,
|
||||
dialog: { status: "open", attempt: state.dialog, reason: state.reason },
|
||||
},
|
||||
effects: [
|
||||
{
|
||||
type: "run-remove",
|
||||
attempt,
|
||||
projectID: state.created.projectID,
|
||||
directory: state.created.directory,
|
||||
timeoutMs: WORKSPACE_REMOVE_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function removing(state: Extract<Live, { status: "removing" }>, event: Step): WorkspaceMoveTransition {
|
||||
const dialog = state.dialog
|
||||
|
||||
if (event.type === "dialog.dismissed") {
|
||||
if (dialog.status !== "open" || event.attempt !== dialog.attempt) return { state, effects: NONE }
|
||||
|
||||
return { state: { ...state, dialog: DISMISSED }, effects: NONE }
|
||||
}
|
||||
|
||||
if (!("attempt" in event) || event.attempt !== state.attempt) return { state, effects: NONE }
|
||||
const abort: WorkspaceMoveEffect = { type: "abort-op", attempt: state.attempt }
|
||||
const directory = state.created.directory
|
||||
|
||||
if (event.type === "remove.succeeded")
|
||||
return {
|
||||
state: idle({ ...state, directories: state.directories?.filter((item) => !sameDirectory(item, directory)) }),
|
||||
effects: [abort, ...closeDialog(dialog)],
|
||||
}
|
||||
|
||||
const reason = failure(event)
|
||||
|
||||
if (!reason) return { state, effects: NONE }
|
||||
|
||||
if (dialog.status === "dismissed")
|
||||
return { state: idle(state), effects: [abort, { type: "toast", kind: "remove", reason }] }
|
||||
|
||||
return {
|
||||
state: { ...base(state), status: "recovering", dialog: dialog.attempt, created: state.created, reason },
|
||||
effects: [abort],
|
||||
}
|
||||
}
|
||||
|
||||
// The controller ends once nothing uses it: no menu is mounted and no create, move, remove or dialog is open.
|
||||
function release(transition: WorkspaceMoveTransition): WorkspaceMoveTransition {
|
||||
const state = transition.state
|
||||
|
||||
if (state.status !== "idle" || state.mounts > 0) return transition
|
||||
|
||||
return { state: { status: "disposed" }, effects: [...transition.effects, ...abortList(state.listing)] }
|
||||
}
|
||||
|
||||
// Attempts are unique, so a failure that matches the state's attempt always answers the operation in flight.
|
||||
function failure(event: Step): WorkspaceMoveFailure | undefined {
|
||||
if (event.type === "move.failed" || event.type === "remove.failed") return { type: "failed", error: event.error }
|
||||
|
||||
if (event.type === "move.blocked") return { type: "running" }
|
||||
|
||||
if (event.type === "op.timed-out") return { type: "timed-out" }
|
||||
}
|
||||
|
||||
function base(state: Live): WorkspaceMoveBase {
|
||||
return {
|
||||
mounts: state.mounts,
|
||||
issued: state.issued,
|
||||
projectID: state.projectID,
|
||||
directories: state.directories,
|
||||
listing: state.listing,
|
||||
}
|
||||
}
|
||||
|
||||
function idle(state: Live): WorkspaceMoveState {
|
||||
return { ...base(state), status: "idle" }
|
||||
}
|
||||
|
||||
function openDialog(state: Live) {
|
||||
if (state.status === "recovering") return state.dialog
|
||||
|
||||
if ((state.status === "moving" || state.status === "removing") && state.dialog?.status === "open")
|
||||
return state.dialog.attempt
|
||||
}
|
||||
|
||||
function closeDialog(dialog: RecoveryDialog | undefined): readonly WorkspaceMoveEffect[] {
|
||||
return dialog?.status === "open" ? [{ type: "close-dialog", attempt: dialog.attempt }] : NONE
|
||||
}
|
||||
|
||||
function abortList(listing: WorkspaceMoveBase["listing"]): readonly WorkspaceMoveEffect[] {
|
||||
return listing ? [{ type: "abort-list", attempt: listing.attempt }] : NONE
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue