fix(app): give composer recovery, queue mutations, row stops and /reload explicit lifecycles (#62097)

This commit is contained in:
Luke Parker 2026-11-05 09:43:40 -06:00 • committed by GitHub
parent 121d822c07
commit 17100fc529
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 1299 additions and 320 deletions

View file

@ -1371,6 +1371,13 @@ test("/reload reloads the server's configuration once and reports it", async ({
await expect(page.locator('[data-suggestion-id="config.reload"]')).toHaveAttribute("data-active", "")
await editor.press("Enter")
await expect(page.getByText("Reloading configuration…", { exact: true })).toBeVisible()
// A second /reload while the first runs joins it: no second request and no second toast.
await expect(editor).toBeEmpty()
await editor.fill("/reload")
await expect(page.locator('[data-suggestion-id="config.reload"]')).toHaveAttribute("data-active", "")
await editor.press("Enter")
await expect(editor).toBeEmpty()
await expect(page.getByText("Reloading configuration…", { exact: true })).toHaveCount(1)
reloaded.resolve()
await expect(page.getByText("Configuration reloaded", { exact: true })).toBeVisible()
await expect(page.getByText("Reloading configuration…", { exact: true })).toBeHidden()

View file

@ -1155,7 +1155,9 @@ test.describe("background shortcut", () => {
const capsule = page.getByRole("button", { name: "1 shell", exact: true, includeHidden: true })
const list = page.getByRole("menu", { name: "1 shell", exact: true })
const closed = (await capsule.boundingBox())!
const inset = (await capsule.locator('[data-component="session-progress-indicator-v2"]').boundingBox())!.x - closed.x
const inset =
(await capsule.locator('[data-component="session-progress-indicator-v2"]').boundingBox())!.x - closed.x
await capsule.click()
// Right placement shares the capsule's end edge and mirrors its inset there; centre placement shares its centre.
@ -1400,13 +1402,23 @@ test.describe("background shortcut", () => {
await interrupt
await expect(list).toBeVisible()
const kill = page.waitForRequest(
(request) => request.method() === "DELETE" && new URL(request.url()).pathname === "/api/shell/shell_backgrounded",
)
const kill = await holdRoute(page, /\/api\/shell\/shell_backgrounded(\?|$)/, { method: "DELETE" })
const shellRow = list.getByRole("menuitem", { name: /sleep 120/ })
await list.getByRole("menuitem", { name: /sleep 120/ }).hover()
await shellRow.hover()
await page.keyboard.press("Delete")
await kill
await kill.arrived
// A second Delete, or a click on the row's stop button, while the first stop runs sends nothing more.
const stopping = shellRow.getByRole("button", { name: "Kill shell command", exact: true })
await expect(stopping).toHaveAttribute("aria-busy", "true")
await page.keyboard.press("Delete")
// aria-disabled leaves a real click through, which Playwright's actionability check would refuse.
await stopping.click({ force: true })
await expect(stopping).toHaveAttribute("aria-busy", "true")
expect(kill.requests).toHaveLength(1)
kill.release()
await expect(stopping).not.toHaveAttribute("aria-busy")
expect(kill.requests).toHaveLength(1)
await page.keyboard.press("Escape")
await expect(list).toHaveCount(0)
await expect(backgroundCard).toContainText("Background task (background)")

View file

@ -11,6 +11,7 @@ import { useServerSDK } from "@/runtime/server/client"
import { formatServerError } from "@/runtime/server/errors"
import { showToast } from "@/shell/notifications/toast"
import { toaster } from "@opencode/ui/toast"
import { createConfigReloadState, transitionConfigReload, type ConfigReloadEvent } from "@/composer/reload-machine"
const withCategory = (category: string) => {
return (option: Omit<CommandOption, "category">): CommandOption => ({
@ -45,24 +46,43 @@ export const useComposerCommands = (input: { model?: ModelSelection } = {}) => {
// Mirrors the TUI's `/reload`. The server rebuilds every loaded location and announces the changed agents,
// commands, models and skills, so the data layer refreshes them without restarting the app.
const reloadConfig = () => {
const pending = showToast({
variant: "loading",
title: language.t("command.config.reload.pending"),
persistent: true,
})
// The result still reports after this composer unmounts: toasts are app-wide.
let reloadState = createConfigReloadState()
let reloadToast: number | undefined
void sdk.api.location
.reload()
.then(() => showToast({ variant: "success", title: language.t("command.config.reload.done") }))
.catch((error) =>
showToast({
variant: "error",
title: language.t("command.config.reload.failed"),
description: formatServerError(error, language.t),
}),
)
.finally(() => toaster.dismiss(pending))
const reloadConfig = (event: ConfigReloadEvent) => {
const next = transitionConfigReload(reloadState, event)
reloadState = next.state
next.effects.forEach((effect) => {
if (effect.type === "reload.run")
return void sdk.api.location.reload().then(
() => reloadConfig({ type: "reload.succeeded", attempt: effect.attempt }),
(cause: unknown) => reloadConfig({ type: "reload.failed", attempt: effect.attempt, cause }),
)
if (effect.type === "toast.pending.show")
return void (reloadToast = showToast({
variant: "loading",
title: language.t("command.config.reload.pending"),
persistent: true,
}))
if (effect.type === "toast.pending.dismiss") {
if (reloadToast !== undefined) toaster.dismiss(reloadToast)
reloadToast = undefined
return
}
if (effect.type === "toast.succeeded")
return void showToast({ variant: "success", title: language.t("command.config.reload.done") })
showToast({
variant: "error",
title: language.t("command.config.reload.failed"),
description: formatServerError(effect.cause, language.t),
})
})
}
const chooseModel = () => {
@ -124,7 +144,7 @@ export const useComposerCommands = (input: { model?: ModelSelection } = {}) => {
title: language.t("command.config.reload"),
description: language.t("command.config.reload.description"),
slash: "reload",
onSelect: reloadConfig,
onSelect: () => reloadConfig({ type: "reload.requested" }),
}),
agentCommand({
id: "agent.cycle",

View file

@ -0,0 +1,51 @@
/**
* `/reload`: one server-wide configuration reload at a time. The request queue already ends a reload whose server
* stops answering, and the reply carries no body, so `reloading` always settles.
*/
export type ConfigReloadState =
| { readonly status: "idle"; readonly issued: number }
| { readonly status: "reloading"; readonly attempt: number }
export type ConfigReloadEvent =
| { readonly type: "reload.requested" }
| { readonly type: "reload.succeeded"; readonly attempt: number }
| { readonly type: "reload.failed"; readonly attempt: number; readonly cause: unknown }
export type ConfigReloadEffect =
| { readonly type: "reload.run"; readonly attempt: number }
| { readonly type: "toast.pending.show" }
| { readonly type: "toast.pending.dismiss" }
| { readonly type: "toast.succeeded" }
| { readonly type: "toast.failed"; readonly cause: unknown }
export type ConfigReloadTransition = {
readonly state: ConfigReloadState
readonly effects: readonly ConfigReloadEffect[]
}
export function createConfigReloadState(): ConfigReloadState {
return { status: "idle", issued: 0 }
}
export function transitionConfigReload(state: ConfigReloadState, event: ConfigReloadEvent): ConfigReloadTransition {
if (event.type === "reload.requested") {
// A second `/reload` while one runs joins it: the server is already rebuilding every location.
if (state.status === "reloading") return { state, effects: [] }
const attempt = state.issued + 1
return {
state: { status: "reloading", attempt },
effects: [{ type: "toast.pending.show" }, { type: "reload.run", attempt }],
}
}
if (state.status !== "reloading" || state.attempt !== event.attempt) return { state, effects: [] }
return {
state: { status: "idle", issued: state.attempt },
effects: [
{ type: "toast.pending.dismiss" },
event.type === "reload.succeeded" ? { type: "toast.succeeded" } : { type: "toast.failed", cause: event.cause },
],
}
}

View file

@ -94,7 +94,12 @@
visibility: hidden;
}
[data-component="menu-v2-item"][data-stoppable]:is(:hover, [data-highlighted]) {
/* A row whose Stop is in flight keeps showing its loader until the work leaves the list or the Stop settles. */
[data-component="menu-v2-item"][data-stoppable]:is(
:hover,
[data-highlighted],
:has([data-slot="session-activity-stop"][aria-disabled="true"])
) {
[data-slot="session-activity-stop"] {
visibility: visible;
}

View file

@ -1,5 +1,6 @@
import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { Loader } from "@opencode/ui/loader"
import { Menu } from "@opencode/ui/menu"
import { MenuScroll } from "@opencode/ui/menu-scroll"
import { SessionProgressIndicatorV2 } from "@opencode/session-ui/v2/session-progress-indicator-v2"
@ -117,10 +118,12 @@ export function SessionActivityChips(props: {
if ((event.key !== "Delete" && event.key !== "Backspace") || !stoppable(item)) return
event.preventDefault()
void props.onStop(item)
panel.stop(item)
},
})
const rowStopping = (item: SessionActivityItem) => view().stoppingKeys[item.key] !== undefined
// One clock for every row, ticking only while the panel is open and something still runs.
const [now, setNow] = createSignal(Date.now())
const clockRunning = createMemo(() => view().clockRunning)
@ -155,8 +158,10 @@ export function SessionActivityChips(props: {
variant="ghost-muted"
tabIndex={-1}
data-slot="session-activity-stop"
icon={<Icon name="outline-xmark" size="small" />}
icon={rowStopping(item) ? <Loader /> : <Icon name="outline-xmark" size="small" />}
aria-label={language.t(item.type === "shell" ? "session.running.stop.shell" : "session.running.stop.subagent")}
aria-disabled={rowStopping(item) || undefined}
aria-busy={rowStopping(item) || undefined}
onPointerDown={(event) => {
event.preventDefault()
event.stopPropagation()
@ -164,7 +169,7 @@ export function SessionActivityChips(props: {
onPointerUp={(event) => event.stopPropagation()}
onClick={(event) => {
event.stopPropagation()
void props.onStop(item)
panel.stop(item)
}}
/>
</Show>
@ -271,7 +276,7 @@ export function SessionActivityChips(props: {
data-slot="session-activity-shell-stop"
closeOnSelect={false}
aria-disabled={view().stopDisabled || undefined}
onSelect={panel.stop}
onSelect={() => panel.stop()}
>
{language.t(
view().stopping ? "session.activity.shell.stopping" : "session.activity.shell.stop",

View file

@ -0,0 +1,127 @@
import { expect, test } from "bun:test"
import type { WorktreeDirectory } from "@opencode/client/promise"
import {
createLocationMissingState,
selectLocationMissingView,
transitionLocationMissing,
type LocationMissingEffect,
type LocationMissingEvent,
type LocationMissingState,
} from "./location-missing-machine"
const missing = "/repo/.worktrees/gone"
const sibling: WorktreeDirectory = { directory: "/repo/.worktrees/sibling", strategy: "git" }
function replay(events: LocationMissingEvent[], from = createLocationMissingState([])) {
return events.reduce<{ state: LocationMissingState; effects: readonly LocationMissingEffect[] }>(
(current, event) => transitionLocationMissing(current.state, event),
{ state: from, effects: [] },
)
}
const attempt = (state: LocationMissingState) => ("attempt" in state ? state.attempt : -1)
test("an open directory picker refuses a second picker or a worktree move, and its answer after unmount moves nothing", () => {
const picking = replay([{ type: "choose.requested" }])
expect(picking.effects).toEqual([{ type: "picker.open", attempt: 1 }])
expect(selectLocationMissingView(picking.state, missing).disabled).toBe(true)
expect(transitionLocationMissing(picking.state, { type: "choose.requested" }).state).toBe(picking.state)
expect(transitionLocationMissing(picking.state, { type: "menu.toggled", open: true }).state).toBe(picking.state)
expect(transitionLocationMissing(picking.state, { type: "move.worktree", directory: sibling.directory }).state).toBe(
picking.state,
)
const disposed = transitionLocationMissing(picking.state, { type: "disposed" })
const late = transitionLocationMissing(disposed.state, {
type: "picker.settled",
attempt: attempt(picking.state),
directory: "/elsewhere",
dialogOpen: false,
})
expect(late.effects).toEqual([])
})
test("a picked folder moves the session once", () => {
const picked = replay([
{ type: "choose.requested" },
{ type: "picker.settled", attempt: 1, directory: "/elsewhere", dialogOpen: false },
])
expect(picked.effects).toEqual([{ type: "move.run", attempt: 2, directory: "/elsewhere" }])
expect(selectLocationMissingView(picked.state, missing).pendingDirectory).toBe(true)
expect(
transitionLocationMissing(picked.state, {
type: "picker.settled",
attempt: 1,
directory: "/elsewhere",
dialogOpen: false,
}).state,
).toBe(picked.state)
})
test("a move the server accepted keeps the controls busy until the notice unmounts, or for its settle bound", () => {
const moving = replay([{ type: "move.worktree" }])
expect(moving.effects).toEqual([{ type: "move.run", attempt: 1 }])
const moved = transitionLocationMissing(moving.state, { type: "move.succeeded", attempt: 1 })
expect(moved.effects).toEqual([{ type: "timer.start", attempt: 1, phase: "moved" }])
expect(selectLocationMissingView(moved.state, missing)).toMatchObject({ pendingWorktree: true, disabled: true })
expect(transitionLocationMissing(moved.state, { type: "move.worktree" }).state).toBe(moved.state)
expect(transitionLocationMissing(moved.state, { type: "choose.requested" }).state).toBe(moved.state)
const settled = transitionLocationMissing(moved.state, { type: "move.settle-timed-out", attempt: 1 })
expect(settled.state).toMatchObject({ status: "idle" })
expect(selectLocationMissingView(settled.state, missing).disabled).toBe(false)
})
test("the worktree menu shows the worktrees it already has, and a stalled load ends with an error", () => {
const cached = replay([{ type: "menu.toggled", open: true }], createLocationMissingState([sibling]))
expect(cached.effects).toEqual([
{ type: "worktrees.load", attempt: 1 },
{ type: "timer.start", attempt: 1, phase: "menu-loading" },
])
expect(selectLocationMissingView(cached.state, missing)).toMatchObject({
menuOpen: true,
menuLoading: false,
visibleWorktrees: [sibling],
})
const empty = replay([{ type: "menu.toggled", open: true }])
expect(selectLocationMissingView(empty.state, missing).menuLoading).toBe(true)
const timedOut = transitionLocationMissing(empty.state, { type: "worktrees.timed-out", attempt: 1 })
expect(timedOut.state).toMatchObject({ status: "menu-ready" })
expect(timedOut.effects).toEqual([{ type: "timer.cancel" }, { type: "toast.worktrees-failed" }])
expect(
transitionLocationMissing(timedOut.state, { type: "worktrees.loaded", attempt: 1, items: [sibling] }).state,
).toBe(timedOut.state)
})
test("a cancelled pick or failed move returns focus to Choose directory once no dialog covers it", () => {
const cancelled = replay([
{ type: "choose.requested" },
{ type: "picker.settled", attempt: 1, directory: undefined, dialogOpen: false },
])
expect(cancelled.effects).toEqual([{ type: "focus.choose" }])
const failed = replay([
{ type: "move.worktree" },
{ type: "move.failed", attempt: 1, error: new Error("denied"), dialogOpen: true },
])
expect(failed.effects).toEqual([{ type: "toast.move-failed", error: new Error("denied") }])
expect(transitionLocationMissing(failed.state, { type: "dialog.changed", open: false }).effects).toEqual([
{ type: "focus.choose" },
])
})

View file

@ -0,0 +1,227 @@
import type { WorktreeDirectory } from "@opencode/client/promise"
import { getFilename, sameDirectory } from "@opencode/util/path"
/** The menu shows what it already has, with an error, once a worktree refresh and list take this long. */
export const WORKTREES_LOAD_TIMEOUT_MS = 15_000
/** A move the server accepted waits this long for the session's new Location to unmount the notice. */
export const LOCATION_MOVE_SETTLE_TIMEOUT_MS = 5_000
export type LocationMissingSource = "worktree" | "directory"
type LocationMissingBase = {
readonly issued: number
/** The project's worktrees as last loaded, shown at once when the menu opens. */
readonly worktrees: readonly WorktreeDirectory[]
}
/**
* Recovering a session whose folder is gone. `picking`: the directory picker is open. `moving`: the worktree or move
* request runs. `moved`: the server moved the session and the notice waits for the new Location to replace it.
* `restoreFocus`: a cancelled or failed move returns focus to Choose directory once the dialog over it closes.
*/
export type LocationMissingState =
| (LocationMissingBase & { readonly status: "idle"; readonly restoreFocus: boolean })
| (LocationMissingBase & { readonly status: "menu-loading"; readonly attempt: number; readonly search: string })
| (LocationMissingBase & { readonly status: "menu-ready"; readonly search: string })
| (LocationMissingBase & { readonly status: "picking"; readonly attempt: number })
| (LocationMissingBase & {
readonly status: "moving" | "moved"
readonly attempt: number
readonly source: LocationMissingSource
})
| { readonly status: "disposed" }
export type LocationMissingEvent =
| { readonly type: "menu.toggled"; readonly open: boolean }
| { readonly type: "search.changed"; readonly search: string }
| {
readonly type: "worktrees.loaded"
readonly attempt: number
readonly items: readonly WorktreeDirectory[] | undefined
}
| { readonly type: "worktrees.timed-out"; readonly attempt: number }
| { readonly type: "choose.requested" }
| {
readonly type: "picker.settled"
readonly attempt: number
readonly directory: string | undefined
readonly dialogOpen: boolean
}
| { readonly type: "move.worktree"; readonly directory?: string }
| { readonly type: "move.succeeded"; readonly attempt: number }
| { readonly type: "move.failed"; readonly attempt: number; readonly error: unknown; readonly dialogOpen: boolean }
| { readonly type: "move.settle-timed-out"; readonly attempt: number }
| { readonly type: "dialog.changed"; readonly open: boolean }
| { readonly type: "disposed" }
export type LocationMissingEffect =
| { readonly type: "worktrees.load"; readonly attempt: number }
| { readonly type: "picker.open"; readonly attempt: number }
/** Without `directory`, the move first creates a worktree from the project's checkout. */
| { readonly type: "move.run"; readonly attempt: number; readonly directory?: string }
| { readonly type: "timer.start"; readonly attempt: number; readonly phase: "menu-loading" | "moved" }
| { readonly type: "timer.cancel" }
| { readonly type: "focus.choose" }
| { readonly type: "toast.worktrees-failed" }
| { readonly type: "toast.move-failed"; readonly error: unknown }
export type LocationMissingTransition = {
readonly state: LocationMissingState
readonly effects: readonly LocationMissingEffect[]
}
const TIMER_CANCEL: LocationMissingEffect = { type: "timer.cancel" }
export function createLocationMissingState(worktrees: readonly WorktreeDirectory[]): LocationMissingState {
return { status: "idle", issued: 0, worktrees, restoreFocus: false }
}
export function transitionLocationMissing(
state: LocationMissingState,
event: LocationMissingEvent,
): LocationMissingTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed")
return changed(
{ status: "disposed" },
state.status === "menu-loading" || state.status === "moved" ? [TIMER_CANCEL] : [],
)
const base = { issued: state.issued, worktrees: state.worktrees }
const loading = state.status === "menu-loading" ? [TIMER_CANCEL] : []
if (event.type === "menu.toggled") {
if (event.open && state.status === "idle") {
const attempt = state.issued + 1
return changed({ ...base, issued: attempt, status: "menu-loading", attempt, search: "" }, [
{ type: "worktrees.load", attempt },
{ type: "timer.start", attempt, phase: "menu-loading" },
])
}
if (!event.open && (state.status === "menu-loading" || state.status === "menu-ready"))
return changed({ ...base, status: "idle", restoreFocus: false }, loading)
return unchanged(state)
}
if (event.type === "search.changed") {
if ((state.status !== "menu-loading" && state.status !== "menu-ready") || state.search === event.search)
return unchanged(state)
return changed({ ...state, search: event.search })
}
if (event.type === "worktrees.loaded" || event.type === "worktrees.timed-out") {
if (state.status !== "menu-loading" || state.attempt !== event.attempt) return unchanged(state)
const items = event.type === "worktrees.loaded" ? event.items : undefined
return changed({ ...base, worktrees: items ?? state.worktrees, status: "menu-ready", search: state.search }, [
TIMER_CANCEL,
...(items ? [] : [{ type: "toast.worktrees-failed" as const }]),
])
}
if (event.type === "choose.requested") {
if (state.status !== "idle" && state.status !== "menu-loading" && state.status !== "menu-ready")
return unchanged(state)
const attempt = state.issued + 1
return changed({ ...base, issued: attempt, status: "picking", attempt }, [
...loading,
{ type: "picker.open", attempt },
])
}
if (event.type === "picker.settled") {
if (state.status !== "picking" || state.attempt !== event.attempt) return unchanged(state)
if (!event.directory) return cancelled(base, event.dialogOpen)
return move(base, "directory", event.directory)
}
if (event.type === "move.worktree") {
if (state.status !== "idle" && state.status !== "menu-loading" && state.status !== "menu-ready")
return unchanged(state)
const next = move(base, "worktree", event.directory)
return changed(next.state, [...loading, ...next.effects])
}
if (event.type === "move.succeeded") {
if (state.status !== "moving" || state.attempt !== event.attempt) return unchanged(state)
return changed({ ...state, status: "moved" }, [{ type: "timer.start", attempt: state.attempt, phase: "moved" }])
}
if (event.type === "move.failed") {
if (state.status !== "moving" || state.attempt !== event.attempt) return unchanged(state)
const next = cancelled(base, event.dialogOpen)
return changed(next.state, [{ type: "toast.move-failed", error: event.error }, ...next.effects])
}
if (event.type === "move.settle-timed-out") {
if (state.status !== "moved" || state.attempt !== event.attempt) return unchanged(state)
return changed({ ...base, status: "idle", restoreFocus: false }, [TIMER_CANCEL])
}
if (event.open || state.status !== "idle" || !state.restoreFocus) return unchanged(state)
return changed({ ...state, restoreFocus: false }, [{ type: "focus.choose" }])
}
export function selectLocationMissingView(state: LocationMissingState, directory: string) {
const live = state.status === "disposed" ? undefined : state
const search = live && "search" in live ? live.search : ""
const others = (live?.worktrees ?? []).filter((item) => item.strategy && !sameDirectory(item.directory, directory))
const query = search.trim().toLowerCase()
const matches = query ? others.filter((item) => getFilename(item.directory).toLowerCase().includes(query)) : others
const loading = state.status === "menu-loading" && others.length === 0
const pending = state.status === "moving" || state.status === "moved" ? state.source : undefined
return {
menuOpen: state.status === "menu-loading" || state.status === "menu-ready",
search,
menuLoading: loading,
hasMenuSeparator: loading || others.length > 0,
searchable: others.length >= 10,
emptySearch: !!query && matches.length === 0,
visibleWorktrees: matches.slice(0, 10),
/** One move at a time: the desktop's native picker leaves the window usable while it is open. */
disabled: !!pending || state.status === "picking" || state.status === "disposed",
pendingWorktree: pending === "worktree",
pendingDirectory: pending === "directory",
}
}
type Base = Pick<Exclude<LocationMissingState, { status: "disposed" }>, "issued" | "worktrees">
function move(base: Base, source: LocationMissingSource, directory: string | undefined): LocationMissingTransition {
const attempt = base.issued + 1
return changed({ ...base, issued: attempt, status: "moving", attempt, source }, [
directory ? { type: "move.run", attempt, directory } : { type: "move.run", attempt },
])
}
// Focus returns to Choose directory now, or once the dialog over it closes.
function cancelled(base: Base, dialogOpen: boolean): LocationMissingTransition {
return changed({ ...base, status: "idle", restoreFocus: dialogOpen }, dialogOpen ? [] : [{ type: "focus.choose" }])
}
function changed(
state: LocationMissingState,
effects: readonly LocationMissingEffect[] = [],
): LocationMissingTransition {
return { state, effects }
}
function unchanged(state: LocationMissingState): LocationMissingTransition {
return { state, effects: [] }
}

View file

@ -5,16 +5,23 @@ 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 { getFilename, sameDirectory } from "@opencode/util/path"
import { getFilename } from "@opencode/util/path"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useMutation } from "@tanstack/solid-query"
import { createEffect, createResource, createUniqueId, For, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { createEffect, createMemo, createSignal, createUniqueId, For, on, onCleanup, Show, untrack } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import { useData, useServer } from "@/runtime/server/current"
import { showToast } from "@/shell/notifications/toast"
import { createWorktree } from "@/workspaces/create"
import { useDirectoryPicker } from "@/workspaces/selection/picker"
import {
createLocationMissingState,
LOCATION_MOVE_SETTLE_TIMEOUT_MS,
selectLocationMissingView,
transitionLocationMissing,
WORKTREES_LOAD_TIMEOUT_MS,
type LocationMissingEffect,
type LocationMissingEvent,
} from "./location-missing-machine"
import "./location-missing.css"
export function SessionLocationMissing(props: { sessionID: string; projectID: string; directory: string }) {
@ -23,93 +30,126 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
const data = useData()
const dialog = useDialog()
const pickDirectory = useDirectoryPicker()
const [state, setState] = createStore({ restoreFocus: false, worktreesOpen: false, search: "" })
const project = () => data.project.get(props.projectID)
const [worktrees] = createResource(
() => (state.worktreesOpen ? props.projectID : undefined),
async (projectID) => {
await server.ctx.sync.worktrees.refresh(projectID)
const items = await server.ctx.sync.worktrees.list(projectID)
if (!items) showToast({ variant: "error", title: language.t("session.location.worktreesFailed") })
return items ?? []
},
// Seed latest so even the first fetch does not enter Suspense.
{ initialValue: [] },
const [machine, setMachine] = createSignal(
createLocationMissingState(untrack(() => server.ctx.sync.worktrees.cached(props.projectID) ?? [])),
)
const otherWorktrees = () =>
worktrees.latest.filter((item) => item.strategy && !sameDirectory(item.directory, props.directory))
const searchable = () => otherWorktrees().length >= 10
const visibleWorktrees = () => {
const query = state.search.trim().toLowerCase()
const matches = query
? otherWorktrees().filter((item) => getFilename(item.directory).toLowerCase().includes(query))
: otherWorktrees()
return matches.slice(0, 10)
}
const view = createMemo(() => selectLocationMissingView(machine(), props.directory))
let timer: ReturnType<typeof setTimeout> | undefined
let button: HTMLButtonElement | undefined
let searchInput: HTMLInputElement | undefined
const move = useMutation(() => ({
mutationFn: async (input: { source: "worktree" | "directory"; directory?: string }) => {
// The missing worktree cannot resolve its own Location, so create from the project's saved checkout.
const current = project()
const dispatch = (event: LocationMissingEvent) => {
const next = transitionLocationMissing(untrack(machine), event)
const destination =
input.directory ??
(current &&
(await createWorktree({
api: server.ctx.sdk.api,
data,
directory: current.canonical,
project: { id: current.id, canonical: current.canonical, directory: current.canonical },
})))
if (next.state !== untrack(machine)) setMachine(next.state)
next.effects.forEach(run)
}
if (!destination) return
await server.ctx.sdk.api.session.move({ sessionID: props.sessionID, directory: destination })
},
onError: (error) => {
setState("restoreFocus", true)
showToast({
variant: "error",
title: language.t("session.location.moveFailed"),
description: error instanceof Error ? error.message : language.t("common.requestFailed"),
function run(effect: LocationMissingEffect) {
if (effect.type === "worktrees.load") {
const projectID = props.projectID
void server.ctx.sync.worktrees
.refresh(projectID)
.then(() => server.ctx.sync.worktrees.list(projectID))
.then((items) => dispatch({ type: "worktrees.loaded", attempt: effect.attempt, items }))
return
}
if (effect.type === "picker.open")
return pickDirectory({
server: server.conn,
title: language.t("session.location.choose"),
onSelect: (result) =>
dispatch({
type: "picker.settled",
attempt: effect.attempt,
directory: (Array.isArray(result) ? result[0] : result) ?? undefined,
dialogOpen: !!dialog.active,
}),
})
},
}))
const pending = (source: "worktree" | "directory") => move.isPending && move.variables?.source === source
const id = createUniqueId()
if (effect.type === "move.run") {
// Creating the worktree is not aborted on unmount: cutting it off kills the project's setup script midway.
void moveSession(effect.directory).then(
() => dispatch({ type: "move.succeeded", attempt: effect.attempt }),
(error) => dispatch({ type: "move.failed", attempt: effect.attempt, error, dialogOpen: !!dialog.active }),
)
createEffect(() => {
if (!state.restoreFocus || move.isPending || dialog.active) return
setState("restoreFocus", false)
button?.focus()
})
return
}
function choose() {
if (move.isPending) return
pickDirectory({
server: server.conn,
title: language.t("session.location.choose"),
onSelect: (result) => {
const selected = Array.isArray(result) ? result[0] : result
if (effect.type === "timer.start") {
clearTimeout(timer)
timer =
effect.phase === "menu-loading"
? setTimeout(
() => dispatch({ type: "worktrees.timed-out", attempt: effect.attempt }),
WORKTREES_LOAD_TIMEOUT_MS,
)
: setTimeout(
() => dispatch({ type: "move.settle-timed-out", attempt: effect.attempt }),
LOCATION_MOVE_SETTLE_TIMEOUT_MS,
)
if (selected) move.mutate({ source: "directory", directory: selected })
return
}
if (!selected) setState("restoreFocus", true)
},
if (effect.type === "timer.cancel") {
clearTimeout(timer)
timer = undefined
return
}
if (effect.type === "focus.choose") return button?.focus()
if (effect.type === "toast.worktrees-failed")
return void showToast({ variant: "error", title: language.t("session.location.worktreesFailed") })
showToast({
variant: "error",
title: language.t("session.location.moveFailed"),
description: effect.error instanceof Error ? effect.error.message : language.t("common.requestFailed"),
})
}
const moveSession = async (directory: string | undefined) => {
// The missing worktree cannot resolve its own Location, so create from the project's saved checkout.
const current = project()
const destination =
directory ??
(current &&
(await createWorktree({
api: server.ctx.sdk.api,
data,
directory: current.canonical,
project: { id: current.id, canonical: current.canonical, directory: current.canonical },
})))
// The project has not loaded yet, so there is no checkout to create the worktree from.
if (!destination) throw new Error(language.t("common.requestFailed"))
await server.ctx.sdk.api.session.move({ sessionID: props.sessionID, directory: destination })
// Read the moved session now, so the notice gives way even when the server's event lags.
await data.session.sync(props.sessionID).catch(() => undefined)
}
createEffect(
on(
() => !!dialog.active,
(open) => dispatch({ type: "dialog.changed", open }),
{ defer: true },
),
)
onCleanup(() => dispatch({ type: "disposed" }))
const id = createUniqueId()
return (
<div data-component="session-location-missing">
<DockShell data-slot="location-body">
@ -135,18 +175,22 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
</DockShell>
<DockTray data-slot="location-footer">
<Show when={project()?.vcs === "git"}>
<Menu placement="top-end" onOpenChange={(open) => setState({ worktreesOpen: open, search: "" })}>
<Menu
placement="top-end"
open={view().menuOpen}
onOpenChange={(open) => dispatch({ type: "menu.toggled", open })}
>
<Menu.Trigger
as={Button}
variant={pending("worktree") ? "loading" : "neutral"}
variant={view().pendingWorktree ? "loading" : "neutral"}
size="large"
disabled={move.isPending}
disabled={view().disabled}
>
<Show when={pending("worktree")}>
<Show when={view().pendingWorktree}>
<Loader />
</Show>
{language.t(pending("worktree") ? "session.location.moving" : "session.location.worktree")}
<Show when={!pending("worktree")}>
{language.t(view().pendingWorktree ? "session.location.moving" : "session.location.worktree")}
<Show when={!view().pendingWorktree}>
<Icon name="chevron-down" size="small" />
</Show>
</Menu.Trigger>
@ -164,7 +208,7 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
if (event.key.length !== 1 && event.key !== "Backspace") return
if (event.key === " " && !state.search) return
if (event.key === " " && !view().search) return
event.stopPropagation()
searchInput.focus({ preventScroll: true })
},
@ -174,17 +218,17 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
class="max-h-[66.667dvh] w-[200px] !p-0"
>
<MenuScroll viewportClass="p-0.5">
<Menu.Item onSelect={() => move.mutate({ source: "worktree" })} disabled={move.isPending}>
<Menu.Item onSelect={() => dispatch({ type: "move.worktree" })} disabled={view().disabled}>
<Icon name="plus" />
<span class="min-w-0 flex-1 truncate">{language.t("workspace.new")}</span>
</Menu.Item>
<Show when={worktrees.loading || otherWorktrees().length > 0}>
<Show when={view().hasMenuSeparator}>
<Menu.Separator class="h-[0.5px]" />
</Show>
<Show when={worktrees.loading && otherWorktrees().length === 0}>
<Show when={view().menuLoading}>
<Menu.Item disabled>{language.t("common.loading")}</Menu.Item>
</Show>
<Show when={searchable()}>
<Show when={view().searchable}>
<div class="flex h-7 items-center gap-2 rounded-sm ps-3 pe-2 text-v2-icon-icon-muted">
<Icon name="magnifying-glass" size="small" class="shrink-0" />
<input
@ -195,11 +239,11 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
requestAnimationFrame(() => element.focus({ preventScroll: true })),
)
}}
value={state.search}
value={view().search}
placeholder={language.t("session.new.workspace.search.placeholder")}
aria-label={language.t("session.new.workspace.search.placeholder")}
class="h-7 min-w-0 flex-1 border-0 bg-transparent text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-base outline-none placeholder:text-v2-text-text-faint"
onInput={(event) => setState("search", event.currentTarget.value)}
onInput={(event) => dispatch({ type: "search.changed", search: event.currentTarget.value })}
onKeyDown={(event) => {
if (
event.key === "Escape" ||
@ -213,17 +257,17 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
/>
</div>
</Show>
<Show when={state.search.trim() && visibleWorktrees().length === 0}>
<Show when={view().emptySearch}>
<div class="px-3 py-4 text-center text-[13px] font-[440] leading-5 text-v2-text-text-muted">
{language.t("session.new.workspace.search.empty")}
</div>
</Show>
<For each={visibleWorktrees()}>
<For each={view().visibleWorktrees}>
{(worktree) => (
<Menu.Item
title={worktree.directory}
onSelect={() => move.mutate({ source: "worktree", directory: worktree.directory })}
disabled={move.isPending}
onSelect={() => dispatch({ type: "move.worktree", directory: worktree.directory })}
disabled={view().disabled}
>
<Icon name="outline-worktree" />
<span class="min-w-0 flex-1 truncate">{getFilename(worktree.directory)}</span>
@ -237,15 +281,15 @@ export function SessionLocationMissing(props: { sessionID: string; projectID: st
</Show>
<Button
ref={button}
variant={pending("directory") ? "loading" : "submit"}
variant={view().pendingDirectory ? "loading" : "submit"}
size="large"
onClick={choose}
disabled={move.isPending}
onClick={() => dispatch({ type: "choose.requested" })}
disabled={view().disabled}
>
<Show when={pending("directory")}>
<Show when={view().pendingDirectory}>
<Loader />
</Show>
{language.t(pending("directory") ? "session.location.moving" : "session.location.choose")}
{language.t(view().pendingDirectory ? "session.location.moving" : "session.location.choose")}
</Button>
</DockTray>
</div>

View file

@ -290,23 +290,168 @@ describe("stale results", () => {
])
})
test("dispose returns the draft and ignores results for operations no longer in flight", () => {
const editing = replay(createQueueState([one, two]), [
test("after dispose an operation that settles starts no expiry timer, toast or waiting operation", () => {
const editing = replay(createQueueState([one, two, three]), [
{ type: "steer.requested", id: "inb_2" },
{ type: "remove.requested", id: "inb_3" },
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("my draft") },
])
const attempt = runs(editing.effects)[0].attempt
const disposed = transitionQueue(editing.state, { type: "dispose" })
expect(disposed.state.status).toBe("mutating")
expect(disposed.state).toEqual({ status: "disposed" })
expect(disposed.effects).toEqual([
{ type: "draft.restore", stash: draft("my draft"), focus: false },
{ type: "timer.clearAll" },
])
expect(viewQueue(disposed.state, { working: true, behavior: "queue" })).toMatchObject({ rows: [], busy: false })
const stale = transitionQueue(disposed.state, { type: "mutation.succeeded", attempt: 0 })
for (const event of [
{ type: "mutation.succeeded", attempt },
{ type: "mutation.failed", attempt, hidden: [] },
] satisfies QueueEvent[])
expect(transitionQueue(disposed.state, event)).toEqual({ state: disposed.state, effects: [] })
})
expect(stale.state).toBe(disposed.state)
test("an edit the server never admitted before dispose returns to the saved draft if it then fails", () => {
const sent = replay(createQueueState([one]), [
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
{ type: "dispose" },
])
const attempt = runs(sent.effects)[0].attempt
expect(transitionQueue(sent.state, { type: "mutation.failed", attempt, hidden: [] }).effects).toEqual([
{ type: "draft.merge", prompt: prompt("inb_1 edited"), context: [], focus: false },
])
const admitted = transitionQueue(sent.state, { type: "mutation.admitted", attempt }).state
expect(transitionQueue(admitted, { type: "mutation.failed", attempt, hidden: [] }).effects).toEqual([])
})
test("dispose stops an undo before its cancel, and an undo the server applied anyway returns its prompt", () => {
const undoing = transitionQueue(createQueueState([one]), { type: "undo.requested", id: "inb_1", mode: "normal" })
const attempt = runs(undoing.effects)[0].attempt
const disposed = transitionQueue(undoing.state, { type: "dispose" })
expect(disposed.effects).toEqual([{ type: "mutation.abort", attempt }, { type: "timer.clearAll" }])
expect(
transitionQueue(disposed.state, { type: "mutation.undone", attempt, prompt: prompt("inb_1 text"), context: [] })
.effects,
).toEqual([{ type: "draft.merge", prompt: prompt("inb_1 text"), context: [], focus: false }])
})
})
describe("an operation past its bound", () => {
test("a stalled undo gives the composer back and ignores its late answer", () => {
const undoing = transitionQueue(createQueueState([one]), { type: "undo.requested", id: "inb_1", mode: "normal" })
const attempt = runs(undoing.effects)[0].attempt
expect(undoing.effects).toContainEqual({ type: "mutation.timer.start", attempt })
expect(viewQueue(undoing.state, { working: true, behavior: "queue" }).undoing).toBe(true)
const timedOut = transitionQueue(undoing.state, {
type: "mutation.timed-out",
attempt,
hidden: [],
stage: "running",
})
expect(timedOut.state.status).toBe("idle")
expect(viewQueue(timedOut.state, { working: true, behavior: "queue" }).undoing).toBe(false)
expect(timedOut.effects).toEqual([
{ type: "mutation.abort", attempt },
{ type: "toast", key: "common.requestFailed" },
{ type: "mutation.timer.clear" },
])
expect(transitionQueue(timedOut.state, { type: "mutation.failed", attempt, hidden: [] }).state).toBe(timedOut.state)
})
test("a steered edit whose admission is in flight keeps the edit until the server answers", () => {
const sent = replay(createQueueState([one, two]), [
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 edited"), ids },
])
const attempt = runs(sent.effects)[0].attempt
const waiting = transitionQueue(sent.state, { type: "mutation.timed-out", attempt, hidden: [], stage: "committed" })
// The replacement may already be delivered: the composer must not get the edit back while it may have gone out.
expect(waiting.state).toBe(sent.state)
expect(waiting.effects).toEqual([])
// Delivered, a later failure of the original's cancel leaves the edit with the server.
const admitted = transitionQueue(waiting.state, { type: "mutation.admitted", attempt }).state
expect(
transitionQueue(admitted, { type: "mutation.failed", attempt, hidden: [] }).effects.some(
(effect) => effect.type === "draft.merge",
),
).toBe(false)
// Refused, it really did not go out, so it returns to the composer.
expect(transitionQueue(waiting.state, { type: "mutation.failed", attempt, hidden: [] }).effects).toContainEqual({
type: "draft.merge",
prompt: prompt("inb_1 edited"),
context: [],
})
})
test("an undo whose cancel is in flight waits for the server's answer", () => {
const undoing = transitionQueue(createQueueState([one]), { type: "undo.requested", id: "inb_1", mode: "normal" })
const attempt = runs(undoing.effects)[0].attempt
expect(
transitionQueue(undoing.state, { type: "mutation.timed-out", attempt, hidden: [], stage: "committed" }).state,
).toBe(undoing.state)
})
test("a stalled reorder hides the copy it withdrew and starts the steer waiting behind it", () => {
const reordering = replay(createQueueState([one, two, three]), [
{ type: "reorder.requested", inboxIDs: ["inb_2", "inb_1", "inb_3"], reverted: false },
{ type: "steer.requested", id: "inb_3" },
{ type: "inbox.synced", items: [one, two, three, item("msg_2")] },
])
const attempt = runs(reordering.effects)[0].attempt
const timedOut = transitionQueue(reordering.state, {
type: "mutation.timed-out",
attempt,
hidden: ["msg_2"],
stage: "running",
})
expect(timedOut.effects).toContainEqual({ type: "mutation.abort", attempt })
expect(timedOut.effects).toContainEqual({ type: "toast", key: "common.requestFailed" })
expect(timedOut.effects).toContainEqual(expect.objectContaining({ type: "timer.start" }))
expect(runs(timedOut.effects)).toMatchObject([{ type: "steer", id: "inb_3" }])
expect(rowIDs(timedOut.state)).toEqual(["inb_1", "inb_2"])
// A steer is one request the request queue already bounds, so it gets no timer of its own.
expect(timedOut.effects.filter((effect) => effect.type === "mutation.timer.start")).toEqual([])
})
test("an edit the server holds whose queue re-read stalled counts as done", () => {
const sent = replay(createQueueState([one]), [
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
])
const attempt = runs(sent.effects)[0].attempt
const timedOut = transitionQueue(sent.state, {
type: "mutation.timed-out",
attempt,
hidden: [],
stage: "settled",
})
expect(timedOut.state.status).toBe("idle")
expect(timedOut.effects).not.toContainEqual({ type: "toast", key: "common.requestFailed" })
expect(timedOut.effects.some((effect) => effect.type === "draft.merge")).toBe(false)
})
})

View file

@ -87,6 +87,26 @@ type QueueBase = {
const NO_MOVES: Readonly<Record<string, string>> = Object.freeze({})
/**
* Bounds an edit, reorder or undo, whose chains include local media reads and one request per rewritten prompt. Each
* request already fails on its own after the request queue's 60 s wait for headers; a steer or removal is one request,
* so it needs no other bound.
*/
export const QUEUE_MUTATION_TIMEOUT_MS = 60_000
/**
* How far a timed-out operation got. `committed`: a step it cannot take back is in flight (an undo's cancel, a steered
* edit's admission, or the cancels of a rewrite's originals once every copy is in), so the operation waits for its
* result. `settled`: the server holds the whole change and only re-reading its queue stalled.
*/
export type QueueMutationStage = "running" | "committed" | "settled"
// After unmount, an operation still in flight can owe the composer's saved draft a prompt: an edit the server never
// admitted, or an undo whose cancel the server may still apply.
type DisposedReturn =
| { readonly type: "edit"; readonly attempt: number; readonly prompt: Prompt }
| { readonly type: "undo"; readonly attempt: number }
// Operations run one at a time in the order they were requested: `active` is in flight and `pending` waits for it.
export type QueueState =
| (QueueBase & { readonly status: "idle" })
@ -102,6 +122,9 @@ export type QueueState =
readonly active: ConcurrentOperation
readonly pending: readonly QueuedOperation[]
})
| { readonly status: "disposed"; readonly returning?: DisposedReturn }
type LiveQueueState = Exclude<QueueState, { status: "disposed" }>
export type QueueEvent =
| { readonly type: "inbox.synced"; readonly items: readonly QueuedPrompt[] }
@ -131,6 +154,13 @@ export type QueueEvent =
}
// `hidden` lists the inbox IDs the failed operation already withdrew or cancelled.
| { readonly type: "mutation.failed"; readonly attempt: number; readonly hidden: readonly string[] }
// `hidden` as for a failure: what the operation withdrew or cancelled before the bound ran out.
| {
readonly type: "mutation.timed-out"
readonly attempt: number
readonly hidden: readonly string[]
readonly stage: QueueMutationStage
}
| { readonly type: "gone.expired"; readonly expiry: number }
| { readonly type: "dispose" }
@ -141,13 +171,23 @@ export type QueueEffect =
// `keep` is the prompt the edit was loaded from: changes made to it join the restored draft.
| { readonly type: "draft.restore"; readonly stash: EditStash; readonly focus: boolean; readonly keep?: QueuedPrompt }
| { readonly type: "draft.pinned"; readonly blobs: ReadonlyMap<string, BlobReference> }
| { readonly type: "draft.merge"; readonly prompt: Prompt; readonly context: readonly ContextItem[] }
// `focus: false` after unmount, when the merge lands in the session's saved draft.
| {
readonly type: "draft.merge"
readonly prompt: Prompt
readonly context: readonly ContextItem[]
readonly focus?: false
}
| {
readonly type: "media.pin"
readonly attempt: number
readonly attachments: readonly (ImageAttachmentPart | PathAttachmentPart)[]
}
| { readonly type: "mutation.run"; readonly operation: ActiveOperation }
// Stops the operation at its next step; a request already sent still finishes.
| { readonly type: "mutation.abort"; readonly attempt: number }
| { readonly type: "mutation.timer.start"; readonly attempt: number }
| { readonly type: "mutation.timer.clear" }
| { readonly type: "timer.start"; readonly expiry: number }
| { readonly type: "timer.clear"; readonly expiry: number }
| { readonly type: "timer.clearAll" }
@ -171,6 +211,8 @@ export function createQueueState(items: readonly QueuedPrompt[]): QueueState {
}
export function transitionQueue(state: QueueState, event: QueueEvent): QueueTransition {
if (state.status === "disposed") return settleDisposed(state, event)
if (event.type === "inbox.synced") return synced(state, event.items)
if (event.type === "edit.start") return startEdit(state, event)
@ -204,19 +246,68 @@ export function transitionQueue(state: QueueState, event: QueueEvent): QueueTran
if (event.type === "dispose") {
const edit = editOf(state)
const closed = state.status === "editing" || state.status === "editing-while-mutating" ? closeEdit(state) : state
const active = state.status === "mutating" || state.status === "editing-while-mutating" ? state.active : undefined
// Operations in flight still finish: the server may already hold half of an edit.
return changed({ ...closed, gone: [], moved: NO_MOVES }, [
const returning: DisposedReturn | undefined =
active?.type === "edit" && active.phase === "admitting"
? { type: "edit", attempt: active.attempt, prompt: active.prompt }
: active?.type === "undo"
? { type: "undo", attempt: active.attempt }
: undefined
// Operations in flight still finish, since the server may already hold half of an edit, but waiting ones never
// start. An undo stops before its cancel if it can: nothing would show the restored prompt.
return changed(returning ? { status: "disposed", returning } : { status: "disposed" }, [
...(edit ? [restore(edit, false)] : []),
...(active?.type === "undo" ? [{ type: "mutation.abort" as const, attempt: active.attempt }] : []),
{ type: "timer.clearAll" },
])
}
if (event.type === "mutation.timed-out") return timedOut(state, event)
return settle(state, event)
}
function settleDisposed(state: Extract<QueueState, { status: "disposed" }>, event: QueueEvent): QueueTransition {
const returning = state.returning
if (!returning || !("attempt" in event) || event.attempt !== returning.attempt) return unchanged(state)
if (event.type === "mutation.admitted" || event.type === "mutation.succeeded") return changed({ status: "disposed" })
if (event.type === "mutation.undone")
return changed({ status: "disposed" }, [
{ type: "draft.merge", prompt: event.prompt, context: event.context, focus: false },
])
if (event.type !== "mutation.failed") return unchanged(state)
return changed(
{ status: "disposed" },
returning.type === "edit" ? [{ type: "draft.merge", prompt: returning.prompt, context: [], focus: false }] : [],
)
}
// An operation past its bound ends as it got: a finished change succeeds, an undo whose cancel is in flight waits for
// it, and anything else fails with what it already withdrew, while its chain stops at the next step.
function timedOut(state: LiveQueueState, event: Extract<QueueEvent, { type: "mutation.timed-out" }>) {
if (state.status !== "mutating" && state.status !== "editing-while-mutating") return unchanged(state)
if (state.active.attempt !== event.attempt || event.stage === "committed") return unchanged(state)
const next = settle(
state,
event.stage === "settled"
? { type: "mutation.succeeded", attempt: event.attempt }
: { type: "mutation.failed", attempt: event.attempt, hidden: event.hidden },
)
return changed(next.state, [{ type: "mutation.abort", attempt: event.attempt }, ...next.effects])
}
export function selectQueueRows(state: QueueState): QueueRow[] {
if (state.status === "disposed") return []
const operations = operationsOf(state)
const hidden = [
@ -271,6 +362,7 @@ export function viewQueue(
}
export function selectQueueMoved(state: QueueState) {
if (state.status === "disposed") return NO_MOVES
const active = state.status === "mutating" || state.status === "editing-while-mutating" ? state.active : undefined
if ((active?.type !== "edit" && active?.type !== "reorder") || !Object.keys(active.moved).length) return state.moved
@ -294,7 +386,7 @@ export function editingID(state: QueueState) {
return editOf(state)?.id
}
function synced(state: QueueState, items: readonly QueuedPrompt[]): QueueTransition {
function synced(state: LiveQueueState, items: readonly QueuedPrompt[]): QueueTransition {
if (items === state.items) return unchanged(state)
const listed = new Set(items.map((item) => item.id))
const gone = state.gone.filter((entry) => listed.has(entry.id))
@ -322,7 +414,7 @@ function synced(state: QueueState, items: readonly QueuedPrompt[]): QueueTransit
return changed(closeEdit(next), [...cleared, restore(next.edit, true, next.edit.item)])
}
function startEdit(state: QueueState, event: Extract<QueueEvent, { type: "edit.start" }>): QueueTransition {
function startEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "edit.start" }>): QueueTransition {
// Other rows stay editable while an edit, steer or removal is in flight; the row it is changing ignores clicks and
// shows as pending until the server catches up.
if (state.status === "mutating" && !isConcurrent(state.active)) return unchanged(state)
@ -364,7 +456,7 @@ function startEdit(state: QueueState, event: Extract<QueueEvent, { type: "edit.s
)
}
function confirmEdit(state: QueueState, event: Extract<QueueEvent, { type: "edit.confirm" }>): QueueTransition {
function confirmEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "edit.confirm" }>): QueueTransition {
if (state.status !== "editing" && state.status !== "editing-while-mutating") return unchanged(state)
if (event.reverted) return changed(state, [{ type: "toast", key: "session.queue.reverted" }])
@ -404,7 +496,7 @@ function confirmEdit(state: QueueState, event: Extract<QueueEvent, { type: "edit
)
}
function reorder(state: QueueState, event: Extract<QueueEvent, { type: "reorder.requested" }>): QueueTransition {
function reorder(state: LiveQueueState, event: Extract<QueueEvent, { type: "reorder.requested" }>): QueueTransition {
if (state.status !== "idle" && state.status !== "editing") return unchanged(state)
if (event.reverted) return changed(state, [{ type: "toast", key: "session.queue.reverted" }])
@ -425,14 +517,11 @@ function reorder(state: QueueState, event: Extract<QueueEvent, { type: "reorder.
active,
pending: [],
},
[
...(state.status === "editing" ? [restore(state.edit, true, state.edit.item)] : []),
{ type: "mutation.run", operation: active },
],
[...(state.status === "editing" ? [restore(state.edit, true, state.edit.item)] : []), ...start(active)],
)
}
function request(state: QueueState, operation: Extract<QueuedOperation, { type: "steer" | "remove" }>) {
function request(state: LiveQueueState, operation: Extract<QueuedOperation, { type: "steer" | "remove" }>) {
const row = selectQueueRows(state).find((entry) => entry.id === operation.id)
if (!row || row.pending) return unchanged(state)
@ -443,7 +532,7 @@ function request(state: QueueState, operation: Extract<QueuedOperation, { type:
return enqueue(state, operation)
}
function undo(state: QueueState, event: Extract<QueueEvent, { type: "undo.requested" }>): QueueTransition {
function undo(state: LiveQueueState, event: Extract<QueueEvent, { type: "undo.requested" }>): QueueTransition {
if (state.status !== "idle") return unchanged(state)
const row = selectQueueRows(state).find((entry) => entry.id === event.id)
const item = state.items.find((entry) => entry.id === event.id)
@ -463,12 +552,12 @@ function undo(state: QueueState, event: Extract<QueueEvent, { type: "undo.reques
active,
pending: [],
},
[{ type: "mutation.run", operation: active }],
start(active),
)
}
function settle(
state: QueueState,
state: LiveQueueState,
event: Extract<
QueueEvent,
{ type: "mutation.moved" | "mutation.admitted" | "mutation.succeeded" | "mutation.undone" | "mutation.failed" }
@ -584,12 +673,15 @@ function advance(state: Mutating, moved: Readonly<Record<string, string>>): Queu
)
const base = { seq: state.seq, items: state.items, gone: state.gone, moved: state.moved }
// `state.active` is the operation that just finished.
const clear: QueueEffect[] = bounded(state.active) ? [{ type: "mutation.timer.clear" }] : []
if (!head)
return changed(
state.status === "editing-while-mutating"
? { ...base, status: "editing", edit: state.edit }
: { ...base, status: "idle" },
clear,
)
const active = activate(head, state.seq + 1)
const next = { ...base, seq: active.attempt, active, pending: rest }
@ -598,21 +690,30 @@ function advance(state: Mutating, moved: Readonly<Record<string, string>>): Queu
state.status === "editing-while-mutating"
? { ...next, status: "editing-while-mutating", edit: state.edit }
: { ...next, status: "mutating" },
[{ type: "mutation.run", operation: active }],
[...clear, ...start(active)],
)
}
function enqueue(state: QueueState, operation: QueuedOperation, effects: QueueEffect[] = []): QueueTransition {
function start(operation: ActiveOperation): QueueEffect[] {
const run: QueueEffect = { type: "mutation.run", operation }
return bounded(operation) ? [run, { type: "mutation.timer.start", attempt: operation.attempt }] : [run]
}
function bounded(operation: ActiveOperation) {
return operation.type !== "steer" && operation.type !== "remove"
}
function enqueue(state: LiveQueueState, operation: QueuedOperation, effects: QueueEffect[] = []): QueueTransition {
if (state.status === "mutating" || state.status === "editing-while-mutating")
return changed({ ...state, pending: [...state.pending, operation] }, effects)
const active = activate(operation, state.seq + 1)
const base = { seq: active.attempt, items: state.items, gone: state.gone, moved: state.moved, active, pending: [] }
const run: QueueEffect = { type: "mutation.run", operation: active }
if (state.status === "editing")
return changed({ ...base, status: "editing-while-mutating", edit: state.edit }, [...effects, run])
return changed({ ...base, status: "editing-while-mutating", edit: state.edit }, [...effects, ...start(active)])
return changed({ ...base, status: "mutating" }, [...effects, run])
return changed({ ...base, status: "mutating" }, [...effects, ...start(active)])
}
function activate(operation: QueuedOperation, attempt: number): ConcurrentOperation {
@ -627,7 +728,7 @@ function withActive(state: Mutating, active: ActiveOperation): QueueState {
return isConcurrent(active) ? { ...state, active } : state
}
function closeEdit(state: Extract<QueueState, { edit: ActiveEdit }>): QueueState {
function closeEdit(state: Extract<QueueState, { edit: ActiveEdit }>): LiveQueueState {
const base = { seq: state.seq, items: state.items, gone: state.gone, moved: state.moved }
if (state.status === "editing") return { ...base, status: "idle" }

View file

@ -286,6 +286,27 @@ describe("queuedPromptAttachments", () => {
}),
).rejects.toBeInstanceOf(Error)
expect(events.slice(cancels)).toEqual([`load:${mediaUri}`])
// An undo stopped while its media loads (past its bound, or on unmount) leaves the item queued.
const stopped = new AbortController()
blobs.set(hash, pngBytes)
setMediaBlobLoader("queue-test", async (uri) => {
stopped.abort()
return `data:image/png;base64,${Buffer.from(blobs.get(uri.slice("media:".length))!).toString("base64")}`
})
const before = events.length
await expect(
undoQueuedPrompt({
prompt: extracted,
signal: stopped.signal,
cancelInboxItem: async () => {
events.push("cancelInboxItem")
},
}),
).rejects.toMatchObject({ name: "AbortError" })
expect(events.slice(before)).toEqual([])
} finally {
setMediaBlobLoader("queue-test", undefined)
}

View file

@ -20,6 +20,7 @@ import {
isComposerAttachment,
isPristine,
mergePrompt,
QUEUE_MUTATION_TIMEOUT_MS,
queuedPromptText,
transitionQueue,
viewQueue,
@ -27,6 +28,7 @@ import {
type EditOperation,
type QueueEffect,
type QueueEvent,
type QueueMutationStage,
type QueuedPrompt,
} from "./queue-machine"
@ -53,6 +55,9 @@ export function createSessionQueue(input: {
const view = createMemo(() => viewQueue(state(), { working: input.working(), behavior: input.behavior() }))
// OS handles for the machine's expiry timers, keyed by its expiry IDs.
const timers = new Map<number, ReturnType<typeof setTimeout>>()
// The bound on the operation in flight, and each running operation's progress, keyed by attempt.
let mutationTimer: ReturnType<typeof setTimeout> | undefined
const runs = new Map<number, MutationProgress>()
// Effects read and write the composer, so neither the transition nor its effects subscribe the caller.
const dispatch = (event: QueueEvent) =>
@ -109,7 +114,8 @@ export function createSessionQueue(input: {
const prompt = mergePrompt(input.draft.current(), effect.prompt)
input.draft.set(prompt, promptLength(prompt))
effect.context.forEach((item) => input.draft.context.add(item))
input.restoreFocus(promptLength(prompt))
if (effect.focus !== false) input.restoreFocus(promptLength(prompt))
return
}
@ -133,7 +139,38 @@ export function createSessionQueue(input: {
return
}
if (effect.type === "mutation.run") return void run(effect.operation)
if (effect.type === "mutation.run") {
const attempt = effect.operation.attempt
const progress: MutationProgress = { controller: new AbortController(), hidden: [], stage: "running" }
runs.set(attempt, progress)
return void run(effect.operation, progress).finally(() => runs.delete(attempt))
}
if (effect.type === "mutation.abort") return runs.get(effect.attempt)?.controller.abort()
if (effect.type === "mutation.timer.start") {
clearTimeout(mutationTimer)
mutationTimer = setTimeout(() => {
const progress = runs.get(effect.attempt)
dispatch({
type: "mutation.timed-out",
attempt: effect.attempt,
hidden: progress ? [...progress.hidden] : [],
stage: progress?.stage ?? "running",
})
}, QUEUE_MUTATION_TIMEOUT_MS)
return
}
if (effect.type === "mutation.timer.clear") {
clearTimeout(mutationTimer)
mutationTimer = undefined
return
}
if (effect.type === "timer.start") {
timers.set(
@ -157,6 +194,8 @@ export function createSessionQueue(input: {
if (effect.type === "timer.clearAll") {
timers.forEach(clearTimeout)
timers.clear()
clearTimeout(mutationTimer)
mutationTimer = undefined
return
}
@ -166,7 +205,7 @@ export function createSessionQueue(input: {
// Runs the operation in flight and reports its progress. Each report carries the operation's attempt, so the machine
// ignores one that arrives after the operation stopped being current.
const run = async (operation: ActiveOperation) => {
const run = async (operation: ActiveOperation, progress: MutationProgress) => {
const attempt = operation.attempt
// SSE retracts and updates materialized timeline messages for a steer or removal, so neither re-syncs the queue.
@ -200,8 +239,12 @@ export function createSessionQueue(input: {
attachmentName: language.t("common.attachment"),
sessionTitle: (id) => data.session.get(id)?.title,
}),
cancelInboxItem: () =>
server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: operation.item.id }),
signal: progress.controller.signal,
cancelInboxItem: () => {
progress.stage = "committed"
return server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: operation.item.id })
},
}).then(
(prompt) =>
dispatch({ type: "mutation.undone", attempt, prompt, context: [...context.comments, ...context.files] }),
@ -212,23 +255,26 @@ export function createSessionQueue(input: {
return
}
// IDs the operation withdrew or cancelled before a failure, which the strip hides until the server's events land.
const hidden: string[] = []
const settled = await (
operation.type === "reorder" ? rewrite(attempt, hidden, [...operation.inboxIDs]) : sendEdit(operation, hidden)
operation.type === "reorder" ? rewrite(attempt, progress, [...operation.inboxIDs]) : sendEdit(operation, progress)
).then(
() => true,
() => false,
)
if (settled) progress.stage = "settled"
if (operation.type === "reorder") data.session.pending.invalidate(input.sessionID)
// The rows keep their optimistic state until the server's queue has caught up.
await data.session.pending.sync(input.sessionID).catch(() => undefined)
dispatch(settled ? { type: "mutation.succeeded", attempt } : { type: "mutation.failed", attempt, hidden })
dispatch(
settled ? { type: "mutation.succeeded", attempt } : { type: "mutation.failed", attempt, hidden: progress.hidden },
)
}
const sendEdit = async (operation: EditOperation & { attempt: number }, hidden: string[]) => {
const sendEdit = async (operation: EditOperation & { attempt: number }, progress: MutationProgress) => {
const signal = progress.controller.signal
const replacement = await editedPromptInput(
input.sessionID,
location().directory,
@ -242,18 +288,23 @@ export function createSessionQueue(input: {
const admission = { ...replacement, id: operation.moved[operation.original], delivery: operation.delivery }
if (operation.delivery === "queue")
return rewrite(operation.attempt, hidden, undefined, {
return rewrite(operation.attempt, progress, undefined, {
original: operation.original,
admission: { ...admission, resume: false },
moved: operation.moved,
})
signal.throwIfAborted()
// Like a queued edit, an original the server delivered meanwhile keeps the edit draft instead of sending twice.
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
if (!pending.some((item) => item.id === operation.original && item.type === "user" && item.delivery === "queue"))
throw new Error("Queued prompt was delivered before the edit")
signal.throwIfAborted()
const background = input.background()
// A steered replacement can be delivered before a withdrawal reaches it, so the bound waits for the admission and
// the edit returns to the composer only if it really did not go out.
progress.stage = "committed"
await data.session.prompt(admission)
void background?.move()
dispatch({ type: "mutation.admitted", attempt: operation.attempt })
@ -266,7 +317,7 @@ export function createSessionQueue(input: {
// Without `inboxIDs` the server's current order is kept.
const rewrite = async (
attempt: number,
hidden: string[],
progress: MutationProgress,
inboxIDs: string[] | undefined,
replace?: {
original: string
@ -274,7 +325,10 @@ export function createSessionQueue(input: {
moved: Readonly<Record<string, string>>
},
) => {
const signal = progress.controller.signal
signal.throwIfAborted()
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
signal.throwIfAborted()
if (pending.some((item) => item.delivery === "queue" && item.type !== "user"))
throw new Error("Queued control items block reordering")
@ -293,6 +347,23 @@ export function createSessionQueue(input: {
// Each ID is recorded before sending: the server can admit a prompt whose response then fails.
const replacements: string[] = []
const withdraw = () =>
Promise.all(
replacements.map((inboxID) =>
server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID }).then(
() => void progress.hidden.push(inboxID),
() => undefined,
),
),
)
// A rewrite stopped by its bound withdraws what it sent, as a failed one does.
const stopped = async () => {
if (!signal.aborted) return
await withdraw()
signal.throwIfAborted()
}
// An edit's pending rows follow the queue as the server has it now, keeping the IDs minted at confirm.
const moved = Object.fromEntries(
ordered.slice(changed).map((item) => [item.id, replace?.moved[item.id] ?? SessionMessage.ID.create()]),
@ -323,20 +394,18 @@ export function createSessionQueue(input: {
const id = admission.id ?? SessionMessage.ID.create()
await stopped()
replacements.push(id)
await data.session.prompt({ ...admission, id }).catch(async (error) => {
await Promise.all(
replacements.map((inboxID) =>
server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID }).then(
() => void hidden.push(inboxID),
() => undefined,
),
),
)
await withdraw()
throw error
})
}
await stopped()
// Every copy is in, so the originals must go, however long that takes, or the queue holds both.
progress.stage = "committed"
if (replace) dispatch({ type: "mutation.admitted", attempt })
// An edit cancels last first: the strip shows each original until it goes, so its copies never
@ -345,7 +414,7 @@ export function createSessionQueue(input: {
for (const item of replace ? replaced.reverse() : replaced) {
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: item.id })
hidden.push(item.id)
progress.hidden.push(item.id)
}
}
@ -412,6 +481,9 @@ export function createSessionQueue(input: {
export type SessionQueue = ReturnType<typeof createSessionQueue>
// What a running operation has done so far: the IDs it withdrew or cancelled, and how far it got.
type MutationProgress = { controller: AbortController; hidden: string[]; stage: QueueMutationStage }
// The slice of the queue the panel renders and drives. Without `moved`, a replaced row closes and its replacement opens.
export type SessionQueueView = Pick<
SessionQueue,
@ -421,11 +493,14 @@ export type SessionQueueView = Pick<
// Pin `media:<hash>` attachments before cancelling: the cancel releases the item's blob refs and sweeps blobs
// nothing else references, so a pin that fails leaves the item queued.
// An undo stopped while its media loads leaves the item queued.
export async function undoQueuedPrompt<A>(input: {
prompt: Prompt
signal?: AbortSignal
cancelInboxItem: () => Promise<A>
}): Promise<Prompt> {
const pinned = await pinPromptMedia(input.prompt)
input.signal?.throwIfAborted()
await input.cancelInboxItem()
return pinned

View file

@ -20,7 +20,10 @@ const watcher: SessionActivityItem = {
started: 2,
}
const work = (shells: readonly SessionActivityItem[], subagents = 0): ShellPanelWork => ({
const work = (
shells: readonly SessionActivityItem[],
subagents: readonly SessionActivityItem[] = [],
): ShellPanelWork => ({
enabled: true,
subagents,
shells,
@ -35,36 +38,103 @@ function replay(events: ShellPanelEvent[], from = createShellPanelState({ active
)
}
const attempt = (state: ShellPanelState) => (state.status === "disposed" ? -1 : state.attempt)
// The attempt of the Stop in flight for `item`, or of the shown shell's end lookup.
const stopOf = (state: ShellPanelState, item: SessionActivityItem) =>
state.status === "disposed" ? -1 : (state.stopping[item.key] ?? -1)
test("a Stop from an earlier visit cannot settle the Stop in flight after reopening the shell", () => {
const endingOf = (state: ShellPanelState) =>
state.status === "shell" && state.phase.status === "ending" ? state.phase.attempt : -1
test("a row's Stop sends once until it settles, and a stop that never settles gives the row back", () => {
const listed = replay([{ type: "menu.toggled", open: true, work: both }]).state
const first = transitionShellPanel(listed, { type: "stop.requested", item: server, work: both })
const attempt = stopOf(first.state, server)
expect(first.effects).toEqual([
{ type: "stop.run", attempt, item: server },
{ type: "timer.start", attempt, phase: "stopping" },
])
expect(selectShellPanelView(first.state, both).stoppingKeys).toEqual({ sh_dev: attempt })
// A double click or a second Delete.
expect(transitionShellPanel(first.state, { type: "stop.requested", item: server, work: both }).state).toBe(
first.state,
)
const timedOut = transitionShellPanel(first.state, { type: "stop.timed-out", attempt, work: both })
expect(timedOut.effects).toEqual([{ type: "timer.cancel", attempt }])
expect(selectShellPanelView(timedOut.state, both).stoppingKeys).toEqual({})
expect(
transitionShellPanel(timedOut.state, { type: "stop.requested", item: server, work: both }).effects,
).toContainEqual(expect.objectContaining({ type: "stop.run", item: server }))
})
test("a subagent row stops only once its child session exists", () => {
const starting: SessionActivityItem = { key: "call_1", type: "subagent", target: "call_1", started: 1 }
const child: SessionActivityItem = { ...starting, key: "call_2", target: "call_2", sessionID: "ses_child" }
const running = work([], [starting, child])
const listed = replay([{ type: "menu.toggled", open: true, work: running }]).state
expect(transitionShellPanel(listed, { type: "stop.requested", item: starting, work: running }).state).toBe(listed)
expect(transitionShellPanel(listed, { type: "stop.requested", item: child, work: running }).effects).toContainEqual(
expect.objectContaining({ type: "stop.run", item: child }),
)
})
test("a shell stopped from its row opens stopping, and the row's Stop settles the panel", () => {
const stopping = replay([
{ type: "menu.toggled", open: true, work: both },
{ type: "stop.requested", item: server, work: both },
{ type: "shell.selected", item: server, work: both },
]).state
expect(selectShellPanelView(stopping, both)).toMatchObject({ stopping: true, stopDisabled: true })
expect(transitionShellPanel(stopping, { type: "stop.requested", work: both }).state).toBe(stopping)
const ended = transitionShellPanel(stopping, {
type: "stop.settled",
attempt: stopOf(stopping, server),
stopped: true,
work: work([watcher]),
now: 5,
})
expect(selectShellPanelView(ended.state, work([watcher])).end).toEqual({ status: "killed", completed: 5 })
})
test("going back keeps a Stop in flight, so reopening the shell shows it stopping and a late answer settles it", () => {
const first = replay([
{ type: "menu.toggled", open: true, work: both },
{ type: "shell.selected", item: server, work: both },
{ type: "stop.requested", work: both },
])
]).state
const stale = attempt(first.state)
const attempt = stopOf(first, server)
const listed = transitionShellPanel(first, { type: "back.requested", work: both })
const second = replay(
[
{ type: "back.requested", work: both },
{ type: "shell.selected", item: server, work: both },
{ type: "stop.requested", work: both },
],
first.state,
expect(listed.effects).not.toContainEqual(expect.objectContaining({ type: "timer.cancel" }))
expect(selectShellPanelView(listed.state, both).stoppingKeys).toEqual({ sh_dev: attempt })
expect(transitionShellPanel(listed.state, { type: "stop.requested", item: server, work: both }).state).toBe(
listed.state,
)
const settled = transitionShellPanel(second.state, {
type: "stop.settled",
attempt: stale,
stopped: false,
work: both,
now: 5,
})
const reopened = transitionShellPanel(listed.state, { type: "shell.selected", item: server, work: both }).state
expect(settled.state).toBe(second.state)
expect(selectShellPanelView(settled.state, both).stopDisabled).toBe(true)
expect(selectShellPanelView(reopened, both).stopDisabled).toBe(true)
// The first Stop times out, so a second one starts; the first one's late answer cannot settle it.
const retried = replay(
[
{ type: "stop.timed-out", attempt, work: both },
{ type: "stop.requested", work: both },
],
reopened,
).state
const stale = transitionShellPanel(retried, { type: "stop.settled", attempt, stopped: false, work: both, now: 5 })
expect(stale.state).toBe(retried)
expect(selectShellPanelView(stale.state, both).stopDisabled).toBe(true)
})
test("a stop that never settles gives the button back, or ends the shell that left the list meanwhile", () => {
@ -73,21 +143,20 @@ test("a stop that never settles gives the button back, or ends the shell that le
{ type: "stop.requested", work: both },
]).state
const kept = transitionShellPanel(stopping, { type: "stop.timed-out", attempt: attempt(stopping), work: both })
expect(kept.state).toMatchObject({ status: "shell", phase: { status: "running" } })
expect(kept.effects).toEqual([{ type: "timer.cancel" }])
const attempt = stopOf(stopping, server)
const kept = transitionShellPanel(stopping, { type: "stop.timed-out", attempt, work: both })
const gone = transitionShellPanel(stopping, {
type: "stop.timed-out",
attempt: attempt(stopping),
work: work([watcher]),
})
expect(kept.state).toMatchObject({ status: "shell", phase: { status: "running" } })
expect(selectShellPanelView(kept.state, both).stopDisabled).toBe(false)
expect(kept.effects).toEqual([{ type: "timer.cancel", attempt }])
const gone = transitionShellPanel(stopping, { type: "stop.timed-out", attempt, work: work([watcher]) })
expect(gone.state).toMatchObject({ status: "shell", phase: { status: "ending" } })
expect(gone.effects).toEqual([
{ type: "timer.cancel" },
{ type: "ended.load", attempt: attempt(gone.state), id: "sh_dev" },
{ type: "timer.start", attempt: attempt(gone.state), phase: "ending" },
{ type: "timer.cancel", attempt },
{ type: "ended.load", attempt: endingOf(gone.state), id: "sh_dev" },
{ type: "timer.start", attempt: endingOf(gone.state), phase: "ending" },
])
})
@ -99,13 +168,13 @@ test("a failed Stop after the shell already left the list asks at once how it en
const next = transitionShellPanel(stopping, {
type: "stop.settled",
attempt: attempt(stopping),
attempt: stopOf(stopping, server),
stopped: false,
work: work([watcher]),
now: 5,
})
expect(next.effects).toContainEqual({ type: "ended.load", attempt: attempt(next.state), id: "sh_dev" })
expect(next.effects).toContainEqual({ type: "ended.load", attempt: endingOf(next.state), id: "sh_dev" })
})
test("an exit that never arrives settles the panel as stopped and stops the output and clock", () => {
@ -116,17 +185,18 @@ test("an exit that never arrives settles the panel as stopped and stops the outp
expect(selectShellPanelView(ending, work([server]))).toMatchObject({ stopDisabled: true, tailRunning: false })
const next = transitionShellPanel(ending, { type: "ended.timed-out", attempt: attempt(ending), now: 9 })
const attempt = endingOf(ending)
const next = transitionShellPanel(ending, { type: "ended.timed-out", attempt, now: 9 })
const view = selectShellPanelView(next.state, work([server]))
expect(view.end).toEqual({ status: "killed", exit: undefined, completed: 9 })
expect(view.clockRunning).toBe(false)
expect(next.effects).toEqual([{ type: "timer.cancel" }, { type: "focus.ended" }])
expect(next.effects).toEqual([{ type: "timer.cancel", attempt }, { type: "focus.ended" }])
// The timer and the late answer cannot settle it again.
expect(
transitionShellPanel(next.state, {
type: "ended.settled",
attempt: attempt(ending),
attempt,
info: { status: "exited", exit: 0 },
now: 10,
}).state,
@ -134,17 +204,23 @@ test("an exit that never arrives settles the panel as stopped and stops the outp
})
test("an ended shell keeps counting until the menu closes, then the capsule fades in next time", () => {
const ended = replay([
const shown = replay([
{ type: "menu.toggled", open: true, work: work([watcher]) },
{ type: "shell.selected", item: watcher, work: work([watcher]) },
{ type: "work.synced", work: work([]) },
{ type: "ended.settled", attempt: 3, info: { status: "exited", exit: 1, completed: 7 }, now: 8 },
]).state
const ended = transitionShellPanel(shown, {
type: "ended.settled",
attempt: endingOf(shown),
info: { status: "exited", exit: 1, completed: 7 },
now: 8,
}).state
expect(selectShellPanelView(ended, work([]))).toMatchObject({ active: true, counts: { shells: 1 } })
const closed = transitionShellPanel(ended, { type: "menu.toggled", open: false, work: work([]) })
expect(closed.state).toEqual({ status: "closed", attempt: attempt(ended) + 1, enter: true })
expect(closed.state).toMatchObject({ status: "closed", enter: true })
expect(closed.effects).toEqual([{ type: "focus.cancel" }, { type: "focus.empty" }])
expect(selectShellPanelView(closed.state, work([])).active).toBe(false)
})
@ -159,7 +235,7 @@ test("going back lists the remaining work, or closes the menu when nothing is le
expect(listed.state).toMatchObject({ status: "list", enter: false })
expect(listed.effects).toEqual([
{ type: "focus.cancel" },
{ type: "focus.row", attempt: attempt(listed.state), key: "sh_test" },
{ type: "focus.row", attempt: listed.state.status === "list" ? listed.state.focusAttempt : -1, key: "sh_test" },
])
const closed = transitionShellPanel(shown, { type: "back.requested", work: work([]) })
@ -167,13 +243,13 @@ test("going back lists the remaining work, or closes the menu when nothing is le
expect(closed.effects).toContainEqual({ type: "focus.empty" })
})
test("disposing cancels the pending timer and focus and ignores later results", () => {
test("disposing cancels every timer and the pending focus and ignores later results", () => {
const ending = replay([{ type: "shell.selected", item: watcher, work: work([server]) }]).state
const disposed = transitionShellPanel(ending, { type: "disposed" })
expect(disposed.effects).toEqual([{ type: "timer.cancel" }, { type: "focus.cancel" }])
expect(
transitionShellPanel(disposed.state, { type: "ended.settled", attempt: attempt(ending), info: undefined, now: 1 })
transitionShellPanel(disposed.state, { type: "ended.settled", attempt: endingOf(ending), info: undefined, now: 1 })
.state,
).toBe(disposed.state)
})

View file

@ -15,34 +15,43 @@ export type ShellEnd = {
export type ShellEndInfo = Omit<ShellEnd, "completed"> & { readonly completed?: number }
/** The shown shell. `ending`: it left the running list and the panel waits for how it ended. */
/**
* The shown shell. `ending`: it left the running list and the panel waits for how it ended. A Stop in flight is not a
* phase: it lives in `stopping`, shared with the list's rows.
*/
export type ShellPanelPhase =
| { readonly status: "running" }
| { readonly status: "stopping" }
| { readonly status: "ending" }
| { readonly status: "ending"; readonly attempt: number }
| { readonly status: "ended"; readonly end: ShellEnd }
type ShellPanelBase = {
readonly issued: number
/** Matches the focus move queued by the last view change; a later change drops it. */
readonly focusAttempt: number
readonly enter: boolean
/** Stops in flight, by item key, whether a list row or the shell panel sent them. Closing the menu keeps them. */
readonly stopping: Readonly<Record<string, number>>
}
/**
* The background work menu: shut, open on the list, or open on one shell. A shell that ends while it is shown keeps
* its panel, with how it ended, until the user goes back or closes the menu. `enter`: the capsule fades in when it
* next appears, because it was absent once while this composer was mounted.
*/
export type ShellPanelState =
| { readonly status: "closed"; readonly attempt: number; readonly enter: boolean }
| { readonly status: "list"; readonly attempt: number; readonly enter: boolean }
| {
| (ShellPanelBase & { readonly status: "closed" })
| (ShellPanelBase & { readonly status: "list" })
| (ShellPanelBase & {
readonly status: "shell"
readonly attempt: number
readonly enter: boolean
readonly item: SessionActivityItem
readonly phase: ShellPanelPhase
}
})
| { readonly status: "disposed" }
/** What runs in the background right now. `enabled`: the background activity setting shows the capsule. */
export type ShellPanelWork = {
readonly enabled: boolean
readonly subagents: number
readonly subagents: readonly SessionActivityItem[]
readonly shells: readonly SessionActivityItem[]
}
@ -51,7 +60,8 @@ export type ShellPanelEvent =
| { readonly type: "menu.toggled"; readonly open: boolean; readonly work: ShellPanelWork }
| { readonly type: "shell.selected"; readonly item: SessionActivityItem; readonly work: ShellPanelWork }
| { readonly type: "back.requested"; readonly work: ShellPanelWork }
| { readonly type: "stop.requested"; readonly work: ShellPanelWork }
/** `item`: a list row's Stop; without it, the shown shell's. */
| { readonly type: "stop.requested"; readonly item?: SessionActivityItem; readonly work: ShellPanelWork }
| {
readonly type: "stop.settled"
readonly attempt: number
@ -69,12 +79,13 @@ export type ShellPanelEvent =
| { readonly type: "ended.timed-out"; readonly attempt: number; readonly now: number }
| { readonly type: "disposed" }
/** `timer.start` replaces the single pending timer; the `focus.*` effects replace the single pending focus frame. */
/** Timers are keyed by attempt, one per Stop in flight plus the shown shell's end; `focus.*` replace one frame. */
export type ShellPanelEffect =
| { readonly type: "stop.run"; readonly attempt: number; readonly item: SessionActivityItem }
| { readonly type: "ended.load"; readonly attempt: number; readonly id: string }
| { readonly type: "timer.start"; readonly attempt: number; readonly phase: "stopping" | "ending" }
| { readonly type: "timer.cancel" }
/** Without `attempt`, cancels every timer. */
| { readonly type: "timer.cancel"; readonly attempt?: number }
| { readonly type: "focus.back"; readonly attempt: number }
| { readonly type: "focus.row"; readonly attempt: number; readonly key: string }
| { readonly type: "focus.empty" }
@ -88,7 +99,9 @@ export type ShellPanelTransition = {
const NO_EFFECTS: readonly ShellPanelEffect[] = Object.freeze([])
const TIMER_CANCEL: ShellPanelEffect = Object.freeze({ type: "timer.cancel" })
const NO_STOPS: Readonly<Record<string, number>> = Object.freeze({})
const TIMERS_CANCEL: ShellPanelEffect = Object.freeze({ type: "timer.cancel" })
const FOCUS_CANCEL: ShellPanelEffect = Object.freeze({ type: "focus.cancel" })
@ -100,39 +113,41 @@ const DISPOSED: ShellPanelState = Object.freeze({ status: "disposed" })
/** `active`: the capsule already shows on mount, so it stays at rest rather than fading in. */
export function createShellPanelState(input: { active: boolean }): ShellPanelState {
return { status: "closed", attempt: 0, enter: !input.active }
return { status: "closed", issued: 0, focusAttempt: 0, enter: !input.active, stopping: NO_STOPS }
}
export function transitionShellPanel(state: ShellPanelState, event: ShellPanelEvent): ShellPanelTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") return changed(DISPOSED, cleanup(state))
if (event.type === "disposed") return changed(DISPOSED, [TIMERS_CANCEL, FOCUS_CANCEL])
if (event.type === "work.synced") return workSynced(state, event.work)
if (event.type === "menu.toggled") {
if (event.open)
return state.status === "closed" && event.work.enabled && count(event.work) > 0
? changed({ status: "list", attempt: state.attempt + 1, enter: state.enter }, [FOCUS_CANCEL])
: unchanged(state)
if (event.type === "stop.requested") return requestStop(state, event)
return state.status === "closed" ? unchanged(state) : close(state, event.work)
if (event.type === "stop.settled" || event.type === "stop.timed-out") return settleStop(state, event)
if (event.type === "menu.toggled") {
if (!event.open) return state.status === "closed" ? unchanged(state) : close(state, event.work)
if (state.status !== "closed" || !event.work.enabled || count(event.work) === 0) return unchanged(state)
const issued = state.issued + 1
return changed({ ...state, status: "list", issued, focusAttempt: issued }, [FOCUS_CANCEL])
}
if (event.type === "shell.selected") {
const attempt = state.attempt + 1
const focus: ShellPanelEffect = { type: "focus.back", attempt }
const issued = state.issued + 1
const base = { issued, focusAttempt: issued, enter: state.enter, stopping: state.stopping }
const effects: ShellPanelEffect[] = [...leave(state), { type: "focus.back", attempt: issued }]
if (running(event.work, event.item))
return changed({ status: "shell", attempt, enter: state.enter, item: event.item, phase: { status: "running" } }, [
...cleanup(state),
focus,
])
// A shell whose Stop is in flight keeps its panel running until the Stop settles, so the panel shows it stopping.
if (state.stopping[event.item.key] !== undefined || running(event.work, event.item))
return changed({ ...base, status: "shell", item: event.item, phase: { status: "running" } }, effects)
return changed({ status: "shell", attempt, enter: state.enter, item: event.item, phase: { status: "ending" } }, [
...cleanup(state),
focus,
...ending(attempt, event.item),
return changed({ ...base, status: "shell", item: event.item, phase: { status: "ending", attempt: issued } }, [
...effects,
...ending(issued, event.item),
])
}
@ -140,58 +155,28 @@ export function transitionShellPanel(state: ShellPanelState, event: ShellPanelEv
if (event.type === "back.requested") {
if (count(event.work) === 0) return close(state, event.work)
const issued = state.issued + 1
const attempt = state.attempt + 1
return changed({ status: "list", attempt, enter: state.enter }, [
...cleanup(state),
{ type: "focus.row", attempt, key: state.item.key },
return changed({ status: "list", issued, focusAttempt: issued, enter: state.enter, stopping: state.stopping }, [
...leave(state),
{ type: "focus.row", attempt: issued, key: state.item.key },
])
}
if (event.type === "stop.requested") {
// A shell that already left the list is ending on its own; stopping it now would report it as stopped.
if (state.phase.status !== "running" || !running(event.work, state.item)) return unchanged(state)
const attempt = state.attempt + 1
return changed({ ...state, attempt, phase: { status: "stopping" } }, [
{ type: "stop.run", attempt, item: state.item },
{ type: "timer.start", attempt, phase: "stopping" },
])
}
if (event.type === "stop.settled" || event.type === "stop.timed-out") {
if (state.phase.status !== "stopping" || event.attempt !== state.attempt) return unchanged(state)
const attempt = state.attempt + 1
if (event.type === "stop.settled" && event.stopped)
return changed(
{ ...state, attempt, phase: { status: "ended", end: { status: "killed", completed: event.now } } },
[TIMER_CANCEL, FOCUS_ENDED],
)
// A Stop that failed leaves the shell running, unless it left the list meanwhile and ends on its own.
if (running(event.work, state.item))
return changed({ ...state, attempt, phase: { status: "running" } }, [TIMER_CANCEL])
return changed({ ...state, attempt, phase: { status: "ending" } }, [TIMER_CANCEL, ...ending(attempt, state.item)])
}
if (event.type === "ended.settled" || event.type === "ended.timed-out") {
if (state.phase.status !== "ending" || event.attempt !== state.attempt) return unchanged(state)
if (state.phase.status !== "ending" || event.attempt !== state.phase.attempt) return unchanged(state)
// Removing a running shell ends it as killed, and the server forgets it.
const info = event.type === "ended.settled" ? event.info : undefined
return changed(
{
...state,
attempt: state.attempt + 1,
phase: {
status: "ended",
end: { status: info?.status ?? "killed", exit: info?.exit, completed: info?.completed ?? event.now },
},
},
[TIMER_CANCEL, FOCUS_ENDED],
[{ type: "timer.cancel", attempt: event.attempt }, FOCUS_ENDED],
)
}
@ -202,8 +187,10 @@ export function selectShellPanelView(state: ShellPanelState, work: ShellPanelWor
const shell = state.status === "shell" ? state : undefined
// A shell that ended while its panel is open still counts until the menu closes.
const held = shell && !running(work, shell.item) ? 1 : 0
const counts = { subagents: work.subagents, shells: work.shells.length + held }
const counts = { subagents: work.subagents.length, shells: work.shells.length + held }
const phase = shell?.phase.status
const stoppingKeys = state.status === "disposed" ? NO_STOPS : state.stopping
const stopping = !!shell && stoppingKeys[shell.item.key] !== undefined
return {
counts,
@ -211,16 +198,62 @@ export function selectShellPanelView(state: ShellPanelState, work: ShellPanelWor
open: state.status === "list" || state.status === "shell",
enter: state.status !== "disposed" && state.enter,
shell: shell?.item,
stopping: phase === "stopping",
stopDisabled: phase === "stopping" || phase === "ending",
/** Rows whose Stop is in flight. */
stoppingKeys,
stopping,
stopDisabled: stopping || phase === "ending",
end: shell?.phase.status === "ended" ? shell.phase.end : undefined,
// Output stops polling once the shell has left the running list; its final read still lands.
tailRunning: phase === "running" || phase === "stopping",
tailRunning: phase === "running",
clockRunning: state.status === "list" || (!!phase && phase !== "ended"),
}
}
function workSynced(state: Exclude<ShellPanelState, { status: "disposed" }>, work: ShellPanelWork) {
type Live = Exclude<ShellPanelState, { status: "disposed" }>
function requestStop(state: Live, event: Extract<ShellPanelEvent, { type: "stop.requested" }>) {
const target = event.item ?? (state.status === "shell" ? state.item : undefined)
if (!target || state.stopping[target.key] !== undefined || !stoppable(event.work, target)) return unchanged(state)
// A shown shell that already left the list is ending on its own; stopping it now would report it as stopped.
if (state.status === "shell" && state.item.key === target.key && state.phase.status !== "running")
return unchanged(state)
const issued = state.issued + 1
return changed({ ...state, issued, stopping: { ...state.stopping, [target.key]: issued } }, [
{ type: "stop.run", attempt: issued, item: target },
{ type: "timer.start", attempt: issued, phase: "stopping" },
])
}
function settleStop(state: Live, event: Extract<ShellPanelEvent, { type: "stop.settled" | "stop.timed-out" }>) {
const key = Object.keys(state.stopping).find((entry) => state.stopping[entry] === event.attempt)
if (key === undefined) return unchanged(state)
const stopping = Object.fromEntries(Object.entries(state.stopping).filter(([entry]) => entry !== key))
const cancel: ShellPanelEffect = { type: "timer.cancel", attempt: event.attempt }
if (state.status !== "shell" || state.item.key !== key || state.phase.status !== "running")
return changed({ ...state, stopping }, [cancel])
if (event.type === "stop.settled" && event.stopped)
return changed(
{ ...state, stopping, phase: { status: "ended", end: { status: "killed", completed: event.now } } },
[cancel, FOCUS_ENDED],
)
// A Stop that failed leaves the shell running, unless it left the list meanwhile and ends on its own.
if (running(event.work, state.item)) return changed({ ...state, stopping }, [cancel])
const issued = state.issued + 1
return changed({ ...state, issued, stopping, phase: { status: "ending", attempt: issued } }, [
cancel,
...ending(issued, state.item),
])
}
function workSynced(state: Live, work: ShellPanelWork) {
if (state.status === "closed")
return !active(state, work) && !state.enter ? changed({ ...state, enter: true }) : unchanged(state)
@ -228,26 +261,36 @@ function workSynced(state: Exclude<ShellPanelState, { status: "disposed" }>, wor
if (!work.enabled) return close(state, work)
if (state.phase.status !== "running" || running(work, state.item)) return unchanged(state)
const attempt = state.attempt + 1
// A shell being stopped waits for its Stop to report how it ended.
if (state.phase.status !== "running" || state.stopping[state.item.key] !== undefined || running(work, state.item))
return unchanged(state)
const issued = state.issued + 1
return changed({ ...state, attempt, phase: { status: "ending" } }, ending(attempt, state.item))
return changed({ ...state, issued, phase: { status: "ending", attempt: issued } }, ending(issued, state.item))
}
// The menu always opens on the list, and closing forgets the shell so nothing follows it while the menu is shut. With
// nothing left to list, the capsule goes and focus moves to the composer.
// nothing left to list, the capsule goes and focus moves to the composer. Stops in flight carry on.
function close(state: Extract<ShellPanelState, { status: "list" | "shell" }>, work: ShellPanelWork) {
const empty = count(work) === 0
const issued = state.issued + 1
return changed({ status: "closed", attempt: state.attempt + 1, enter: state.enter || empty || !work.enabled }, [
...cleanup(state),
...(empty ? [FOCUS_EMPTY] : []),
])
return changed(
{
status: "closed",
issued,
focusAttempt: issued,
enter: state.enter || empty || !work.enabled,
stopping: state.stopping,
},
[...leave(state), ...(empty ? [FOCUS_EMPTY] : [])],
)
}
function cleanup(state: Exclude<ShellPanelState, { status: "disposed" }>): readonly ShellPanelEffect[] {
if (state.status === "shell" && (state.phase.status === "stopping" || state.phase.status === "ending"))
return [TIMER_CANCEL, FOCUS_CANCEL]
// Leaving a view drops its queued focus move and the shown shell's end lookup.
function leave(state: Live): readonly ShellPanelEffect[] {
if (state.status === "shell" && state.phase.status === "ending")
return [{ type: "timer.cancel", attempt: state.phase.attempt }, FOCUS_CANCEL]
return [FOCUS_CANCEL]
}
@ -259,7 +302,7 @@ function ending(attempt: number, item: SessionActivityItem): readonly ShellPanel
]
}
function active(state: Exclude<ShellPanelState, { status: "disposed" }>, work: ShellPanelWork) {
function active(state: Live, work: ShellPanelWork) {
return selectShellPanelView(state, work).active
}
@ -267,8 +310,15 @@ function running(work: ShellPanelWork, item: SessionActivityItem) {
return work.shells.some((shell) => shell.key === item.key)
}
// A subagent can only be interrupted once its child session exists.
function stoppable(work: ShellPanelWork, item: SessionActivityItem) {
if (item.type === "shell") return running(work, item)
return !!item.sessionID && work.subagents.some((subagent) => subagent.key === item.key)
}
function count(work: ShellPanelWork) {
return work.subagents + work.shells.length
return work.subagents.length + work.shells.length
}
function changed(state: ShellPanelState, effects: readonly ShellPanelEffect[] = NO_EFFECTS): ShellPanelTransition {

View file

@ -29,14 +29,15 @@ export function createShellPanel(input: {
ended: () => void
}
}) {
const work = () => ({ enabled: input.enabled(), subagents: input.subagents().length, shells: input.shells() })
const work = () => ({ enabled: input.enabled(), subagents: input.subagents(), shells: input.shells() })
const initial = untrack(work)
const [panelState, setPanelState] = createSignal(
createShellPanelState({ active: initial.enabled && initial.subagents + initial.shells.length > 0 }),
createShellPanelState({ active: initial.enabled && initial.subagents.length + initial.shells.length > 0 }),
)
let timer: ReturnType<typeof setTimeout> | undefined
// One per Stop in flight, plus the shown shell's end lookup, keyed by attempt.
const timers = new Map<number, ReturnType<typeof setTimeout>>()
let frame = 0
const dispatch = (event: ShellPanelEvent) => {
@ -49,7 +50,7 @@ export function createShellPanel(input: {
const current = (attempt: number) => {
const state = untrack(panelState)
return state.status !== "disposed" && state.attempt === attempt
return state.status !== "disposed" && state.focusAttempt === attempt
}
const later = (move: () => void) => {
@ -77,24 +78,35 @@ export function createShellPanel(input: {
}
if (effect.type === "timer.start") {
clearTimeout(timer)
timer =
effect.phase === "stopping"
? setTimeout(
() => dispatch({ type: "stop.timed-out", attempt: effect.attempt, work: untrack(work) }),
SHELL_STOP_TIMEOUT_MS,
)
: setTimeout(
() => dispatch({ type: "ended.timed-out", attempt: effect.attempt, now: Date.now() }),
SHELL_END_TIMEOUT_MS,
clearTimeout(timers.get(effect.attempt))
timers.set(
effect.attempt,
setTimeout(
() => {
timers.delete(effect.attempt)
dispatch(
effect.phase === "stopping"
? { type: "stop.timed-out", attempt: effect.attempt, work: untrack(work) }
: { type: "ended.timed-out", attempt: effect.attempt, now: Date.now() },
)
},
effect.phase === "stopping" ? SHELL_STOP_TIMEOUT_MS : SHELL_END_TIMEOUT_MS,
),
)
return
}
if (effect.type === "timer.cancel") {
clearTimeout(timer)
timer = undefined
if (effect.attempt === undefined) {
timers.forEach(clearTimeout)
timers.clear()
return
}
clearTimeout(timers.get(effect.attempt))
timers.delete(effect.attempt)
return
}
@ -121,7 +133,8 @@ export function createShellPanel(input: {
toggle: (open: boolean) => dispatch({ type: "menu.toggled", open, work: untrack(work) }),
open: (item: SessionActivityItem) => dispatch({ type: "shell.selected", item, work: untrack(work) }),
back: () => dispatch({ type: "back.requested", work: untrack(work) }),
stop: () => dispatch({ type: "stop.requested", work: untrack(work) }),
/** Without `item`, stops the shown shell. */
stop: (item?: SessionActivityItem) => dispatch({ type: "stop.requested", item, work: untrack(work) }),
}
}