fix(app): fence session navigation, share session exports, and claim Home delete and import (#62101)

This commit is contained in:
Luke Parker
2026-11-05 09:42:51 -06:00
committed by GitHub
Unverified
parent 2f31b3d52c
commit 121d822c07
28 changed files with 1399 additions and 547 deletions
+11 -5
View File
@@ -138,13 +138,19 @@ test("the session context menu renames, exports, and deletes a Home session", as
await expect(dialog).toContainText('Delete session "Renamed from Home"?')
await expect(dialog.getByRole("button", { name: "Cancel", exact: true })).toBeFocused()
const removed = page.waitForRequest(
(request) => request.method() === "DELETE" && new URL(request.url()).pathname.endsWith(`/${fixture.targetID}`),
)
const removed = await holdRoute(page, (url) => url.pathname.endsWith(`/session/${fixture.targetID}`), {
method: "DELETE",
})
await dialog.getByRole("button", { name: "Delete session" }).click()
await removed
// A double click claims one delete: the dialog stays open, with both buttons disabled, until the server answers.
await dialog.getByRole("button", { name: "Delete session" }).dblclick()
await removed.arrived
await expect(dialog.getByRole("button", { name: "Delete session" })).toBeDisabled()
await expect(dialog.getByRole("button", { name: "Cancel", exact: true })).toBeDisabled()
removed.release()
await expect(dialog).toBeHidden()
await expect(renamedRow).toBeHidden()
expect(removed.requests).toHaveLength(1)
})
test("a failed session list says so and loads again on Try again, instead of showing the empty state", async ({
+114 -28
View File
@@ -1,5 +1,8 @@
import { Schema } from "effect"
import { useLocation } from "@solidjs/router"
import { createSignal, onCleanup, untrack } from "solid-js"
import { useDialog } from "@opencode/ui/context/dialog"
import { toaster } from "@opencode/ui/toast"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { ServerConnection } from "@/runtime/server/registry"
@@ -10,11 +13,21 @@ import { errorMessage } from "@/shell/layout/helpers"
import { showToast } from "@/shell/notifications/toast"
import type { LocalProject } from "@/shell/state/layout"
import { createProjectSessionActions } from "@/shell/tabs/project-sessions"
import {
INITIAL_PROJECT_IMPORT_STATE,
selectProjectImporting,
transitionProjectImport,
type ProjectImportEffect,
type ProjectImportEvent,
type ProjectImportTarget,
} from "./import-machine"
import { useRevealProject } from "./reveal"
export function createProjectActions() {
const platform = usePlatform()
const location = useLocation()
const dialog = useDialog()
const language = useLanguage()
@@ -44,6 +57,102 @@ export function createProjectActions() {
const directories = (project: LocalProject) => [project.worktree, ...(project.sandboxes ?? [])]
const currentPath = () => location.pathname + location.search
const [importState, setImportState] = createSignal(INITIAL_PROJECT_IMPORT_STATE)
let pendingToast: number | undefined
const dispatchImport = (event: ProjectImportEvent) => {
const previous = untrack(importState)
const next = transitionProjectImport(previous, event)
if (next.state !== previous) setImportState(next.state)
next.effects.forEach((effect) =>
Promise.try(() => runImport(effect)).catch((cause: unknown) => console.error("[project.import]", cause)),
)
}
function runImport(effect: ProjectImportEffect) {
if (effect.type === "picker.open") {
// Keep only the file: the picker releases its read access once the callback returns, not after the upload.
let picked: File | undefined
if (!platform.openAttachmentPickerDialog)
return dispatchImport({ type: "picker.closed", attempt: effect.attempt, file: undefined })
void platform
.openAttachmentPickerDialog(
{ title: language.t("command.session.import"), accept: ["application/json"], extensions: ["json"] },
async (file) => {
picked = file
},
)
.then(
() => dispatchImport({ type: "picker.closed", attempt: effect.attempt, file: picked }),
(cause: unknown) => dispatchImport({ type: "picker.failed", attempt: effect.attempt, cause }),
)
return
}
if (effect.type === "upload.start") {
void upload(effect.target, effect.file).then(
(session) =>
dispatchImport({
type: "import.succeeded",
attempt: effect.attempt,
target: effect.target,
session,
currentPath: untrack(currentPath),
}),
(cause: unknown) => dispatchImport({ type: "import.failed", attempt: effect.attempt, cause }),
)
return
}
if (effect.type === "toast.pending.show") {
pendingToast = showToast({
variant: "loading",
title: language.t("toast.session.import.pending"),
persistent: true,
})
return
}
if (effect.type === "toast.pending.dismiss") {
if (pendingToast !== undefined) toaster.dismiss(pendingToast)
pendingToast = undefined
return
}
if (effect.type === "toast.failed")
return showToast({
title: language.t("common.requestFailed"),
description: errorMessage(effect.cause, language.t("common.requestFailed")),
})
if (effect.type === "session.open")
return sessions.openProjectSession(effect.target.conn, effect.target.worktree, effect.session)
untrack(() => global.serverCtx(ServerConnection.key(effect.target.conn)))?.data.session.remember(effect.session)
}
async function upload(target: ProjectImportTarget, file: File) {
const data = await Schema.decodeUnknownPromise(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)))(
await file.text(),
)
const ctx = untrack(() => global.serverCtx(ServerConnection.key(target.conn)))
if (!ctx) throw new Error(language.t("common.requestFailed"))
const api = ctx.sdk.api.experimental.session
// SAFETY: the import endpoint validates the transcript, including exports written by earlier releases.
return api.import({ ...data, location: { directory: target.worktree } } as Parameters<typeof api.import>[0])
}
onCleanup(() => dispatchImport({ type: "disposed" }))
return {
authenticate,
editServer,
@@ -52,35 +161,12 @@ export function createProjectActions() {
sessions.openProjectNewSession(conn, directory)
},
canImportSession: !!platform.openAttachmentPickerDialog,
importingSession: () => selectProjectImporting(importState()),
importSession(conn: ServerConnection.Any, project: LocalProject) {
if (!platform.openAttachmentPickerDialog) return
void platform
.openAttachmentPickerDialog(
{ title: language.t("command.session.import"), accept: ["application/json"], extensions: ["json"] },
async (file) => {
const data = await Schema.decodeUnknownPromise(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)),
)(await file.text())
const ctx = global.serverCtx(ServerConnection.key(conn))
if (!ctx) throw new Error(language.t("common.requestFailed"))
const api = ctx.sdk.api.experimental.session
// SAFETY: the import endpoint validates the transcript, including exports written by earlier releases.
const imported = await api.import({ ...data, location: { directory: project.worktree } } as Parameters<
typeof api.import
>[0])
sessions.openProjectSession(conn, project.worktree, imported)
},
)
.catch((cause: unknown) => {
showToast({
title: language.t("common.requestFailed"),
description: errorMessage(cause, language.t("common.requestFailed")),
})
})
dispatchImport({
type: "import.requested",
target: { conn, worktree: project.worktree, originPath: currentPath() },
})
},
edit(conn: ServerConnection.Any, project: LocalProject) {
settings.openProject({ server: ServerConnection.key(conn), project: project.worktree })
@@ -84,6 +84,7 @@ export function createHomeProjectsController(home: HomeController) {
add: home.project.add,
openNewSession: actions.openNewSession,
canImportSession: actions.canImportSession,
importingSession: actions.importingSession,
importSession: actions.importSession,
edit: actions.edit,
hasUnread: actions.hasUnread,
@@ -0,0 +1,117 @@
import { expect, test } from "bun:test"
import type { SessionInfo } from "@opencode/client/promise"
import type { ServerConnection } from "@/runtime/server/registry"
import {
INITIAL_PROJECT_IMPORT_STATE,
selectProjectImporting,
transitionProjectImport,
type ProjectImportEvent,
type ProjectImportTransition,
} from "./import-machine"
const conn: ServerConnection.Any = { type: "sidecar", variant: "base", http: { url: "http://127.0.0.1:4096" } }
const target = { conn, worktree: "/repo", originPath: "/" }
const file = new File(["{}"], "transcript.json")
/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- the machine passes the session through untouched */
const imported = { id: "ses_imported" } as SessionInfo
function replay(events: ProjectImportEvent[]) {
return events.reduce<ProjectImportTransition[]>((steps, event) => {
steps.push(transitionProjectImport(steps.at(-1)?.state ?? INITIAL_PROJECT_IMPORT_STATE, event))
return steps
}, [])
}
const picked: ProjectImportEvent[] = [
{ type: "import.requested", target },
{ type: "picker.closed", attempt: 1, file },
]
test("an upload that lands after the user opened another session does not switch tabs", () => {
const [, uploading, moved] = replay([
...picked,
{ type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/server/a/session/ses_other" },
])
const [, , stayed] = replay([
...picked,
{ type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/" },
])
expect(uploading?.effects).toEqual([
{ type: "toast.pending.show" },
{ type: "upload.start", attempt: 1, target, file },
])
expect(moved?.effects).toEqual([
{ type: "toast.pending.dismiss" },
{ type: "session.remember", target, session: imported },
])
expect(stayed?.effects).toEqual([
{ type: "toast.pending.dismiss" },
{ type: "session.open", target, session: imported },
])
expect(moved?.state).toEqual({ status: "idle", attempt: 1 })
})
test("an upload that outlives Home still lands and reports, without taking over the window", () => {
const [, , disposed, succeeded] = replay([
...picked,
{ type: "disposed" },
{ type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/" },
])
const [, , , failed] = replay([...picked, { type: "disposed" }, { type: "import.failed", attempt: 1, cause: "500" }])
expect(disposed?.effects).toEqual([])
expect(succeeded?.state).toBe(disposed!.state)
expect(succeeded?.effects).toEqual([
{ type: "toast.pending.dismiss" },
{ type: "session.remember", target, session: imported },
])
expect(failed?.effects).toEqual([{ type: "toast.pending.dismiss" }, { type: "toast.failed", cause: "500" }])
})
test("Import session again while the picker is open or a transcript uploads starts nothing", () => {
const [picking, again, uploading, onceMore] = replay([
{ type: "import.requested", target },
{ type: "import.requested", target },
{ type: "picker.closed", attempt: 1, file },
{ type: "import.requested", target },
])
expect(picking?.effects).toEqual([{ type: "picker.open", attempt: 1 }])
expect(selectProjectImporting(picking!.state)).toBe(true)
expect(again?.state).toBe(picking!.state)
expect(again?.effects).toEqual([])
expect(selectProjectImporting(uploading!.state)).toBe(true)
expect(onceMore?.state).toBe(uploading!.state)
expect(onceMore?.effects).toEqual([])
})
test("a cancelled picker is quiet, failures toast, and the next import starts a new attempt", () => {
const [, cancelled, retried, stale] = replay([
{ type: "import.requested", target },
{ type: "picker.closed", attempt: 1, file: undefined },
{ type: "import.requested", target },
{ type: "picker.closed", attempt: 1, file },
])
const [, pickerFailed] = replay([
{ type: "import.requested", target },
{ type: "picker.failed", attempt: 1, cause: "denied" },
])
const [, , uploadFailed] = replay([...picked, { type: "import.failed", attempt: 1, cause: "invalid" }])
expect(cancelled?.effects).toEqual([])
expect(selectProjectImporting(cancelled!.state)).toBe(false)
expect(retried?.effects).toEqual([{ type: "picker.open", attempt: 2 }])
expect(stale?.state).toBe(retried!.state)
expect(pickerFailed?.effects).toEqual([{ type: "toast.failed", cause: "denied" }])
expect(uploadFailed?.effects).toEqual([{ type: "toast.pending.dismiss" }, { type: "toast.failed", cause: "invalid" }])
expect(selectProjectImporting(uploadFailed!.state)).toBe(false)
})
@@ -0,0 +1,133 @@
import type { SessionInfo } from "@opencode/client/promise"
import type { ServerConnection } from "@/runtime/server/registry"
/** Where the import was asked from: the imported session opens only while the user is still there. */
export type ProjectImportTarget = {
readonly conn: ServerConnection.Any
readonly worktree: string
readonly originPath: string
}
/**
* Importing a session transcript into a project: the file picker is open, or the transcript is uploading. One import at
* a time. An upload the owner outlives (`disposed`) still lands, and reports, without taking over the window.
*/
export type ProjectImportState =
| { readonly status: "idle"; readonly attempt: number }
| { readonly status: "picking"; readonly attempt: number; readonly target: ProjectImportTarget }
| { readonly status: "importing"; readonly attempt: number; readonly target: ProjectImportTarget }
| { readonly status: "disposed" }
export type ProjectImportEvent =
| { readonly type: "import.requested"; readonly target: ProjectImportTarget }
/** `file`: undefined when the picker was cancelled. */
| { readonly type: "picker.closed"; readonly attempt: number; readonly file: File | undefined }
| { readonly type: "picker.failed"; readonly attempt: number; readonly cause: unknown }
| {
readonly type: "import.succeeded"
readonly attempt: number
readonly target: ProjectImportTarget
readonly session: SessionInfo
readonly currentPath: string
}
| { readonly type: "import.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "disposed" }
export type ProjectImportEffect =
| { readonly type: "picker.open"; readonly attempt: number }
| {
readonly type: "upload.start"
readonly attempt: number
readonly target: ProjectImportTarget
readonly file: File
}
| { readonly type: "toast.pending.show" }
| { readonly type: "toast.pending.dismiss" }
| { readonly type: "toast.failed"; readonly cause: unknown }
| { readonly type: "session.open"; readonly target: ProjectImportTarget; readonly session: SessionInfo }
/** The imported session joins the lists without switching tabs. */
| { readonly type: "session.remember"; readonly target: ProjectImportTarget; readonly session: SessionInfo }
export type ProjectImportTransition = {
readonly state: ProjectImportState
readonly effects: readonly ProjectImportEffect[]
}
const NO_EFFECTS: readonly never[] = Object.freeze([])
const PENDING_DISMISS: ProjectImportEffect = Object.freeze({ type: "toast.pending.dismiss" })
export const INITIAL_PROJECT_IMPORT_STATE: ProjectImportState = Object.freeze({ status: "idle", attempt: 0 })
const DISPOSED: ProjectImportState = Object.freeze({ status: "disposed" })
export function transitionProjectImport(state: ProjectImportState, event: ProjectImportEvent): ProjectImportTransition {
if (state.status === "disposed") {
// Only an upload can outlive its owner, and only one runs at a time.
if (event.type === "import.succeeded")
return {
state,
effects: [PENDING_DISMISS, { type: "session.remember", target: event.target, session: event.session }],
}
if (event.type === "import.failed")
return { state, effects: [PENDING_DISMISS, { type: "toast.failed", cause: event.cause }] }
return { state, effects: NO_EFFECTS }
}
if (event.type === "disposed") return { state: DISPOSED, effects: NO_EFFECTS }
if (event.type === "import.requested") {
// A second Import session while the picker is open or a transcript uploads would run two imports.
if (state.status !== "idle") return { state, effects: NO_EFFECTS }
const attempt = state.attempt + 1
return {
state: { status: "picking", attempt, target: event.target },
effects: [{ type: "picker.open", attempt }],
}
}
if (state.status === "idle" || event.attempt !== state.attempt) return { state, effects: NO_EFFECTS }
const idle: ProjectImportState = { status: "idle", attempt: state.attempt }
if (state.status === "picking") {
if (event.type === "picker.failed") return { state: idle, effects: [{ type: "toast.failed", cause: event.cause }] }
if (event.type !== "picker.closed") return { state, effects: NO_EFFECTS }
if (!event.file) return { state: idle, effects: NO_EFFECTS }
return {
state: { status: "importing", attempt: state.attempt, target: state.target },
effects: [
{ type: "toast.pending.show" },
{ type: "upload.start", attempt: state.attempt, target: state.target, file: event.file },
],
}
}
if (event.type === "import.failed")
return { state: idle, effects: [PENDING_DISMISS, { type: "toast.failed", cause: event.cause }] }
if (event.type !== "import.succeeded") return { state, effects: NO_EFFECTS }
// The user moved on while the transcript uploaded: the import must not pull them away.
return {
state: idle,
effects: [
PENDING_DISMISS,
{
type: event.currentPath === state.target.originPath ? "session.open" : "session.remember",
target: state.target,
session: event.session,
},
],
}
}
export function selectProjectImporting(state: ProjectImportState) {
return state.status === "picking" || state.status === "importing"
}
+5 -1
View File
@@ -11,6 +11,7 @@ export function ProjectMenuItems(props: {
project: LocalProject
unread: boolean
canImportSession: boolean
importingSession?: boolean
canRevealProject: (server: ServerConnection.Any) => boolean
onOpenProjectNewSession: (server: ServerConnection.Any, directory: string) => void
onImportSession: (server: ServerConnection.Any, project: LocalProject) => void
@@ -29,7 +30,10 @@ export function ProjectMenuItems(props: {
{language.t("command.session.new")}
</Menu.Item>
<Show when={props.canImportSession}>
<Menu.Item onSelect={() => props.onImportSession(props.server, props.project)}>
<Menu.Item
disabled={props.importingSession}
onSelect={() => props.onImportSession(props.server, props.project)}
>
{language.t("command.session.import")}
</Menu.Item>
</Show>
@@ -33,6 +33,7 @@ export function HomeProjects(props: {
onSelectProject={props.projects.project.select}
onOpenProjectNewSession={props.projects.project.openNewSession}
canImportSession={props.projects.project.canImportSession}
importingSession={props.projects.project.importingSession()}
onImportSession={props.projects.project.importSession}
onEditProject={props.projects.project.edit}
onRevealProject={props.projects.project.reveal}
+1
View File
@@ -72,6 +72,7 @@ export type HomeProjectsViewProps = {
onSelectProject: (server: ServerConnection.Any, directory: string) => void
onOpenProjectNewSession: (server: ServerConnection.Any, directory: string) => void
canImportSession: boolean
importingSession?: boolean
onImportSession: (server: ServerConnection.Any, project: LocalProject) => void
onEditProject: (server: ServerConnection.Any, project: LocalProject) => void
onRevealProject: (server: ServerConnection.Any, project: LocalProject) => void
+97 -66
View File
@@ -26,7 +26,15 @@ import { errorMessage } from "@/shell/layout/helpers"
import { useSessionTabAvatarState } from "@/shell/layout/project-avatar-state"
import { sessionTreeIDs } from "@/session/requests/session-request-tree"
import { pathKey } from "@/workspaces/path-key"
import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "@/session/commands/export"
import { createSessionExporter } from "@/session/commands/export-session"
import {
createSessionDeleteState,
selectSessionDeleteView,
SESSION_DELETE_TIMEOUT_MS,
transitionSessionDelete,
type SessionDeleteEffect,
type SessionDeleteEvent,
} from "@/session/delete-machine"
import { usePlatform } from "@/runtime/platform/platform"
import { sessionLabel, sessionTitle } from "@/session/title"
import { showToast } from "@/shell/notifications/toast"
@@ -359,78 +367,94 @@ export function createHomeSessionsController(home: HomeController) {
})
}
const exportSession = async (server: ServerConnection.Key, session: SessionInfo) => {
const exporter = createSessionExporter()
const serverContext = (server: ServerConnection.Key) => {
const conn = home.server.list().find((item) => ServerConnection.key(item) === server)
const ctx = conn ? home.server.context(conn) : undefined
if (!ctx) return
try {
const data = await fetchSessionExport({ sessionID: session.id, api: ctx.sdk.api })
const filename = sessionExportFilename(data.info)
if (!(await saveSessionExport(filename, data, platform))) return
showToast({
variant: "success",
icon: "circle-check",
title: language.t("toast.session.export.success.title"),
description: language.t("toast.session.export.success.description", { filename }),
})
} catch (cause) {
showToast({
variant: "error",
title: language.t("toast.session.export.failed.title"),
description: cause instanceof Error ? cause.message : language.t("toast.session.export.failed.description"),
})
}
}
const remove = async (server: ServerConnection.Key, session: SessionInfo) => {
const conn = home.server.list().find((item) => ServerConnection.key(item) === server)
const ctx = conn ? home.server.context(conn) : undefined
if (!conn || !ctx) return false
const ids = sessionTreeIDs(ctx.data.session.list(), session.id)
const rows = homeRowTops()
// The data layer hides the session at once, keeps it hidden after session.deleted, and shows it again if the
// request fails, so the cached index drops it only once the server has.
const request = ctx.data.session.remove(session.id)
animateHomeRowsUp(rows)
return request
.then(() => {
queryClient.setQueryData<SessionInfo[]>(["home-sessions", conn], (current) =>
current?.filter((item) => !ids.includes(item.id)),
)
notifySessionTabsRemoved({
server: ServerConnection.key(conn),
directory: session.location.directory,
sessionIDs: ids,
})
return true
})
.catch((cause) => {
showToast({
title: language.t("session.delete.failed.title"),
description: errorMessage(cause, language.t("session.delete.failed.title")),
})
return false
})
.finally(() => {
void queryClient.invalidateQueries({ queryKey: ["home-sessions", conn], exact: true })
})
return conn && ctx ? { conn, ctx } : undefined
}
function DeleteDialog(props: { server: ServerConnection.Key; session: SessionInfo }) {
const name = () => sessionTitle(props.session.title) ?? language.t("command.session.new")
const [deleteState, setDeleteState] = createSignal(createSessionDeleteState(props.session.id))
let timer: ReturnType<typeof setTimeout> | undefined
const confirm = async () => {
dialog.close()
await remove(props.server, props.session)
const dispatch = (event: SessionDeleteEvent) => {
const next = transitionSessionDelete(untrack(deleteState), event)
if (next.state !== untrack(deleteState)) setDeleteState(next.state)
next.effects.forEach(run)
}
// Read when the user confirms, before the delete hides the session and its children from the list.
const deleteTarget = () => {
const ctx = serverContext(props.server)?.ctx
return ctx ? { removedIDs: sessionTreeIDs(ctx.data.session.list(), props.session.id) } : undefined
}
function run(effect: SessionDeleteEffect) {
if (effect.type === "delete.run") {
const target = serverContext(props.server)
if (!target) return dispatch({ type: "delete.failed", attempt: effect.attempt, cause: undefined })
const rows = homeRowTops()
// The data layer hides the session at once, keeps it hidden after session.deleted, and shows it again if the
// request fails, so the cached index drops it only once the server has.
const request = Promise.try(() => target.ctx.data.session.remove(effect.sessionID))
animateHomeRowsUp(rows)
void request
.finally(() => void queryClient.invalidateQueries({ queryKey: ["home-sessions", target.conn], exact: true }))
.then(
() => dispatch({ type: "delete.succeeded", attempt: effect.attempt, target: effect.target }),
(cause: unknown) => dispatch({ type: "delete.failed", attempt: effect.attempt, cause }),
)
return
}
if (effect.type === "dialog.close") return dialog.close()
if (effect.type === "session.removed") {
const conn = serverContext(props.server)?.conn
if (conn)
queryClient.setQueryData<SessionInfo[]>(["home-sessions", conn], (current) =>
current?.filter((item) => !effect.target.removedIDs.includes(item.id)),
)
notifySessionTabsRemoved({
server: props.server,
directory: props.session.location.directory,
sessionIDs: [...effect.target.removedIDs],
})
return
}
if (effect.type === "toast.delete-failed")
return showToast({
title: language.t("session.delete.failed.title"),
description:
effect.cause === undefined
? undefined
: errorMessage(effect.cause, language.t("session.delete.failed.title")),
})
clearTimeout(timer)
timer = undefined
if (effect.type === "timer.cancel") return
timer = setTimeout(
() => dispatch({ type: "delete.timed-out", attempt: effect.attempt }),
SESSION_DELETE_TIMEOUT_MS,
)
}
onCleanup(() => dispatch({ type: "disposed" }))
const busy = () => selectSessionDeleteView(deleteState()).busy
return (
<Dialog fit>
<DialogHeader hideClose>
@@ -440,10 +464,14 @@ export function createHomeSessionsController(home: HomeController) {
/>
</DialogHeader>
<DialogFooter>
<Button variant="ghost" autofocus onClick={() => dialog.close()}>
<Button variant="ghost" autofocus disabled={busy()} onClick={() => dispatch({ type: "cancel.requested" })}>
{language.t("common.cancel")}
</Button>
<Button variant="danger" onClick={confirm}>
<Button
variant="danger"
disabled={busy()}
onClick={() => dispatch({ type: "confirm.requested", target: deleteTarget() })}
>
{language.t("session.delete.button")}
</Button>
</DialogFooter>
@@ -532,7 +560,10 @@ export function createHomeSessionsController(home: HomeController) {
})
},
rename,
export: exportSession,
export: (server: ServerConnection.Key, session: SessionInfo) =>
exporter.export({ server, sessionID: session.id }),
exporting: (server: ServerConnection.Key, session: SessionInfo) =>
exporter.exporting({ server, sessionID: session.id }),
showDelete: (server: ServerConnection.Key, session: SessionInfo) =>
dialog.show(() => <DeleteDialog server={server} session={session} />),
},
@@ -37,6 +37,7 @@ export function HomeSessions(props: {
onArchiveSession={props.sessions.session.archive}
onRenameSession={props.sessions.session.rename}
onExportSession={props.sessions.session.export}
isExportingSession={props.sessions.session.exporting}
onDeleteSession={props.sessions.session.showDelete}
onSetHoverTarget={props.scroll.viewport.setHoverTarget}
onSetThumbTrack={props.scroll.viewport.setThumbTrack}
+6 -2
View File
@@ -96,7 +96,8 @@ export type HomeSessionsViewProps = {
title: string,
signal: AbortSignal,
) => Promise<boolean>
onExportSession: (server: ServerConnection.Key, session: SessionInfo) => Promise<void>
onExportSession: (server: ServerConnection.Key, session: SessionInfo) => void
isExportingSession: (server: ServerConnection.Key, session: SessionInfo) => boolean
onDeleteSession: (server: ServerConnection.Key, session: SessionInfo) => void
onSetHoverTarget: (element: HTMLElement) => void
onSetThumbTrack: (element: HTMLDivElement) => void
@@ -860,7 +861,10 @@ function HomeSessionRow(
>
{props.language.t("common.rename")}
</Menu.Item>
<Menu.Item onSelect={() => void props.onExportSession(props.server, props.record.session)}>
<Menu.Item
disabled={props.isExportingSession(props.server, props.record.session)}
onSelect={() => props.onExportSession(props.server, props.record.session)}
>
{props.language.t("common.export")}…
</Menu.Item>
<Menu.Separator />
+1
View File
@@ -500,6 +500,7 @@ export const dict = {
"toast.session.export.success.description": "Saved session to {{filename}}",
"toast.session.export.failed.title": "Failed to export session",
"toast.session.export.failed.description": "An error occurred while exporting the session",
"toast.session.import.pending": "Importing session…",
"toast.session.copyID.failed.title": "Failed to copy session ID",
"toast.session.copyID.failed.description": "An error occurred while copying the session ID",
"toast.project.copyID.failed.title": "Failed to copy project ID",
@@ -0,0 +1,99 @@
import { expect, test } from "bun:test"
import type { SessionInfo } from "@opencode/client/promise"
import { ServerConnection } from "@/runtime/server/registry"
import {
createSessionExportState,
selectSessionExporting,
transitionSessionExport,
type SessionExportEvent,
type SessionExportState,
type SessionExportTransition,
} from "./export-machine"
/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- the machine passes export data through untouched */
const exported = { info: { id: "ses_1" } as SessionInfo, messages: [] }
const server = ServerConnection.Key.make("srv_1")
const target = { server, sessionID: "ses_1" }
function replay(events: SessionExportEvent[], from: SessionExportState = createSessionExportState()) {
return events.reduce<SessionExportTransition[]>((steps, event) => {
steps.push(transitionSessionExport(steps.at(-1)?.state ?? from, event))
return steps
}, [])
}
test("Export from the header menu while /export runs, or a second click on a Home row, fetches and saves once", () => {
const [first, repeat, fetched, again, saved] = replay([
{ type: "export.requested", target },
{ type: "export.requested", target: { ...target } },
{ type: "export.fetched", attempt: 1, target, data: exported },
{ type: "export.requested", target },
{ type: "export.saved", attempt: 1, target, filename: "ses_1.json", saved: true },
])
expect(first?.effects).toEqual([{ type: "export.fetch", attempt: 1, target }])
expect(repeat?.state).toBe(first!.state)
expect(repeat?.effects).toEqual([])
// The save dialog may stay open a long time; the export still holds the session until it answers.
expect(fetched?.state).toBe(first!.state)
expect(fetched?.effects).toEqual([{ type: "export.save", attempt: 1, target, data: exported }])
expect(selectSessionExporting(fetched!.state, target)).toBe(true)
expect(again?.effects).toEqual([])
expect(saved?.effects).toEqual([{ type: "toast.exported", filename: "ses_1.json" }])
expect(selectSessionExporting(saved!.state, target)).toBe(false)
})
test("another session, or the same session on another server, exports alongside", () => {
const [, otherSession, otherServer] = replay([
{ type: "export.requested", target },
{ type: "export.requested", target: { server, sessionID: "ses_2" } },
{ type: "export.requested", target: { server: ServerConnection.Key.make("srv_2"), sessionID: "ses_1" } },
])
expect(otherSession?.effects).toEqual([{ type: "export.fetch", attempt: 2, target: { server, sessionID: "ses_2" } }])
expect(otherServer?.effects).toMatchObject([{ type: "export.fetch", attempt: 3 }])
})
test("a cancelled save is quiet, a failure toasts, and a stale result is dropped", () => {
const [, , cancelled] = replay([
{ type: "export.requested", target },
{ type: "export.fetched", attempt: 1, target, data: exported },
{ type: "export.saved", attempt: 1, target, filename: "ses_1.json", saved: false },
])
const [, failed, retried, stale] = replay([
{ type: "export.requested", target },
{ type: "export.failed", attempt: 1, target, message: "timed out" },
{ type: "export.requested", target },
{ type: "export.fetched", attempt: 1, target, data: exported },
])
expect(cancelled?.effects).toEqual([])
expect(selectSessionExporting(cancelled!.state, target)).toBe(false)
expect(failed?.effects).toEqual([{ type: "toast.export-failed", message: "timed out" }])
expect(retried?.effects).toEqual([{ type: "export.fetch", attempt: 2, target }])
expect(stale?.state).toBe(retried!.state)
expect(stale?.effects).toEqual([])
})
test("leaving the screen aborts the fetches still paging, and no save dialog or toast follows", () => {
const [, , disposed, lateFetch, lateFailure] = replay([
{ type: "export.requested", target },
{ type: "export.requested", target: { server, sessionID: "ses_2" } },
{ type: "disposed" },
{ type: "export.fetched", attempt: 1, target, data: exported },
{ type: "export.failed", attempt: 2, target: { server, sessionID: "ses_2" }, message: "aborted" },
])
expect(disposed?.state).toEqual({ status: "disposed" })
expect(disposed?.effects).toEqual([
{ type: "export.abort", attempt: 1 },
{ type: "export.abort", attempt: 2 },
])
expect(lateFetch?.state).toBe(disposed!.state)
expect(lateFetch?.effects).toEqual([])
expect(lateFailure?.effects).toEqual([])
})
@@ -0,0 +1,117 @@
import type { ServerConnection } from "@/runtime/server/registry"
import type { SessionExportData } from "./export"
export type SessionExportTarget = {
readonly server: ServerConnection.Key
readonly sessionID: string
}
/**
* Session exports, keyed by server and session: /export, the session header's menu and Home's rows share one export
* per session, which holds it from the first page fetch until the save dialog answers.
*/
export type SessionExportState =
| {
readonly status: "active"
readonly issued: number
readonly exporting: Readonly<Record<string, number>>
}
| { readonly status: "disposed" }
export type SessionExportEvent =
| { readonly type: "export.requested"; readonly target: SessionExportTarget }
| {
readonly type: "export.fetched"
readonly attempt: number
readonly target: SessionExportTarget
readonly data: SessionExportData
}
| {
readonly type: "export.saved"
readonly attempt: number
readonly target: SessionExportTarget
readonly filename: string
readonly saved: boolean
}
| {
readonly type: "export.failed"
readonly attempt: number
readonly target: SessionExportTarget
readonly message?: string
}
| { readonly type: "disposed" }
export type SessionExportEffect =
| { readonly type: "export.fetch"; readonly attempt: number; readonly target: SessionExportTarget }
| {
readonly type: "export.save"
readonly attempt: number
readonly target: SessionExportTarget
readonly data: SessionExportData
}
| { readonly type: "export.abort"; readonly attempt: number }
| { readonly type: "toast.exported"; readonly filename: string }
| { readonly type: "toast.export-failed"; readonly message?: string }
export type SessionExportTransition = {
readonly state: SessionExportState
readonly effects: readonly SessionExportEffect[]
}
const NO_EFFECTS: readonly never[] = Object.freeze([])
export function createSessionExportState(): SessionExportState {
return { status: "active", issued: 0, exporting: {} }
}
export function transitionSessionExport(state: SessionExportState, event: SessionExportEvent): SessionExportTransition {
if (state.status === "disposed") return { state, effects: NO_EFFECTS }
if (event.type === "disposed") {
return {
state: { status: "disposed" },
effects: Object.values(state.exporting).map((attempt) => ({ type: "export.abort", attempt })),
}
}
const key = sessionExportKey(event.target)
if (event.type === "export.requested") {
// Another surface, or a second click, joins the export already running for this session.
if (state.exporting[key] !== undefined) return { state, effects: NO_EFFECTS }
const attempt = state.issued + 1
return {
state: { status: "active", issued: attempt, exporting: { ...state.exporting, [key]: attempt } },
effects: [{ type: "export.fetch", attempt, target: event.target }],
}
}
if (state.exporting[key] !== event.attempt) return { state, effects: NO_EFFECTS }
// The save dialog may stay open a long time; the export still holds the session until it answers.
if (event.type === "export.fetched")
return {
state,
effects: [{ type: "export.save", attempt: event.attempt, target: event.target, data: event.data }],
}
const next: SessionExportState = {
...state,
exporting: Object.fromEntries(Object.entries(state.exporting).filter(([entry]) => entry !== key)),
}
if (event.type === "export.failed")
return { state: next, effects: [{ type: "toast.export-failed", message: event.message }] }
// A cancelled save dialog is not a failure.
return { state: next, effects: event.saved ? [{ type: "toast.exported", filename: event.filename }] : NO_EFFECTS }
}
export function selectSessionExporting(state: SessionExportState, target: SessionExportTarget) {
return state.status === "active" && state.exporting[sessionExportKey(target)] !== undefined
}
function sessionExportKey(target: SessionExportTarget) {
return `${target.server}\0${target.sessionID}`
}
@@ -0,0 +1,108 @@
import { createSimpleContext } from "@opencode/ui/context"
import { createSignal, onCleanup, untrack } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { useGlobal } from "@/runtime/server/runtime"
import { showToast } from "@/shell/notifications/toast"
import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "./export"
import {
createSessionExportState,
selectSessionExporting,
transitionSessionExport,
type SessionExportEffect,
type SessionExportEvent,
type SessionExportTarget,
} from "./export-machine"
/** Runs session exports for its owner's lifetime; leaving the owner aborts the fetches still paging. */
export function createSessionExporter() {
const global = useGlobal()
const language = useLanguage()
const platform = usePlatform()
const [exportState, setExportState] = createSignal(createSessionExportState())
const fetches = new Map<number, AbortController>()
const dispatch = (event: SessionExportEvent) => {
const previous = untrack(exportState)
const next = transitionSessionExport(previous, event)
if (next.state !== previous) setExportState(next.state)
next.effects.forEach((effect) =>
Promise.try(() => run(effect)).catch((cause: unknown) => console.error("[session.export]", cause)),
)
}
const failed = (attempt: number, target: SessionExportTarget) => (cause: unknown) =>
dispatch({
type: "export.failed",
attempt,
target,
message: cause instanceof Error ? cause.message : undefined,
})
function run(effect: SessionExportEffect) {
if (effect.type === "export.fetch") {
const api = untrack(() => global.serverCtx(effect.target.server))?.sdk.api
if (!api) return dispatch({ type: "export.failed", attempt: effect.attempt, target: effect.target })
const controller = new AbortController()
fetches.set(effect.attempt, controller)
void fetchSessionExport({ sessionID: effect.target.sessionID, api, signal: controller.signal })
.finally(() => fetches.delete(effect.attempt))
.then(
(data) => dispatch({ type: "export.fetched", attempt: effect.attempt, target: effect.target, data }),
failed(effect.attempt, effect.target),
)
return
}
if (effect.type === "export.abort") {
fetches.get(effect.attempt)?.abort()
fetches.delete(effect.attempt)
return
}
if (effect.type === "export.save") {
const filename = sessionExportFilename(effect.data.info)
void Promise.try(() => saveSessionExport(filename, effect.data, platform)).then(
(saved) => dispatch({ type: "export.saved", attempt: effect.attempt, target: effect.target, filename, saved }),
failed(effect.attempt, effect.target),
)
return
}
if (effect.type === "toast.exported") {
showToast({
variant: "success",
icon: "circle-check",
title: language.t("toast.session.export.success.title"),
description: language.t("toast.session.export.success.description", { filename: effect.filename }),
})
return
}
showToast({
variant: "error",
title: language.t("toast.session.export.failed.title"),
description: effect.message ?? language.t("toast.session.export.failed.description"),
})
}
onCleanup(() => dispatch({ type: "disposed" }))
return {
export: (target: SessionExportTarget) => dispatch({ type: "export.requested", target }),
exporting: (target: SessionExportTarget) => selectSessionExporting(exportState(), target),
}
}
/** One exporter for the session screen, so /export and the header menu share each session's export. */
export const { use: useSessionExporter, provider: SessionExportProvider } = createSimpleContext({
name: "SessionExport",
gate: false,
init: createSessionExporter,
})
@@ -1,5 +1,4 @@
import { describe, expect, test } from "bun:test"
import type { SessionInfo } from "@opencode/client/promise"
import {
createCloseTabGuardState,
createSessionCommandsState,
@@ -14,9 +13,6 @@ import {
type SessionCommandsTransition,
} from "./machine"
/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- the machine passes export data through untouched */
const exported = { info: { id: "ses_1" } as SessionInfo, messages: [] }
function replay(events: SessionCommandsEvent[], from: SessionCommandsState = createSessionCommandsState()) {
return events.reduce<SessionCommandsTransition[]>((steps, event) => {
steps.push(transitionSessionCommands(steps.at(-1)?.state ?? from, event))
@@ -64,53 +60,15 @@ describe("transitionSessionCommands", () => {
expect(late?.effects).toEqual([])
})
test("a repeated /export while one runs fetches and saves once", () => {
const [first, repeat, fetched, saved] = replay([
{ type: "export.requested", sessionID: "ses_1" },
{ type: "export.requested", sessionID: "ses_1" },
{ type: "export.fetched", attempt: 1, sessionID: "ses_1", data: exported },
{ type: "export.saved", attempt: 1, sessionID: "ses_1", filename: "ses_1.json", saved: true },
])
expect(first?.effects).toEqual([{ type: "export.fetch", attempt: 1, sessionID: "ses_1" }])
expect(repeat?.state).toBe(first!.state)
expect(repeat?.effects).toEqual([])
// The save dialog may stay open a long time; the export still holds the session until it answers.
expect(fetched?.state).toBe(first!.state)
expect(fetched?.effects).toEqual([{ type: "export.save", attempt: 1, sessionID: "ses_1", data: exported }])
expect(saved?.state).toMatchObject({ exporting: {} })
expect(saved?.effects).toEqual([{ type: "toast.exported", filename: "ses_1.json" }])
})
test("a cancelled save is quiet and a failed fetch toasts", () => {
const [, , cancelled] = replay([
{ type: "export.requested", sessionID: "ses_1" },
{ type: "export.fetched", attempt: 1, sessionID: "ses_1", data: exported },
{ type: "export.saved", attempt: 1, sessionID: "ses_1", filename: "ses_1.json", saved: false },
])
const [, failed] = replay([
{ type: "export.requested", sessionID: "ses_1" },
{ type: "export.failed", attempt: 1, sessionID: "ses_1", message: "timed out" },
])
expect(cancelled?.effects).toEqual([])
expect(failed?.effects).toEqual([{ type: "toast.export-failed", message: "timed out" }])
})
test("leaving the session screen aborts exports and silences late results", () => {
const [, , disposed, lateExport, lateCompact] = replay([
test("leaving the session screen silences late results", () => {
const [, disposed, lateCompact] = replay([
{ type: "compact.requested", sessionID: "ses_1" },
{ type: "export.requested", sessionID: "ses_2" },
{ type: "disposed" },
{ type: "export.failed", attempt: 2, sessionID: "ses_2", message: "aborted" },
{ type: "compact.failed", attempt: 1, sessionID: "ses_1", cause: "late" },
])
expect(disposed?.state).toEqual({ status: "disposed" })
expect(disposed?.effects).toEqual([{ type: "export.abort", attempt: 2 }])
expect(lateExport?.state).toBe(disposed!.state)
expect(lateExport?.effects).toEqual([])
expect(lateCompact?.state).toBe(disposed!.state)
expect(lateCompact?.effects).toEqual([])
})
@@ -147,15 +105,14 @@ describe("transitionSessionCommands", () => {
expect(failed?.state).toMatchObject({ forkDialog: { status: "closed" } })
})
test("switching session keeps the other session's compaction and export running", () => {
const [, , changed] = replay([
test("switching session keeps the other session's compaction running", () => {
const [, changed] = replay([
{ type: "compact.requested", sessionID: "ses_1" },
{ type: "export.requested", sessionID: "ses_1" },
{ type: "session.changed", sessionID: "ses_2" },
])
expect(changed?.effects).toEqual([])
expect(changed?.state).toMatchObject({ compacting: { ses_1: 1 }, exporting: { ses_1: 2 } })
expect(changed?.state).toMatchObject({ compacting: { ses_1: 1 } })
})
})
+5 -69
View File
@@ -1,17 +1,14 @@
import type { SessionExportData } from "./export"
// --- Session commands: /compact, /export and opening /fork ---
// --- Session commands: /compact and opening /fork ---
/**
* The session commands stay mounted while tabs switch between sessions, so compactions and exports are keyed by the
* session they run for; the /fork picker loads for the session it was asked from.
* The session commands stay mounted while tabs switch between sessions, so compactions are keyed by the session they
* run for; the /fork picker loads for the session it was asked from. /export runs through `export-machine.ts`.
*/
export type SessionCommandsState =
| {
readonly status: "active"
readonly issued: number
readonly compacting: Readonly<Record<string, number>>
readonly exporting: Readonly<Record<string, number>>
readonly forkDialog:
| { readonly status: "closed" }
| { readonly status: "loading"; readonly attempt: number; readonly sessionID: string }
@@ -22,21 +19,6 @@ export type SessionCommandsEvent =
| { readonly type: "compact.requested"; readonly sessionID: string }
| { readonly type: "compact.succeeded"; readonly attempt: number; readonly sessionID: string }
| { readonly type: "compact.failed"; readonly attempt: number; readonly sessionID: string; readonly cause: unknown }
| { readonly type: "export.requested"; readonly sessionID: string }
| {
readonly type: "export.fetched"
readonly attempt: number
readonly sessionID: string
readonly data: SessionExportData
}
| {
readonly type: "export.saved"
readonly attempt: number
readonly sessionID: string
readonly filename: string
readonly saved: boolean
}
| { readonly type: "export.failed"; readonly attempt: number; readonly sessionID: string; readonly message?: string }
| { readonly type: "fork.requested"; readonly sessionID: string }
| { readonly type: "fork.loaded"; readonly attempt: number }
| { readonly type: "fork.load-failed"; readonly attempt: number; readonly cause: unknown }
@@ -45,19 +27,9 @@ export type SessionCommandsEvent =
export type SessionCommandsEffect =
| { readonly type: "compact.run"; readonly attempt: number; readonly sessionID: string }
| { readonly type: "export.fetch"; readonly attempt: number; readonly sessionID: string }
| {
readonly type: "export.save"
readonly attempt: number
readonly sessionID: string
readonly data: SessionExportData
}
| { readonly type: "export.abort"; readonly attempt: number }
| { readonly type: "fork.load"; readonly attempt: number }
| { readonly type: "fork.show" }
| { readonly type: "toast.request-failed"; readonly cause: unknown }
| { readonly type: "toast.exported"; readonly filename: string }
| { readonly type: "toast.export-failed"; readonly message?: string }
export type SessionCommandsTransition = {
readonly state: SessionCommandsState
@@ -65,7 +37,7 @@ export type SessionCommandsTransition = {
}
export function createSessionCommandsState(): SessionCommandsState {
return { status: "active", issued: 0, compacting: {}, exporting: {}, forkDialog: { status: "closed" } }
return { status: "active", issued: 0, compacting: {}, forkDialog: { status: "closed" } }
}
export function transitionSessionCommands(
@@ -74,12 +46,7 @@ export function transitionSessionCommands(
): SessionCommandsTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") {
return {
state: { status: "disposed" },
effects: Object.values(state.exporting).map((attempt) => ({ type: "export.abort", attempt })),
}
}
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [] }
if (event.type === "compact.requested") {
// A compaction already admitting for this session answers a repeat, which would run with the same request.
@@ -101,37 +68,6 @@ export function transitionSessionCommands(
return { state: next, effects: [{ type: "toast.request-failed", cause: event.cause }] }
}
if (event.type === "export.requested") {
if (state.exporting[event.sessionID] !== undefined) return unchanged(state)
const attempt = state.issued + 1
return {
state: { ...state, issued: attempt, exporting: { ...state.exporting, [event.sessionID]: attempt } },
effects: [{ type: "export.fetch", attempt, sessionID: event.sessionID }],
}
}
if (event.type === "export.fetched") {
if (state.exporting[event.sessionID] !== event.attempt) return unchanged(state)
return {
state,
effects: [{ type: "export.save", attempt: event.attempt, sessionID: event.sessionID, data: event.data }],
}
}
if (event.type === "export.saved" || event.type === "export.failed") {
if (state.exporting[event.sessionID] !== event.attempt) return unchanged(state)
const next = { ...state, exporting: omit(state.exporting, event.sessionID) }
if (event.type === "export.failed") {
return { state: next, effects: [{ type: "toast.export-failed", message: event.message }] }
}
// A cancelled save dialog is not a failure.
return { state: next, effects: event.saved ? [{ type: "toast.exported", filename: event.filename }] : [] }
}
if (event.type === "fork.requested") {
// The picker's chunk is still loading: a repeat would open it twice.
if (state.forkDialog.status !== "closed") return unchanged(state)
@@ -8,11 +8,11 @@ import { useFile, selectionFromLines, type FileSelection } from "@/workspaces/fi
import { useLanguage } from "@/runtime/i18n/language"
import { useComposerState } from "@/composer/persistence"
import { useServerSDK } from "@/runtime/server/client"
import { useData } from "@/runtime/server/current"
import { useData, useServer } from "@/runtime/server/current"
import { formatServerError } from "@/runtime/server/errors"
import { projectSettingsKey, useSettings } from "@/settings/model"
import { showToast } from "@/shell/notifications/toast"
import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "@/session/commands/export"
import { useSessionExporter } from "@/session/commands/export-session"
import { usePlatform } from "@/runtime/platform/platform"
import type { SessionModel } from "@/session/model"
import type { SessionRevert } from "@/session/revert"
@@ -73,9 +73,11 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const language = useLanguage()
const prompt = useComposerState()
const serverSDK = useServerSDK()
const server = useServer()
const data = useData()
const settings = useSettings()
const platform = usePlatform()
const exporter = useSessionExporter()
const pluginScoped = usePluginScoped()
const pluginClaims = usePluginClaims()
@@ -184,7 +186,6 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const permissionsCommand = withCategory(language.t("command.category.permissions"))
const [commandsState, setCommandsState] = createSignal(createSessionCommandsState())
const exportFetches = new Map<number, AbortController>()
let forkModule: typeof import("@/session/commands/fork-dialog") | undefined
const dispatchCommands = (event: SessionCommandsEvent) => {
@@ -207,61 +208,6 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
return
}
if (effect.type === "export.fetch") {
const controller = new AbortController()
exportFetches.set(effect.attempt, controller)
fetchSessionExport({ sessionID: effect.sessionID, api: serverSDK.api, signal: controller.signal })
.finally(() => exportFetches.delete(effect.attempt))
.then(
(exported) =>
dispatchCommands({
type: "export.fetched",
attempt: effect.attempt,
sessionID: effect.sessionID,
data: exported,
}),
(cause: unknown) =>
dispatchCommands({
type: "export.failed",
attempt: effect.attempt,
sessionID: effect.sessionID,
message: cause instanceof Error ? cause.message : undefined,
}),
)
return
}
if (effect.type === "export.abort") {
exportFetches.get(effect.attempt)?.abort()
exportFetches.delete(effect.attempt)
return
}
if (effect.type === "export.save") {
const filename = sessionExportFilename(effect.data.info)
Promise.try(() => saveSessionExport(filename, effect.data, platform)).then(
(saved) =>
dispatchCommands({
type: "export.saved",
attempt: effect.attempt,
sessionID: effect.sessionID,
filename,
saved,
}),
(cause: unknown) =>
dispatchCommands({
type: "export.failed",
attempt: effect.attempt,
sessionID: effect.sessionID,
message: cause instanceof Error ? cause.message : undefined,
}),
)
return
}
if (effect.type === "fork.load") {
import("@/session/commands/fork-dialog").then(
(mod) => {
@@ -282,28 +228,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
return
}
if (effect.type === "toast.request-failed") {
showToast({ title: formatServerError(effect.cause, language.t, language.t("common.requestFailed")) })
return
}
if (effect.type === "toast.exported") {
showToast({
variant: "success",
icon: "circle-check",
title: language.t("toast.session.export.success.title"),
description: language.t("toast.session.export.success.description", { filename: effect.filename }),
})
return
}
showToast({
variant: "error",
title: language.t("toast.session.export.failed.title"),
description: effect.message ?? language.t("toast.session.export.failed.description"),
})
showToast({ title: formatServerError(effect.cause, language.t, language.t("common.requestFailed")) })
}
createEffect(
@@ -318,7 +243,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const exportSession = () => {
const sessionID = actions.session.identity.params.id
if (sessionID) dispatchCommands({ type: "export.requested", sessionID })
if (sessionID) exporter.export({ server: server.key, sessionID })
}
const copySessionID = async () => {
@@ -551,7 +476,9 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
title: language.t("command.session.export"),
description: language.t("command.session.export.description"),
slash: "export",
disabled: !actions.session.identity.params.id,
disabled:
!actions.session.identity.params.id ||
exporter.exporting({ server: server.key, sessionID: actions.session.identity.params.id }),
onSelect: exportSession,
}),
sessionCommand({
@@ -0,0 +1,83 @@
import { expect, test } from "bun:test"
import {
createSessionDeleteState,
selectSessionDeleteView,
transitionSessionDelete,
type SessionDeleteEvent,
type SessionDeleteState,
} from "./delete-machine"
const replay = (events: SessionDeleteEvent[], from = createSessionDeleteState("ses_a")) =>
events.reduce((state: SessionDeleteState, event) => transitionSessionDelete(state, event).state, from)
// The session header reads where to go next; Home only removes the rows.
const header = { removedIDs: ["ses_a"], nextID: "ses_b" }
const home = { removedIDs: ["ses_a", "ses_a_child"] }
test.each([
["session header", header],
["Home", home],
])("%s Delete claims the request at once, so a double click or Cancel waits for it", (_name, target) => {
const deleting = transitionSessionDelete(createSessionDeleteState("ses_a"), { type: "confirm.requested", target })
expect(deleting.effects).toEqual([
{ type: "delete.run", attempt: 1, sessionID: "ses_a", target },
{ type: "timer.start", attempt: 1 },
])
expect(selectSessionDeleteView(deleting.state).busy).toBe(true)
for (const event of [{ type: "confirm.requested", target }, { type: "cancel.requested" }] as const) {
const next = transitionSessionDelete(deleting.state, event)
expect(next.state).toBe(deleting.state)
expect(next.effects).toEqual([])
}
})
test("a delete that fails or hangs returns to the confirmation", () => {
const deleting = replay([{ type: "confirm.requested", target: header }])
for (const event of [
{ type: "delete.failed", attempt: deleting.attempt, cause: new Error("no") },
{ type: "delete.timed-out", attempt: deleting.attempt },
] as const) {
const next = transitionSessionDelete(deleting, event)
expect(next.state.status).toBe("confirming")
expect(selectSessionDeleteView(next.state).busy).toBe(false)
expect(next.effects).toContainEqual(expect.objectContaining({ type: "toast.delete-failed" }))
}
})
test("a delete closes the dialog and leaves the session, even when it lands after the dialog went", () => {
const deleting = replay([{ type: "confirm.requested", target: header }])
const done = transitionSessionDelete(deleting, {
type: "delete.succeeded",
attempt: deleting.attempt,
target: header,
})
expect(done.effects).toEqual([
{ type: "timer.cancel" },
{ type: "dialog.close" },
{ type: "session.removed", sessionID: "ses_a", target: header },
])
const disposed = transitionSessionDelete(deleting, { type: "disposed" })
expect(
transitionSessionDelete(disposed.state, { type: "delete.succeeded", attempt: deleting.attempt, target: header })
.effects,
).toEqual([{ type: "session.removed", sessionID: "ses_a", target: header }])
})
test("confirming a session that is already gone closes the dialog", () => {
const next = transitionSessionDelete(createSessionDeleteState("ses_a"), {
type: "confirm.requested",
target: undefined,
})
expect(next.state.status).toBe("closed")
expect(next.effects).toEqual([{ type: "dialog.close" }])
})
+128
View File
@@ -0,0 +1,128 @@
/** A delete that has not settled by then counts as failed, so the dialog's buttons cannot stay disabled. */
export const SESSION_DELETE_TIMEOUT_MS = 15_000
/** The delete confirmation for one session, in the session header or on Home: asking, or waiting for the server. */
export type SessionDeleteState =
| { readonly status: "confirming"; readonly sessionID: string; readonly attempt: number }
| {
readonly status: "deleting"
readonly sessionID: string
readonly attempt: number
readonly target: SessionDeleteTarget
}
| { readonly status: "closed"; readonly sessionID: string; readonly attempt: number }
| { readonly status: "disposed"; readonly sessionID: string; readonly attempt: number }
/** Read when the user confirms, before the delete hides the session from the list. */
export type SessionDeleteTarget = {
readonly parentID?: string
readonly nextID?: string
readonly removedIDs: readonly string[]
}
export type SessionDeleteEvent =
| { readonly type: "cancel.requested" }
/** `target`: undefined once the session is gone. */
| { readonly type: "confirm.requested"; readonly target: SessionDeleteTarget | undefined }
| { readonly type: "delete.succeeded"; readonly attempt: number; readonly target: SessionDeleteTarget }
| { readonly type: "delete.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "delete.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type SessionDeleteEffect =
| {
readonly type: "delete.run"
readonly attempt: number
readonly sessionID: string
readonly target: SessionDeleteTarget
}
| { readonly type: "timer.start"; readonly attempt: number }
| { readonly type: "timer.cancel" }
| { readonly type: "dialog.close" }
| { readonly type: "session.removed"; readonly sessionID: string; readonly target: SessionDeleteTarget }
| { readonly type: "toast.delete-failed"; readonly cause?: unknown }
export type SessionDeleteTransition = {
readonly state: SessionDeleteState
readonly effects: readonly SessionDeleteEffect[]
}
const NO_EFFECTS: readonly never[] = Object.freeze([])
const TIMER_CANCEL: SessionDeleteEffect = Object.freeze({ type: "timer.cancel" })
const DIALOG_CLOSE: SessionDeleteEffect = Object.freeze({ type: "dialog.close" })
export function createSessionDeleteState(sessionID: string): SessionDeleteState {
return { status: "confirming", sessionID, attempt: 0 }
}
export function transitionSessionDelete(state: SessionDeleteState, event: SessionDeleteEvent): SessionDeleteTransition {
if (state.status === "closed" || state.status === "disposed") {
// The server deleted the session after the dialog went: it still leaves the session and its tabs.
if (event.type === "delete.succeeded")
return { state, effects: [{ type: "session.removed", sessionID: state.sessionID, target: event.target }] }
return { state, effects: NO_EFFECTS }
}
if (event.type === "disposed")
return {
state: { status: "disposed", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: state.status === "deleting" ? [TIMER_CANCEL] : NO_EFFECTS,
}
if (state.status === "confirming") {
// A delete that timed out can still land; the session is gone, so the dialog goes too.
if (event.type === "delete.succeeded") return deleted(state, event.target)
if (event.type === "cancel.requested" || (event.type === "confirm.requested" && !event.target))
return { state: { ...state, status: "closed", attempt: state.attempt + 1 }, effects: [DIALOG_CLOSE] }
if (event.type !== "confirm.requested" || !event.target) return { state, effects: NO_EFFECTS }
const attempt = state.attempt + 1
return {
state: { status: "deleting", sessionID: state.sessionID, attempt, target: event.target },
effects: [
{ type: "delete.run", attempt, sessionID: state.sessionID, target: event.target },
{ type: "timer.start", attempt },
],
}
}
// A second click, Enter or Cancel waits for the delete in flight.
if (event.type !== "delete.succeeded" && event.type !== "delete.failed" && event.type !== "delete.timed-out")
return { state, effects: NO_EFFECTS }
if (event.attempt !== state.attempt) return { state, effects: NO_EFFECTS }
if (event.type === "delete.succeeded") return deleted(state, event.target)
// A failed delete keeps the dialog, so the user can retry or cancel.
return {
state: { status: "confirming", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: [
TIMER_CANCEL,
{ type: "toast.delete-failed", cause: event.type === "delete.failed" ? event.cause : undefined },
],
}
}
export function selectSessionDeleteView(state: SessionDeleteState) {
return { busy: state.status !== "confirming" }
}
function deleted(
state: Extract<SessionDeleteState, { status: "confirming" | "deleting" }>,
target: SessionDeleteTarget,
): SessionDeleteTransition {
return {
state: { status: "closed", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: [
...(state.status === "deleting" ? [TIMER_CANCEL] : []),
DIALOG_CLOSE,
{ type: "session.removed", sessionID: state.sessionID, target },
],
}
}
@@ -15,21 +15,22 @@ import { sessionTreeIDs } from "@/session/requests/session-request-tree"
import { useServerSDK } from "@/runtime/server/client"
import { sessionHref } from "@/shell/routes/session"
import { sessionTitle } from "@/session/title"
import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "@/session/commands/export"
import { showToast } from "@/shell/notifications/toast"
import { usePlatform } from "@/runtime/platform/platform"
import { applyTimelineMessageHandoff, timelineChildTitle, visibleTimelineMessages } from "./controller-projection"
import {
createSessionDeleteState,
createSessionHeaderTitleState,
selectSessionDeleteView,
selectSessionHeaderTitleView,
SESSION_DELETE_TIMEOUT_MS,
SESSION_RENAME_TIMEOUT_MS,
transitionSessionDelete,
transitionSessionHeaderTitle,
type SessionDeleteEffect,
type SessionDeleteEvent,
} from "@/session/delete-machine"
import { useSessionExporter } from "@/session/commands/export-session"
import {
createSessionHeaderTitleState,
selectSessionHeaderTitleView,
SESSION_RENAME_TIMEOUT_MS,
transitionSessionHeaderTitle,
type SessionHeaderTitleEffect,
type SessionHeaderTitleEvent,
} from "./header-actions-machine"
@@ -78,7 +79,7 @@ export function createTimelineController(input: { session: TimelineSessionSource
const tabs = useTabs()
const dialog = useDialog()
const language = useLanguage()
const platform = usePlatform()
const exporter = useSessionExporter()
// Pending inputs and the handoff hold with the history while the view is detached, so a hidden view never shows
// one against history it has not caught up with.
@@ -298,27 +299,6 @@ export function createTimelineController(input: { session: TimelineSessionSource
return tabs.newDraft({ server: server.key, directory: sdk().directory })
}
const exportSession = async (id: string) => {
try {
const data = await fetchSessionExport({ sessionID: id, api: serverSDK.api })
const filename = sessionExportFilename(data.info)
if (!(await saveSessionExport(filename, data, platform))) return
showToast({
variant: "success",
icon: "circle-check",
title: language.t("toast.session.export.success.title"),
description: language.t("toast.session.export.success.description", { filename }),
})
} catch (error) {
showToast({
variant: "error",
title: language.t("toast.session.export.failed.title"),
description: error instanceof Error ? error.message : language.t("toast.session.export.failed.description"),
})
}
}
// Where the view goes once the session is gone, read before the delete hides it from the list.
const deleteTarget = (id: string) => {
const session = data.session.get(id)
@@ -460,7 +440,8 @@ export function createTimelineController(input: { session: TimelineSessionSource
}),
},
action: {
export: exportSession,
export: (id: string) => exporter.export({ server: server.key, sessionID: id }),
exporting: (id: string) => exporter.exporting({ server: server.key, sessionID: id }),
showDelete: (id: string) => dialog.show(() => <DeleteDialog sessionID={id} />),
navigateParent: () => {
const id = input.session.data.parentID()
@@ -1,13 +1,8 @@
import { expect, test } from "bun:test"
import {
createSessionDeleteState,
createSessionHeaderTitleState,
selectSessionDeleteView,
selectSessionHeaderTitleView,
transitionSessionDelete,
transitionSessionHeaderTitle,
type SessionDeleteEvent,
type SessionDeleteState,
type SessionHeaderTitleEvent,
type SessionHeaderTitleState,
} from "./header-actions-machine"
@@ -15,15 +10,10 @@ import {
const titleReplay = (events: SessionHeaderTitleEvent[], from = createSessionHeaderTitleState("ses_a")) =>
events.reduce((state: SessionHeaderTitleState, event) => transitionSessionHeaderTitle(state, event).state, from)
const deleteReplay = (events: SessionDeleteEvent[], from = createSessionDeleteState("ses_a")) =>
events.reduce((state: SessionDeleteState, event) => transitionSessionDelete(state, event).state, from)
const attempt = (state: SessionHeaderTitleState | SessionDeleteState) => ("attempt" in state ? state.attempt : -1)
const attempt = (state: SessionHeaderTitleState) => ("attempt" in state ? state.attempt : -1)
const submit = { type: "edit.submitted", sessionID: "ses_a", editable: true, currentTitle: "Old" } as const
const target = { removedIDs: ["ses_a"], nextID: "ses_b" }
test("Rename opens the editor once the closing menu hands focus back", () => {
const closing = titleReplay([
{ type: "menu.toggled", open: true, editable: true },
@@ -134,60 +124,3 @@ test("a save that fails or hangs returns to the edit with the draft", () => {
transitionSessionHeaderTitle(saving, { type: "rename.succeeded", attempt: attempt(saving) }).state.status,
).toBe("idle")
})
test("Delete claims the request at once, so a double click or Cancel waits for it", () => {
const deleting = transitionSessionDelete(createSessionDeleteState("ses_a"), { type: "confirm.requested", target })
expect(deleting.effects).toEqual([
{ type: "delete.run", attempt: 1, sessionID: "ses_a", target },
{ type: "timer.start", attempt: 1 },
])
expect(selectSessionDeleteView(deleting.state).busy).toBe(true)
for (const event of [{ type: "confirm.requested", target }, { type: "cancel.requested" }] as const) {
const next = transitionSessionDelete(deleting.state, event)
expect(next.state).toBe(deleting.state)
expect(next.effects).toEqual([])
}
})
test("a delete that fails or hangs returns to the confirmation", () => {
const deleting = deleteReplay([{ type: "confirm.requested", target }])
for (const event of [
{ type: "delete.failed", attempt: attempt(deleting), cause: new Error("no") },
{ type: "delete.timed-out", attempt: attempt(deleting) },
] as const) {
const next = transitionSessionDelete(deleting, event)
expect(next.state.status).toBe("confirming")
expect(next.effects).toContainEqual(expect.objectContaining({ type: "toast.delete-failed" }))
}
})
test("a delete closes the dialog and leaves the session, even when it lands after the dialog went", () => {
const deleting = deleteReplay([{ type: "confirm.requested", target }])
const done = transitionSessionDelete(deleting, { type: "delete.succeeded", attempt: attempt(deleting), target })
expect(done.effects).toEqual([
{ type: "timer.cancel" },
{ type: "dialog.close" },
{ type: "session.removed", sessionID: "ses_a", target },
])
const disposed = transitionSessionDelete(deleting, { type: "disposed" })
expect(
transitionSessionDelete(disposed.state, { type: "delete.succeeded", attempt: attempt(deleting), target }).effects,
).toEqual([{ type: "session.removed", sessionID: "ses_a", target }])
})
test("confirming a session that is already gone closes the dialog", () => {
const next = transitionSessionDelete(createSessionDeleteState("ses_a"), {
type: "confirm.requested",
target: undefined,
})
expect(next.state.status).toBe("closed")
expect(next.effects).toEqual([{ type: "dialog.close" }])
})
@@ -1,9 +1,6 @@
/** A rename that has not settled by then counts as failed, so the title input cannot stay disabled. */
export const SESSION_RENAME_TIMEOUT_MS = 15_000
/** A delete that has not settled by then counts as failed, so the dialog's buttons cannot stay disabled. */
export const SESSION_DELETE_TIMEOUT_MS = 15_000
/**
* The session header's title: shown, with its options menu open, edited inline, or saving the edit. `renaming`: Rename
* was chosen and the menu is closing; the editor opens once the menu hands focus back, so the menu cannot take focus
@@ -57,60 +54,12 @@ export type SessionHeaderTitleTransition = {
readonly effects: readonly SessionHeaderTitleEffect[]
}
/** The delete confirmation for one session: asking, or waiting for the server. */
export type SessionDeleteState =
| { readonly status: "confirming"; readonly sessionID: string; readonly attempt: number }
| {
readonly status: "deleting"
readonly sessionID: string
readonly attempt: number
readonly target: SessionDeleteTarget
}
| { readonly status: "closed"; readonly sessionID: string; readonly attempt: number }
| { readonly status: "disposed"; readonly sessionID: string; readonly attempt: number }
/** Read when the user confirms, before the delete hides the session from the list. */
export type SessionDeleteTarget = {
readonly parentID?: string
readonly nextID?: string
readonly removedIDs: readonly string[]
}
export type SessionDeleteEvent =
| { readonly type: "cancel.requested" }
/** `target`: undefined once the session is gone. */
| { readonly type: "confirm.requested"; readonly target: SessionDeleteTarget | undefined }
| { readonly type: "delete.succeeded"; readonly attempt: number; readonly target: SessionDeleteTarget }
| { readonly type: "delete.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "delete.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type SessionDeleteEffect =
| {
readonly type: "delete.run"
readonly attempt: number
readonly sessionID: string
readonly target: SessionDeleteTarget
}
| { readonly type: "timer.start"; readonly attempt: number }
| { readonly type: "timer.cancel" }
| { readonly type: "dialog.close" }
| { readonly type: "session.removed"; readonly sessionID: string; readonly target: SessionDeleteTarget }
| { readonly type: "toast.delete-failed"; readonly cause?: unknown }
export type SessionDeleteTransition = {
readonly state: SessionDeleteState
readonly effects: readonly SessionDeleteEffect[]
}
const NO_EFFECTS: readonly never[] = Object.freeze([])
const TIMER_CANCEL = Object.freeze({ type: "timer.cancel" } as const)
const TIMER_CANCEL: SessionHeaderTitleEffect = Object.freeze({ type: "timer.cancel" })
const FOCUS_CANCEL: SessionHeaderTitleEffect = Object.freeze({ type: "focus.cancel" })
const DIALOG_CLOSE: SessionDeleteEffect = Object.freeze({ type: "dialog.close" })
const TITLE_DISPOSED: SessionHeaderTitleState = Object.freeze({ status: "disposed" })
export function createSessionHeaderTitleState(sessionKey: string): SessionHeaderTitleState {
@@ -231,66 +180,6 @@ export function selectSessionHeaderTitleView(state: SessionHeaderTitleState) {
}
}
export function createSessionDeleteState(sessionID: string): SessionDeleteState {
return { status: "confirming", sessionID, attempt: 0 }
}
export function transitionSessionDelete(state: SessionDeleteState, event: SessionDeleteEvent): SessionDeleteTransition {
if (state.status === "closed" || state.status === "disposed") {
// The server deleted the session after the dialog went: it still leaves the session and its tabs.
if (event.type === "delete.succeeded")
return { state, effects: [{ type: "session.removed", sessionID: state.sessionID, target: event.target }] }
return { state, effects: NO_EFFECTS }
}
if (event.type === "disposed")
return {
state: { status: "disposed", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: state.status === "deleting" ? [TIMER_CANCEL] : NO_EFFECTS,
}
if (state.status === "confirming") {
// A delete that timed out can still land; the session is gone, so the dialog goes too.
if (event.type === "delete.succeeded") return deleted(state, event.target)
if (event.type === "cancel.requested" || (event.type === "confirm.requested" && !event.target))
return { state: { ...state, status: "closed", attempt: state.attempt + 1 }, effects: [DIALOG_CLOSE] }
if (event.type !== "confirm.requested" || !event.target) return { state, effects: NO_EFFECTS }
const attempt = state.attempt + 1
return {
state: { status: "deleting", sessionID: state.sessionID, attempt, target: event.target },
effects: [
{ type: "delete.run", attempt, sessionID: state.sessionID, target: event.target },
{ type: "timer.start", attempt },
],
}
}
// A second click, Enter or Cancel waits for the delete in flight.
if (event.type !== "delete.succeeded" && event.type !== "delete.failed" && event.type !== "delete.timed-out")
return { state, effects: NO_EFFECTS }
if (event.attempt !== state.attempt) return { state, effects: NO_EFFECTS }
if (event.type === "delete.succeeded") return deleted(state, event.target)
// A failed delete keeps the dialog, so the user can retry or cancel.
return {
state: { status: "confirming", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: [
TIMER_CANCEL,
{ type: "toast.delete-failed", cause: event.type === "delete.failed" ? event.cause : undefined },
],
}
}
export function selectSessionDeleteView(state: SessionDeleteState) {
return { busy: state.status !== "confirming" }
}
function rest(state: Exclude<SessionHeaderTitleState, { status: "disposed" }>, status: "idle" | "menu" | "renaming") {
return { status, sessionKey: state.sessionKey, attempt: state.attempt + 1 }
}
@@ -304,20 +193,6 @@ function edit(state: Exclude<SessionHeaderTitleState, { status: "disposed" }>, t
} satisfies SessionHeaderTitleTransition
}
function deleted(
state: Extract<SessionDeleteState, { status: "confirming" | "deleting" }>,
target: SessionDeleteTarget,
): SessionDeleteTransition {
return {
state: { status: "closed", sessionID: state.sessionID, attempt: state.attempt + 1 },
effects: [
...(state.status === "deleting" ? [TIMER_CANCEL] : []),
DIALOG_CLOSE,
{ type: "session.removed", sessionID: state.sessionID, target },
],
}
}
function cleanupTitle(
state: Exclude<SessionHeaderTitleState, { status: "disposed" }>,
): readonly SessionHeaderTitleEffect[] {
@@ -608,7 +608,7 @@ function MessageTimelineView(
}}
>
<Menu.Item onSelect={props.title.chooseRename}>{language.t("common.rename")}</Menu.Item>
<Menu.Item onSelect={() => void props.action.export(id)}>
<Menu.Item disabled={props.action.exporting(id)} onSelect={() => props.action.export(id)}>
{language.t("common.export")}…
</Menu.Item>
<Menu.Separator />
@@ -0,0 +1,124 @@
import { expect, test } from "bun:test"
import type { SessionInfo } from "@opencode/client/promise"
import { ServerConnection } from "@/runtime/server/registry"
import {
INITIAL_SESSION_UI_NAVIGATE_STATE,
transitionSessionUINavigate,
type SessionUINavigateEvent,
type SessionUINavigateTransition,
} from "./session-ui-navigate-machine"
const server = ServerConnection.Key.make("sidecar")
const parent = { server, sessionID: "ses_parent" }
/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- the machine passes the session through untouched */
const linked = { id: "ses_linked", time: { created: 1 } } as SessionInfo
function replay(events: SessionUINavigateEvent[]) {
return events.reduce<SessionUINavigateTransition[]>((steps, event) => {
steps.push(transitionSessionUINavigate(steps.at(-1)?.state ?? INITIAL_SESSION_UI_NAVIGATE_STATE, event))
return steps
}, [])
}
test("clicking subagent A, then B, lands on B whenever A's sync settles", () => {
const clicks: SessionUINavigateEvent[] = [
{ type: "child.requested", origin: parent, targetSessionID: "ses_a" },
{ type: "child.requested", origin: parent, targetSessionID: "ses_b" },
]
const [a, b, syncedB, lateA] = replay([
...clicks,
{ type: "child.synced", attempt: 2 },
{ type: "child.synced", attempt: 1 },
])
const [, resolvingB, earlyA, thenB] = replay([
...clicks,
{ type: "child.synced", attempt: 1 },
{ type: "child.synced", attempt: 2 },
])
// Nothing touches the tab or the route until the sync settles.
expect(a?.effects).toEqual([{ type: "child.sync", attempt: 1, targetSessionID: "ses_a" }])
expect(b?.effects).toEqual([{ type: "child.sync", attempt: 2, targetSessionID: "ses_b" }])
expect(syncedB?.effects).toEqual([{ type: "child.navigate", origin: parent, targetSessionID: "ses_b" }])
expect(lateA?.state).toBe(syncedB!.state)
expect(lateA?.effects).toEqual([])
expect(earlyA?.state).toBe(resolvingB!.state)
expect(earlyA?.effects).toEqual([])
expect(thenB?.effects).toEqual([{ type: "child.navigate", origin: parent, targetSessionID: "ses_b" }])
})
test.each<[string, SessionUINavigateEvent]>([
["switching tabs", { type: "origin.changed", origin: { server, sessionID: "ses_other" } }],
["leaving the session screen", { type: "disposed" }],
])("%s while a child syncs or a link resolves drops the late result", (_name, leave) => {
const [, left, lateChild] = replay([
{ type: "child.requested", origin: parent, targetSessionID: "ses_a" },
leave,
{ type: "child.synced", attempt: 1 },
])
const [, abort, lateLink] = replay([
{ type: "referenced.requested", origin: parent, targetSessionID: linked.id },
leave,
{ type: "referenced.resolved", attempt: 1, session: linked },
])
expect(left?.effects).toEqual([])
expect(lateChild?.state).toBe(left!.state)
expect(lateChild?.effects).toEqual([])
expect(abort?.effects).toEqual([{ type: "referenced.abort", attempt: 1 }])
expect(lateLink?.state).toBe(abort!.state)
expect(lateLink?.effects).toEqual([])
})
test("a repeat click joins the request in flight, and the session on screen needs none", () => {
const [first, repeat, linkFirst, linkRepeat] = replay([
{ type: "child.requested", origin: parent, targetSessionID: "ses_a" },
{ type: "child.requested", origin: { ...parent }, targetSessionID: "ses_a" },
{ type: "referenced.requested", origin: parent, targetSessionID: linked.id },
{ type: "referenced.requested", origin: parent, targetSessionID: linked.id },
])
const [self] = replay([{ type: "child.requested", origin: parent, targetSessionID: parent.sessionID }])
expect(repeat?.state).toBe(first!.state)
expect(repeat?.effects).toEqual([])
// A link replaces the child sync; the late sync no longer navigates.
expect(linkFirst?.effects).toEqual([{ type: "referenced.lookup", attempt: 2, targetSessionID: linked.id }])
expect(linkRepeat?.state).toBe(linkFirst!.state)
expect(transitionSessionUINavigate(linkFirst!.state, { type: "child.synced", attempt: 1 }).effects).toEqual([])
expect(self?.state).toBe(INITIAL_SESSION_UI_NAVIGATE_STATE)
})
test("a newer link aborts the older lookup", () => {
const [, second] = replay([
{ type: "referenced.requested", origin: parent, targetSessionID: "ses_old" },
{ type: "referenced.requested", origin: parent, targetSessionID: linked.id },
])
expect(second?.effects).toEqual([
{ type: "referenced.abort", attempt: 1 },
{ type: "referenced.lookup", attempt: 2, targetSessionID: linked.id },
])
})
test("a link opens a found session, says not found for a missing one, and reports a failed request", () => {
const requested: SessionUINavigateEvent = { type: "referenced.requested", origin: parent, targetSessionID: linked.id }
const [, opened] = replay([requested, { type: "referenced.resolved", attempt: 1, session: linked }])
const [, missing] = replay([requested, { type: "referenced.missing", attempt: 1 }])
const [, failed] = replay([requested, { type: "referenced.failed", attempt: 1, cause: "500" }])
expect(opened?.effects).toEqual([{ type: "referenced.open", server, session: linked }])
expect(missing?.effects).toEqual([{ type: "toast.not-found" }])
expect(failed?.effects).toEqual([{ type: "toast.request-failed", cause: "500" }])
expect([opened, missing, failed].map((step) => step?.state)).toEqual([
{ status: "idle", attempt: 1 },
{ status: "idle", attempt: 1 },
{ status: "idle", attempt: 1 },
])
})
@@ -0,0 +1,127 @@
import type { SessionInfo } from "@opencode/client/promise"
import type { ServerConnection } from "@/runtime/server/registry"
/** The screen that asked to open a session: a result lands only while the user is still there. */
export type SessionNavigateOrigin = {
readonly server: ServerConnection.Key
readonly sessionID: string | undefined
}
/**
* Opening a session from the timeline: a subagent card syncs the child before it navigates, so the parent stays on
* screen meanwhile; a session ID in Markdown is looked up on this server before it opens a tab. One at a time: the
* latest click wins, and leaving the screen drops it.
*/
export type SessionUINavigateState =
| { readonly status: "idle"; readonly attempt: number }
| {
readonly status: "resolving"
readonly kind: "child" | "referenced"
readonly attempt: number
readonly origin: SessionNavigateOrigin
readonly targetSessionID: string
}
| { readonly status: "disposed" }
export type SessionUINavigateEvent =
| { readonly type: "child.requested"; readonly origin: SessionNavigateOrigin; readonly targetSessionID: string }
/** The sync settled, either way: the session route shows the child, or its error, from there. */
| { readonly type: "child.synced"; readonly attempt: number }
| { readonly type: "referenced.requested"; readonly origin: SessionNavigateOrigin; readonly targetSessionID: string }
| { readonly type: "referenced.resolved"; readonly attempt: number; readonly session: SessionInfo }
| { readonly type: "referenced.missing"; readonly attempt: number }
| { readonly type: "referenced.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "origin.changed"; readonly origin: SessionNavigateOrigin }
| { readonly type: "disposed" }
export type SessionUINavigateEffect =
| { readonly type: "child.sync"; readonly attempt: number; readonly targetSessionID: string }
| { readonly type: "child.navigate"; readonly origin: SessionNavigateOrigin; readonly targetSessionID: string }
| { readonly type: "referenced.lookup"; readonly attempt: number; readonly targetSessionID: string }
| { readonly type: "referenced.abort"; readonly attempt: number }
| { readonly type: "referenced.open"; readonly server: ServerConnection.Key; readonly session: SessionInfo }
| { readonly type: "toast.not-found" }
| { readonly type: "toast.request-failed"; readonly cause: unknown }
export type SessionUINavigateTransition = {
readonly state: SessionUINavigateState
readonly effects: readonly SessionUINavigateEffect[]
}
const NO_EFFECTS: readonly never[] = Object.freeze([])
export const INITIAL_SESSION_UI_NAVIGATE_STATE: SessionUINavigateState = Object.freeze({ status: "idle", attempt: 0 })
const DISPOSED: SessionUINavigateState = Object.freeze({ status: "disposed" })
export function transitionSessionUINavigate(
state: SessionUINavigateState,
event: SessionUINavigateEvent,
): SessionUINavigateTransition {
if (state.status === "disposed") return { state, effects: NO_EFFECTS }
if (event.type === "disposed") return { state: DISPOSED, effects: abort(state) }
if (event.type === "origin.changed") {
if (state.status === "idle" || sameOrigin(state.origin, event.origin)) return { state, effects: NO_EFFECTS }
return { state: { status: "idle", attempt: state.attempt }, effects: abort(state) }
}
if (event.type === "child.requested" || event.type === "referenced.requested") {
const kind = event.type === "child.requested" ? "child" : "referenced"
// The session on screen needs no opening, and a repeat click joins the one in flight.
if (kind === "child" && event.origin.sessionID === event.targetSessionID) return { state, effects: NO_EFFECTS }
if (
state.status === "resolving" &&
state.kind === kind &&
state.targetSessionID === event.targetSessionID &&
sameOrigin(state.origin, event.origin)
)
return { state, effects: NO_EFFECTS }
const attempt = state.attempt + 1
return {
state: { status: "resolving", kind, attempt, origin: event.origin, targetSessionID: event.targetSessionID },
effects: [
...abort(state),
kind === "child"
? { type: "child.sync", attempt, targetSessionID: event.targetSessionID }
: { type: "referenced.lookup", attempt, targetSessionID: event.targetSessionID },
],
}
}
if (state.status !== "resolving" || state.attempt !== event.attempt) return { state, effects: NO_EFFECTS }
const idle: SessionUINavigateState = { status: "idle", attempt: state.attempt }
if (event.type === "child.synced")
return state.kind === "child"
? {
state: idle,
effects: [{ type: "child.navigate", origin: state.origin, targetSessionID: state.targetSessionID }],
}
: { state, effects: NO_EFFECTS }
if (state.kind !== "referenced") return { state, effects: NO_EFFECTS }
if (event.type === "referenced.resolved")
return { state: idle, effects: [{ type: "referenced.open", server: state.origin.server, session: event.session }] }
if (event.type === "referenced.missing") return { state: idle, effects: [{ type: "toast.not-found" }] }
return { state: idle, effects: [{ type: "toast.request-failed", cause: event.cause }] }
}
function sameOrigin(a: SessionNavigateOrigin, b: SessionNavigateOrigin) {
return a.server === b.server && a.sessionID === b.sessionID
}
function abort(state: SessionUINavigateState): readonly SessionUINavigateEffect[] {
return state.status === "resolving" && state.kind === "referenced"
? [{ type: "referenced.abort", attempt: state.attempt }]
: NO_EFFECTS
}
@@ -2,19 +2,28 @@ import { DataProvider, type TurnDiffInput } from "@opencode/session-ui/context"
import { MarkdownProvider, type ReadMarkdownImage } from "@opencode/session-ui/context/markdown"
import { useNavigate, useParams } from "@solidjs/router"
import { useQuery } from "@tanstack/solid-query"
import { createMemo, onCleanup, untrack, type ParentProps } from "solid-js"
import { createEffect, createMemo, createSignal, on, onCleanup, untrack, type ParentProps } from "solid-js"
import { useProviders } from "@/providers/catalog/providers"
import { LocalProvider } from "@/providers/models/selection"
import type { ServerConnection } from "@/runtime/server/registry"
import { sessionHref } from "@/shell/routes/session"
import { useData } from "@/runtime/server/current"
import { useServerSDK } from "@/runtime/server/client"
import { formatServerError, isSessionNotFoundError } from "@/runtime/server/errors"
import { findSessionTab, useTabs } from "@/shell/tabs/tabs"
import { readLocalImage } from "@/runtime/server/image"
import { useLanguage } from "@/runtime/i18n/language"
import { showToast } from "@/shell/notifications/toast"
import { SessionExportProvider } from "@/session/commands/export-session"
import { createTurnDiffCache } from "@/session/timeline/turn-diffs"
import { useSettings } from "@/settings/model"
import {
INITIAL_SESSION_UI_NAVIGATE_STATE,
transitionSessionUINavigate,
type SessionNavigateOrigin,
type SessionUINavigateEffect,
type SessionUINavigateEvent,
} from "./session-ui-navigate-machine"
export function SessionUIProvider(
props: ParentProps<{
@@ -39,34 +48,95 @@ export function SessionUIProvider(
const href = (sessionID: string) => sessionHref(props.server, sessionID)
const navigateToSession = async (sessionID: string) => {
const tab = tabs.store.find(
(item) =>
item.type === "session" &&
item.server === props.server &&
(item.sessionId === params.id || item.routeSessionId === params.id),
)
const origin = (): SessionNavigateOrigin => ({ server: props.server, sessionID: params.id })
const [navigation, setNavigation] = createSignal(INITIAL_SESSION_UI_NAVIGATE_STATE)
const lookups = new Map<number, AbortController>()
if (tab?.type === "session") tabs.rememberSessionRoute(tab, sessionID, params.id)
await data.session.sync(sessionID).catch(() => undefined)
navigate(href(sessionID))
const dispatchNavigation = (event: SessionUINavigateEvent) => {
const previous = untrack(navigation)
const next = transitionSessionUINavigate(previous, event)
if (next.state !== previous) setNavigation(next.state)
next.effects.forEach((effect) =>
Promise.try(() => runNavigation(effect)).catch((cause: unknown) => console.error("[session.navigate]", cause)),
)
}
const openReferencedSession = async (sessionID: string) => {
// The transcript may mention a session from another server (or one that was deleted).
// Resolve it on this server before touching tabs or the current route.
const session = await serverSDK.api.session.get({ sessionID }).catch(() => undefined)
if (!session || session.time.archived) {
showToast({ title: language.t("session.error.notFound") })
function runNavigation(effect: SessionUINavigateEffect) {
if (effect.type === "child.sync") {
const settled = () => dispatchNavigation({ type: "child.synced", attempt: effect.attempt })
void Promise.try(() => data.session.sync(effect.targetSessionID)).then(settled, settled)
return
}
data.session.remember(session)
tabs.select(tabs.addSessionTab({ server: props.server, sessionId: session.id }))
if (effect.type === "child.navigate") {
// The tab remembers the child only when the screen goes there, so it never disagrees with the route.
const tab = effect.origin.sessionID ? tabs.sessionTab(effect.origin.server, effect.origin.sessionID) : undefined
if (tab?.type === "session") tabs.rememberSessionRoute(tab, effect.targetSessionID, effect.origin.sessionID)
navigate(sessionHref(effect.origin.server, effect.targetSessionID))
return
}
if (effect.type === "referenced.lookup") {
// The transcript may mention a session from another server (or one that was deleted).
// Resolve it on this server before touching tabs or the current route.
const controller = new AbortController()
lookups.set(effect.attempt, controller)
void Promise.try(() =>
serverSDK.api.session.get({ sessionID: effect.targetSessionID }, { signal: controller.signal }),
)
.finally(() => lookups.delete(effect.attempt))
.then(
(session) =>
dispatchNavigation(
session.time.archived
? { type: "referenced.missing", attempt: effect.attempt }
: { type: "referenced.resolved", attempt: effect.attempt, session },
),
(cause: unknown) =>
dispatchNavigation(
isSessionNotFoundError(cause, effect.targetSessionID)
? { type: "referenced.missing", attempt: effect.attempt }
: { type: "referenced.failed", attempt: effect.attempt, cause },
),
)
return
}
if (effect.type === "referenced.abort") {
lookups.get(effect.attempt)?.abort()
lookups.delete(effect.attempt)
return
}
if (effect.type === "referenced.open") {
data.session.remember(effect.session)
tabs.select(tabs.addSessionTab({ server: effect.server, sessionId: effect.session.id }))
return
}
if (effect.type === "toast.not-found") return showToast({ title: language.t("session.error.notFound") })
showToast({ title: formatServerError(effect.cause, language.t, language.t("common.requestFailed")) })
}
createEffect(
on(origin, (current) => dispatchNavigation({ type: "origin.changed", origin: current }), { defer: true }),
)
onCleanup(() => dispatchNavigation({ type: "disposed" }))
const navigateToSession = (sessionID: string) =>
dispatchNavigation({ type: "child.requested", origin: untrack(origin), targetSessionID: sessionID })
const openReferencedSession = (sessionID: string) =>
dispatchNavigation({ type: "referenced.requested", origin: untrack(origin), targetSessionID: sessionID })
const sessionTitle = (id: string) => {
const session = data.session.get(id)
@@ -148,7 +218,7 @@ export function SessionUIProvider(
backgroundCompaction={backgroundCompaction()}
>
<MarkdownProvider readImage={readImage()} openSession={openReferencedSession} sessionTitle={sessionTitle}>
{props.children}
<SessionExportProvider>{props.children}</SessionExportProvider>
</MarkdownProvider>
</DataProvider>
</LocalProvider>
@@ -441,6 +441,7 @@ function ProjectRow(props: {
project={props.project}
unread={props.actions.hasUnread(props.server, props.project)}
canImportSession={props.actions.canImportSession}
importingSession={props.actions.importingSession()}
canRevealProject={props.actions.canReveal}
onOpenProjectNewSession={props.actions.openNewSession}
onImportSession={props.actions.importSession}