fix(sessions): recover sessions whose directory disappeared (#3365)
* fix(sessions): keep a shared chat directory until its last session is deleted Deleting a root chat session removed its managed scratch directory even when forks, side threads, or subagents still lived in it; OpenCode then failed every prompt in those sessions with FileSystem.realPath NotFound. The directory is now removed only once no other known session resolves to it. The deleted subtree does not count, because the server cascade- deletes it, and an unloaded global cache keeps the directory instead of guessing. Closes #3312. * fix(sessions): relocate a session whose worktree directory disappeared A worktree removed outside OpenChamber, by the agent or by hand, left its sessions pointed at a path that no longer exists: every terminal create and restart failed with "Invalid working directory" and the tab stayed stuck, while Git, Files, and prompts kept targeting the dead path. The terminal server now names that one rejection (TERMINAL_CWD_MISSING) instead of substituting a directory of its own. The shared UI reuses the archived-restore fallback for live sessions: a server-confirmed missing directory moves the session and its stranded subtree to the project's primary directory through the control-plane move, clears the worktree hint, re-selects the session, and tells the user where it went. It runs from a terminal failure and on activation of any session whose directory is neither a project root nor a managed chat directory; available, unknown, and failed probes leave everything untouched. Closes #3338. * fix(scripts): make oc-dev load again after the changelog cleanup The changelog cleanup referenced fs.existsSync in a module that imports existsSync by name and never binds fs, so every oc-dev invocation failed with "fs is not defined" before reaching its action. * fix(sessions): probe directory availability on disk, not through OpenCode path resolution OpenCode's /path never checks that a directory exists: it echoes the requested path and resolves its project through Git discovery that swallows errors, so a deleted worktree came back as a valid location and every missing-directory fallback (draft recovery, archived restore, session relocation) stayed inert on a real server. The probe now asks OpenChamber's own /api/fs/list, which stats the path and reports not-found and not-directory explicitly; anything else stays unknown. * fix(sidebar): keep a worktree whose directory is gone visible as missing git keeps a worktree registered after its directory is deleted outside git and marks it prunable; the list parser ignored that line, so a deleted worktree looked alive, and nothing in the app asked for a new listing anyway. The server now reports prunable, the UI keeps such a worktree in the topology with worktreeStatus missing and a warning icon on its sidebar group, and relocating a session out of a confirmed- missing directory raises an in-app topology signal the sidebar rediscovers on. Dropping the worktree instead would hide every session that lived there, and a hidden session can never be opened or relocated. No idle polling is added. * fix(sessions): never relocate a session to the filesystem root OpenCode files a directory outside any Git repository under its global project, whose worktree is the filesystem root. A managed chat whose directory vanished would otherwise be moved to /. The relocation now refuses a root destination, and the activation probe recognizes chat directories through the home-based check as well, so it does not depend on the chats root having been resolved yet. * test(sessions): mirror the relocation action in the issue-2039 session-actions mock session-ui-store now imports relocateSessionFromMissingDirectory, and the mocked module in this test listed every other action but not that one, so the file failed on import.
This commit is contained in:
@@ -382,11 +382,36 @@ reports failure instead of committing. The deletion already accepted by the
|
||||
server stays deleted there; its persisted state is left as harmless stale
|
||||
metadata and the next authoritative load reconciles it.
|
||||
|
||||
### Missing directory relocation (active sessions)
|
||||
|
||||
The same directory can disappear under an active session: a worktree removed
|
||||
by the agent or by hand leaves the session, its tabs, and its prompts pointed
|
||||
at a path that no longer exists, and the terminal server answers every create
|
||||
and restart with `Invalid working directory`. `relocateSessionFromMissingDirectory`
|
||||
(`session-actions.ts`) applies the restore fallback's gate to a live session:
|
||||
an exact `missing` probe, the destination resolved from the server `projectID`,
|
||||
and `available`, `unknown`, probe failures, project-root sessions, and sessions
|
||||
without a project left untouched. Every session of the root's subtree still
|
||||
stranded in that directory moves with it, root first, so the session the user
|
||||
is looking at is usable even when a descendant move fails; the result names
|
||||
the sessions already moved. Moves carry no changes because the source is gone.
|
||||
|
||||
`session-ui-store.recoverMissingSessionDirectory` owns the user-visible side:
|
||||
one shared attempt per runtime and session, the worktree hint cleared for each
|
||||
moved session (it is the first thing every directory lookup reads), the current
|
||||
session re-selected through `setCurrentSession` so the active directory,
|
||||
project, and OpenCode client follow it, and one toast naming the destination.
|
||||
It runs from two places: a terminal create/restart rejected with the server's
|
||||
`TERMINAL_CWD_MISSING` code, and session activation for any session whose
|
||||
directory is neither a registered project root nor a managed chat directory
|
||||
(the same probe a reopened draft performs on its inherited directory). VS Code
|
||||
registers no worktrees, so activation never probes there.
|
||||
|
||||
## The golden rule
|
||||
|
||||
### Managed chat directories
|
||||
|
||||
Ordinary user-created drafts default to the OpenChamber-managed Chat target. The first submit creates one isolated directory under the server-resolved managed chats root (`OPENCHAMBER_CHATS_DIR`, default `~/.config/openchamber/chats`) as `YYYY-MM-DD/session-<id>` before creating the OpenCode session. That root acts as a system project owner for sidebar membership and Notes, Todo, Plans, pinned knowledge, and project memory, but it is never persisted or rendered as a user project and exposes no Git/worktree controls. Project and worktree actions remain explicit targets. Archiving retains a chat directory so restore remains lossless. Confirmed deletion accepts only descendants of the configured root or the actual server home's legacy chats root. It rejects both shared roots themselves, dot segments, lookalike paths elsewhere, and a runtime switch during root resolution. It never removes project directories.
|
||||
Ordinary user-created drafts default to the OpenChamber-managed Chat target. The first submit creates one isolated directory under the server-resolved managed chats root (`OPENCHAMBER_CHATS_DIR`, default `~/.config/openchamber/chats`) as `YYYY-MM-DD/session-<id>` before creating the OpenCode session. That root acts as a system project owner for sidebar membership and Notes, Todo, Plans, pinned knowledge, and project memory, but it is never persisted or rendered as a user project and exposes no Git/worktree controls. Project and worktree actions remain explicit targets. Archiving retains a chat directory so restore remains lossless. Confirmed deletion accepts only descendants of the configured root or the actual server home's legacy chats root. It rejects both shared roots themselves, dot segments, lookalike paths elsewhere, and a runtime switch during root resolution. It also removes a directory only once no other known session still resolves to it: forks, side threads, and subagents share the directory of the chat that created them, and OpenCode fails every prompt in a session whose directory is gone. The deleted session's own subtree does not count, because the server cascade-deletes it, and an unloaded global cache keeps the directory because it cannot prove it is unused. It never removes project directories.
|
||||
|
||||
Typing the first character in a managed Chat draft starts one deduplicated directory preparation for that draft. Materialization consumes the prepared directory before `createSession`, removing filesystem creation from the usual submit path. Closing the draft, changing it to a project target, or completing preparation after the runtime/draft changed deletes the unclaimed directory. A create failure also deletes the consumed directory.
|
||||
|
||||
|
||||
@@ -309,6 +309,7 @@ mock.module("../session-actions", () => ({
|
||||
unrevertSession: mock(async () => undefined),
|
||||
forkFromMessage: mock(async () => undefined),
|
||||
fetchMessagesForSession: mock(async () => undefined),
|
||||
relocateSessionFromMissingDirectory: mock(async () => ({ status: "unchanged" })),
|
||||
getSessionLastAssistantModel: () => null,
|
||||
patchSessionMetadata: mock(async () => undefined),
|
||||
abortCurrentOperation: mock(async () => undefined),
|
||||
|
||||
@@ -21,6 +21,10 @@ let sessionDeleteError: unknown | null = null
|
||||
let beforeSessionUpdateResolve: ((sessionId: string) => void) | null = null
|
||||
let beforeSessionDeleteResolve: ((sessionId: string) => void) | null = null
|
||||
let beforeControlPlaneMoveResolve: ((sessionId: string) => void) | null = null
|
||||
let beforeDirectoryAvailabilityResolve: (() => void) | null = null
|
||||
const controlPlaneMoveErrorsById = new Map<string, Error>()
|
||||
let globalHasLoaded = true
|
||||
const deletedChatDirectories: string[] = []
|
||||
const globalUpsertedSessions: unknown[] = []
|
||||
const globalUpsertedSessionBatches: Session[][] = []
|
||||
const globalRemovedSessionIds: string[] = []
|
||||
@@ -76,6 +80,8 @@ const mockSdk = {
|
||||
moveSession: mock((params: Record<string, unknown>) => {
|
||||
replyCalls.push({ method: "controlPlane.moveSession", params })
|
||||
beforeControlPlaneMoveResolve?.(String(params.sessionID))
|
||||
const error = controlPlaneMoveErrorsById.get(String(params.sessionID))
|
||||
if (error) return Promise.resolve({ error, response: { status: 500 } })
|
||||
return Promise.resolve({})
|
||||
}),
|
||||
},
|
||||
@@ -153,6 +159,9 @@ const mockSdk = {
|
||||
}
|
||||
|
||||
// Mock opencodeClient singleton
|
||||
// SAFETY: the actions under test touch only the SDK surface mocked above.
|
||||
const actionSdk = mockSdk as unknown as OpencodeClient
|
||||
|
||||
mock.module("@/lib/opencode/client", () => ({
|
||||
opencodeClient: {
|
||||
getScopedSdkClient: (directory: string) => {
|
||||
@@ -160,7 +169,10 @@ mock.module("@/lib/opencode/client", () => ({
|
||||
return mockScopedClient
|
||||
},
|
||||
getDirectory: () => "/test/project",
|
||||
getDirectoryAvailability: mock(async (directory: string) => directoryAvailability.get(directory) ?? "available"),
|
||||
getDirectoryAvailability: mock(async (directory: string) => {
|
||||
beforeDirectoryAvailabilityResolve?.()
|
||||
return directoryAvailability.get(directory) ?? "available"
|
||||
}),
|
||||
getFilesystemHome: mock(async () => "/home/test"),
|
||||
getSdkClient: () => mockSdk,
|
||||
getSessionMessages: mock((sessionId: string, _limit?: number, directory?: string | null) => {
|
||||
@@ -285,6 +297,7 @@ mock.module("@/stores/useGlobalSessionsStore", () => ({
|
||||
getState: () => ({
|
||||
activeSessions: globalActiveSessions,
|
||||
archivedSessions: globalArchivedSessions,
|
||||
hasLoaded: globalHasLoaded,
|
||||
upsertSession: (session: unknown) => {
|
||||
globalUpsertedSessions.push(session)
|
||||
},
|
||||
@@ -383,7 +396,9 @@ mock.module("./send-failure-classification", () => ({
|
||||
}))
|
||||
|
||||
mock.module("@/lib/chatDirectories", () => ({
|
||||
deleteChatDirectory: async () => {},
|
||||
deleteChatDirectory: async (directory: string) => {
|
||||
deletedChatDirectories.push(directory)
|
||||
},
|
||||
}))
|
||||
|
||||
mock.module("./session-deletion-cleanup", () => ({
|
||||
@@ -549,6 +564,10 @@ describe("confirmed session removal", () => {
|
||||
archiveBatchRequests.length = 0
|
||||
archiveBatchResponse = { status: 404, body: { error: 'not found' } }
|
||||
beforeControlPlaneMoveResolve = null
|
||||
beforeDirectoryAvailabilityResolve = null
|
||||
controlPlaneMoveErrorsById.clear()
|
||||
globalHasLoaded = true
|
||||
deletedChatDirectories.length = 0
|
||||
})
|
||||
|
||||
test("does not remove live or persisted state when delete fails", async () => {
|
||||
@@ -683,6 +702,58 @@ describe("confirmed session removal", () => {
|
||||
.toEqual(["session-a", "session-b"])
|
||||
})
|
||||
|
||||
const chatDirectory = "/home/user/.config/openchamber/chats/2026-09-05/session-abc"
|
||||
const chatSession = (id: string, parentID?: string): Session => ({
|
||||
id,
|
||||
slug: id,
|
||||
projectID: "project-chats",
|
||||
directory: chatDirectory,
|
||||
title: id,
|
||||
version: "1",
|
||||
time: { created: 1, updated: 1 },
|
||||
parentID,
|
||||
})
|
||||
|
||||
test("keeps a shared chat directory while another root session still uses it", async () => {
|
||||
const root = chatSession("chat-root")
|
||||
const fork = chatSession("chat-fork")
|
||||
globalActiveSessions = [root, fork]
|
||||
const source = createStore({}, { session: [root, fork] })
|
||||
const { deleteSession, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, createChildStores([[chatDirectory, source]]), () => chatDirectory)
|
||||
|
||||
expect(await deleteSession("chat-root")).toBe(true)
|
||||
expect(deletedChatDirectories).toEqual([])
|
||||
|
||||
globalActiveSessions = [fork]
|
||||
expect(await deleteSession("chat-fork")).toBe(true)
|
||||
expect(deletedChatDirectories).toEqual([chatDirectory])
|
||||
})
|
||||
|
||||
test("removes the chat directory with its last root even though the root's own subagents share it", async () => {
|
||||
const root = chatSession("chat-root")
|
||||
const subagent = chatSession("chat-subagent", "chat-root")
|
||||
globalActiveSessions = [root, subagent]
|
||||
const source = createStore({}, { session: [root, subagent] })
|
||||
const { deleteSession, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, createChildStores([[chatDirectory, source]]), () => chatDirectory)
|
||||
|
||||
expect(await deleteSession("chat-root")).toBe(true)
|
||||
expect(deletedChatDirectories).toEqual([chatDirectory])
|
||||
})
|
||||
|
||||
test("keeps the chat directory when the global cache cannot prove it is unused", async () => {
|
||||
const root = chatSession("chat-root")
|
||||
globalActiveSessions = [root]
|
||||
globalHasLoaded = false
|
||||
const source = createStore({}, { session: [root] })
|
||||
const { deleteSession, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, createChildStores([[chatDirectory, source]]), () => chatDirectory)
|
||||
|
||||
expect(await deleteSession("chat-root")).toBe(true)
|
||||
expect(deletedChatDirectories).toEqual([])
|
||||
})
|
||||
|
||||
test("does not archive locally until the server returns the archived session", async () => {
|
||||
const source = createStore({}, {
|
||||
session: [{ id: "session-a", directory: "/test/project", time: { created: 1 } } as Session],
|
||||
@@ -959,6 +1030,10 @@ describe("session restore (unarchive)", () => {
|
||||
sessionUpdateResult = {}
|
||||
beforeSessionUpdateResolve = null
|
||||
beforeControlPlaneMoveResolve = null
|
||||
beforeDirectoryAvailabilityResolve = null
|
||||
controlPlaneMoveErrorsById.clear()
|
||||
globalHasLoaded = true
|
||||
deletedChatDirectories.length = 0
|
||||
})
|
||||
|
||||
test("does not restore locally until the server returns the restored session", async () => {
|
||||
@@ -2944,3 +3019,148 @@ describe("dismissOpenPermissionsForSession", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("relocateSessionFromMissingDirectory", () => {
|
||||
const missingWorktree = "/projects/main/.worktrees/gone"
|
||||
const projectDirectory = "/projects/main"
|
||||
const worktreeSession = (id: string, parentID: string | null, directory = missingWorktree, archived = 0): Session & { project: { worktree: string } } => ({
|
||||
id,
|
||||
slug: id,
|
||||
projectID: "project-main",
|
||||
directory,
|
||||
title: id,
|
||||
version: "1",
|
||||
project: { worktree: projectDirectory },
|
||||
time: { created: 1, updated: 1, archived },
|
||||
parentID: parentID ?? undefined,
|
||||
})
|
||||
const mainProject: Project = { id: "project-main", worktree: projectDirectory, time: { created: 1, updated: 1 }, sandboxes: [] }
|
||||
const stores = () => createChildStores([[missingWorktree, createStore({})], [projectDirectory, createStore({})]])
|
||||
const movesOf = () => replyCalls
|
||||
.filter((call) => call.method === "controlPlane.moveSession")
|
||||
.map((call) => ({ sessionID: call.params.sessionID, destination: call.params.destination, moveChanges: call.params.moveChanges }))
|
||||
|
||||
beforeEach(() => {
|
||||
replyCalls.length = 0
|
||||
registeredSessionDirectories.length = 0
|
||||
movedSessionDirectories.length = 0
|
||||
globalUpsertedSessions.length = 0
|
||||
globalActiveSessions = []
|
||||
globalArchivedSessions.length = 0
|
||||
openCodeProjects.length = 0
|
||||
directoryAvailability.clear()
|
||||
controlPlaneMoveErrorsById.clear()
|
||||
beforeDirectoryAvailabilityResolve = null
|
||||
runtimeKey = "default-runtime"
|
||||
})
|
||||
|
||||
test("moves the whole stranded subtree, root first, to the project directory without carrying changes", async () => {
|
||||
const root = worktreeSession("root", null)
|
||||
const child = worktreeSession("child", "root")
|
||||
const archivedChild = worktreeSession("archived-child", "root", missingWorktree, 42)
|
||||
const elsewhere = worktreeSession("elsewhere", "root", projectDirectory)
|
||||
globalActiveSessions = [root, child, elsewhere]
|
||||
globalArchivedSessions.push(archivedChild)
|
||||
openCodeProjects.push(mainProject)
|
||||
directoryAvailability.set(missingWorktree, "missing")
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => missingWorktree)
|
||||
|
||||
const result = await relocateSessionFromMissingDirectory("root")
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "moved",
|
||||
sourceDirectory: missingWorktree,
|
||||
destinationDirectory: projectDirectory,
|
||||
movedSessionIds: ["root", "child", "archived-child"],
|
||||
})
|
||||
expect(movesOf()).toEqual([
|
||||
{ sessionID: "root", destination: { directory: projectDirectory }, moveChanges: false },
|
||||
{ sessionID: "child", destination: { directory: projectDirectory }, moveChanges: false },
|
||||
{ sessionID: "archived-child", destination: { directory: projectDirectory }, moveChanges: false },
|
||||
])
|
||||
expect(movedSessionDirectories).toEqual([
|
||||
{ sessionID: "root", directory: projectDirectory },
|
||||
{ sessionID: "child", directory: projectDirectory },
|
||||
{ sessionID: "archived-child", directory: projectDirectory },
|
||||
])
|
||||
})
|
||||
|
||||
for (const availability of ["available", "unknown"] as const) {
|
||||
test(`leaves the session alone when its directory is ${availability}`, async () => {
|
||||
globalActiveSessions = [worktreeSession("root", null)]
|
||||
openCodeProjects.push(mainProject)
|
||||
directoryAvailability.set(missingWorktree, availability)
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => missingWorktree)
|
||||
|
||||
expect(await relocateSessionFromMissingDirectory("root")).toEqual({ status: "unchanged" })
|
||||
expect(movesOf()).toEqual([])
|
||||
})
|
||||
}
|
||||
|
||||
test("leaves a session that already lives in its project directory alone", async () => {
|
||||
globalActiveSessions = [worktreeSession("root", null, projectDirectory)]
|
||||
openCodeProjects.push(mainProject)
|
||||
directoryAvailability.set(projectDirectory, "missing")
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => projectDirectory)
|
||||
|
||||
expect(await relocateSessionFromMissingDirectory("root")).toEqual({ status: "unchanged" })
|
||||
expect(movesOf()).toEqual([])
|
||||
})
|
||||
|
||||
test("never relocates to the filesystem root OpenCode reports for its global project", async () => {
|
||||
const chatDirectory = "/Users/tester/.config/openchamber/chats/2026-09-05/session-gone"
|
||||
const chat = { ...worktreeSession("chat", null, chatDirectory), projectID: "global", project: { worktree: "/" } }
|
||||
globalActiveSessions = [chat]
|
||||
openCodeProjects.push({ id: "global", worktree: "/", time: { created: 1, updated: 1 }, sandboxes: [] })
|
||||
directoryAvailability.set(chatDirectory, "missing")
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => chatDirectory)
|
||||
|
||||
expect(await relocateSessionFromMissingDirectory("chat")).toEqual({ status: "unchanged" })
|
||||
expect(movesOf()).toEqual([])
|
||||
})
|
||||
|
||||
test("leaves the session alone when OpenCode knows no project for it", async () => {
|
||||
globalActiveSessions = [worktreeSession("root", null)]
|
||||
directoryAvailability.set(missingWorktree, "missing")
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => missingWorktree)
|
||||
|
||||
expect(await relocateSessionFromMissingDirectory("root")).toEqual({ status: "unchanged" })
|
||||
expect(movesOf()).toEqual([])
|
||||
})
|
||||
|
||||
test("reports the sessions already moved when a descendant move fails", async () => {
|
||||
globalActiveSessions = [worktreeSession("root", null), worktreeSession("child", "root")]
|
||||
openCodeProjects.push(mainProject)
|
||||
directoryAvailability.set(missingWorktree, "missing")
|
||||
controlPlaneMoveErrorsById.set("child", new Error("destination busy"))
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => missingWorktree)
|
||||
|
||||
const result = await relocateSessionFromMissingDirectory("root")
|
||||
|
||||
expect(result.status).toBe("failed")
|
||||
expect(result.status === "failed" ? result.movedSessionIds : null).toEqual(["root"])
|
||||
expect(movedSessionDirectories).toEqual([{ sessionID: "root", directory: projectDirectory }])
|
||||
})
|
||||
|
||||
test("publishes nothing when the runtime changes while the directory is being probed", async () => {
|
||||
globalActiveSessions = [worktreeSession("root", null)]
|
||||
openCodeProjects.push(mainProject)
|
||||
directoryAvailability.set(missingWorktree, "missing")
|
||||
const { switchRuntimeEndpoint } = await import("../lib/runtime-switch")
|
||||
beforeDirectoryAvailabilityResolve = () => {
|
||||
switchRuntimeEndpoint({ apiBaseUrl: "http://other.test", runtimeKey: "other-runtime" })
|
||||
}
|
||||
const { relocateSessionFromMissingDirectory, setActionRefs } = await import("./session-actions")
|
||||
setActionRefs(actionSdk, stores(), () => missingWorktree)
|
||||
|
||||
expect(await relocateSessionFromMissingDirectory("root")).toEqual({ status: "stale" })
|
||||
expect(movesOf()).toEqual([])
|
||||
expect(movedSessionDirectories).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1144,10 +1144,45 @@ function finalizeConfirmedSessionDeletion(
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanupDeletedChatDirectory(directory: string | undefined, deleteDirectory: boolean): Promise<void> {
|
||||
if (!directory || !deleteDirectory) return
|
||||
type ChatDirectoryCleanupPlan = {
|
||||
directory: string | undefined
|
||||
/** Only a root session owns its managed chat directory. */
|
||||
rootDeleted: boolean
|
||||
/** The deleted session and the descendants the server cascade-deletes with it. */
|
||||
cascadeIds: ReadonlySet<string>
|
||||
}
|
||||
|
||||
function planChatDirectoryCleanup(sessionId: string, snapshot: Session | null, directory: string | undefined): ChatDirectoryCleanupPlan {
|
||||
const global = useGlobalSessionsStore.getState()
|
||||
return {
|
||||
directory,
|
||||
rootDeleted: Boolean(snapshot && snapshot.parentID == null),
|
||||
cascadeIds: computeSubtreeIds([...global.activeSessions, ...global.archivedSessions], sessionId),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A managed chat directory is shared by every fork, side thread, and subagent
|
||||
* of the chat that created it, and OpenCode fails every prompt in a session
|
||||
* whose directory is gone. The directory is therefore removed only once no
|
||||
* known session outside the deleted subtree still resolves to it. An unloaded
|
||||
* global cache cannot prove that, so it keeps the directory: a leaked scratch
|
||||
* directory is recoverable, a stranded session is not.
|
||||
*/
|
||||
function isChatDirectoryStillReferenced(directory: string, excludedIds: ReadonlySet<string>): boolean {
|
||||
const global = useGlobalSessionsStore.getState()
|
||||
if (!global.hasLoaded) return true
|
||||
const normalized = normalizePath(directory)
|
||||
return [...global.activeSessions, ...global.archivedSessions].some((session) => (
|
||||
!excludedIds.has(session.id) && resolveGlobalSessionDirectory(session) === normalized
|
||||
))
|
||||
}
|
||||
|
||||
async function cleanupDeletedChatDirectory(plan: ChatDirectoryCleanupPlan): Promise<void> {
|
||||
if (!plan.directory || !plan.rootDeleted) return
|
||||
if (isChatDirectoryStillReferenced(plan.directory, plan.cascadeIds)) return
|
||||
try {
|
||||
await deleteChatDirectory(directory)
|
||||
await deleteChatDirectory(plan.directory)
|
||||
} catch (error) {
|
||||
console.warn("[session-actions] deleted chat directory cleanup failed", error)
|
||||
}
|
||||
@@ -1181,8 +1216,7 @@ export async function deleteSession(sessionId: string, options?: DeleteSessionOp
|
||||
const expectedRuntimeKey = options?.expectedRuntimeKey ?? getRuntimeKey()
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
const sessionDirectory = getSessionDirectory(sessionId)
|
||||
const sessionSnapshot = getGlobalSessionSnapshot(sessionId)
|
||||
const deleteManagedDirectory = Boolean(sessionSnapshot && sessionSnapshot.parentID == null)
|
||||
const chatDirectoryCleanup = planChatDirectoryCleanup(sessionId, getGlobalSessionSnapshot(sessionId), sessionDirectory)
|
||||
try {
|
||||
await cleanupReviewMetadataBeforeDelete(sessionId, sessionDirectory, expectedRuntimeKey)
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
@@ -1192,7 +1226,7 @@ export async function deleteSession(sessionId: string, options?: DeleteSessionOp
|
||||
throw new Error("session.delete failed: server did not confirm deletion")
|
||||
}
|
||||
finalizeConfirmedSessionDeletion(sessionId, sessionDirectory, expectedRuntimeKey)
|
||||
await cleanupDeletedChatDirectory(sessionDirectory, deleteManagedDirectory)
|
||||
await cleanupDeletedChatDirectory(chatDirectoryCleanup)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error("[session-actions] deleteSession failed", error)
|
||||
@@ -1202,7 +1236,7 @@ export async function deleteSession(sessionId: string, options?: DeleteSessionOp
|
||||
if ((error as { status?: number })?.status === 404) {
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
finalizeConfirmedSessionDeletion(sessionId, sessionDirectory, expectedRuntimeKey)
|
||||
await cleanupDeletedChatDirectory(sessionDirectory, deleteManagedDirectory)
|
||||
await cleanupDeletedChatDirectory(chatDirectoryCleanup)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -1216,8 +1250,7 @@ export async function deleteSessionInDirectory(
|
||||
expectedRuntimeKey = getRuntimeKey(),
|
||||
): Promise<boolean> {
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
const sessionSnapshot = getGlobalSessionSnapshot(sessionId)
|
||||
const deleteManagedDirectory = Boolean(sessionSnapshot && sessionSnapshot.parentID == null)
|
||||
const chatDirectoryCleanup = planChatDirectoryCleanup(sessionId, getGlobalSessionSnapshot(sessionId), directory)
|
||||
try {
|
||||
await cleanupReviewMetadataBeforeDelete(sessionId, directory, expectedRuntimeKey)
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
@@ -1227,14 +1260,14 @@ export async function deleteSessionInDirectory(
|
||||
throw new Error("session.delete failed: server did not confirm deletion")
|
||||
}
|
||||
finalizeConfirmedSessionDeletion(sessionId, directory, expectedRuntimeKey)
|
||||
await cleanupDeletedChatDirectory(directory, deleteManagedDirectory)
|
||||
await cleanupDeletedChatDirectory(chatDirectoryCleanup)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error("[session-actions] deleteSessionInDirectory failed", error)
|
||||
if ((error as { status?: number })?.status === 404) {
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
finalizeConfirmedSessionDeletion(sessionId, directory, expectedRuntimeKey)
|
||||
await cleanupDeletedChatDirectory(directory, deleteManagedDirectory)
|
||||
await cleanupDeletedChatDirectory(chatDirectoryCleanup)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -1511,11 +1544,13 @@ async function getProjectPrimaryDirectory(projectID?: string): Promise<string |
|
||||
}
|
||||
}
|
||||
|
||||
type MissingWorktreeRestore = { sourceDirectory: string; destinationDirectory: string }
|
||||
type MissingWorktreeRelocation = { sourceDirectory: string; destinationDirectory: string }
|
||||
|
||||
async function resolveMissingWorktreeRestore(
|
||||
const isFilesystemRoot = (directory: string): boolean => directory === "/" || /^[A-Za-z]:\/?$/.test(directory)
|
||||
|
||||
async function resolveMissingWorktreeRelocation(
|
||||
session: Session & { project?: { worktree?: string | null } | null },
|
||||
): Promise<MissingWorktreeRestore | null> {
|
||||
): Promise<MissingWorktreeRelocation | null> {
|
||||
const ownedDirectory = resolveSessionOwnedDirectory(session)
|
||||
const projectWorktree = session.project?.worktree?.trim()
|
||||
if (!ownedDirectory || !projectWorktree) return null
|
||||
@@ -1530,10 +1565,21 @@ async function resolveMissingWorktreeRestore(
|
||||
|
||||
const projectDirectory = await getProjectPrimaryDirectory(session.projectID)
|
||||
if (!projectDirectory || projectDirectory === ownedDirectory) return null
|
||||
// OpenCode files a directory outside any Git repository under its global
|
||||
// project, whose "worktree" is the filesystem root. That is not a home for
|
||||
// a session; a managed chat whose directory vanished stays where it is.
|
||||
if (isFilesystemRoot(projectDirectory)) return null
|
||||
return { sourceDirectory: ownedDirectory, destinationDirectory: projectDirectory }
|
||||
}
|
||||
|
||||
function getRestoreSubtree(rootSession: Session, sourceDirectory: string): Array<{ session: Session; sourceDirectory: string }> {
|
||||
type OwnedSubtreeEntry = { session: Session; ownedDirectory: string | null }
|
||||
|
||||
/**
|
||||
* The root's subtree as the global cache knows it, root first. Drawn from the
|
||||
* global cache rather than a live child store so archived descendants that
|
||||
* never materialized in a directory store are still included.
|
||||
*/
|
||||
function getGlobalSubtree(rootSession: Session): OwnedSubtreeEntry[] {
|
||||
const global = useGlobalSessionsStore.getState()
|
||||
const sessionsById = new Map<string, Session>()
|
||||
|
||||
@@ -1547,6 +1593,10 @@ function getRestoreSubtree(rootSession: Session, sourceDirectory: string): Array
|
||||
.map((id) => sessionsById.get(id))
|
||||
.filter((session): session is Session => Boolean(session))
|
||||
.map((session) => ({ session, ownedDirectory: resolveSessionOwnedDirectory(session) }))
|
||||
}
|
||||
|
||||
function getRestoreSubtree(rootSession: Session, sourceDirectory: string): Array<{ session: Session; sourceDirectory: string }> {
|
||||
return getGlobalSubtree(rootSession)
|
||||
// Keep a node while it is still archived or still stranded in the
|
||||
// confirmed-missing worktree. The second clause matters on retry: a prior
|
||||
// attempt may have already unarchived the root (server echo made it active)
|
||||
@@ -1557,6 +1607,58 @@ function getRestoreSubtree(rootSession: Session, sourceDirectory: string): Array
|
||||
.filter((entry): entry is { session: Session; sourceDirectory: string } => entry !== null)
|
||||
}
|
||||
|
||||
export type MissingDirectoryRelocation =
|
||||
/** The session's directory is gone; its subtree now lives in the project directory. */
|
||||
| { status: "moved"; sourceDirectory: string; destinationDirectory: string; movedSessionIds: string[] }
|
||||
/** The directory is available, its state is unknown, or the session has no project to move to. */
|
||||
| { status: "unchanged" }
|
||||
/** The runtime changed while the relocation was in flight; nothing local was published. */
|
||||
| { status: "stale" }
|
||||
/** A control-plane move failed; `movedSessionIds` already live in the destination. */
|
||||
| { status: "failed"; movedSessionIds: string[]; error: unknown }
|
||||
|
||||
/**
|
||||
* Move an active session whose worktree no longer exists into its project's
|
||||
* primary directory.
|
||||
*
|
||||
* Same gate as the archived-session restore fallback: only a server-confirmed
|
||||
* `missing` directory qualifies, the destination is the OpenCode project the
|
||||
* session belongs to, and `available`, `unknown`, probe failures, and sessions
|
||||
* without a project leave everything untouched. Every session of the root's
|
||||
* subtree still stranded in that directory moves with it, root first, so the
|
||||
* session the user is looking at is usable even if a descendant move fails.
|
||||
* Moves carry no changes (`moveChanges: false`): the directory is gone, so
|
||||
* there is nothing to carry.
|
||||
*/
|
||||
export async function relocateSessionFromMissingDirectory(
|
||||
sessionId: string,
|
||||
expectedRuntimeKey = getRuntimeKey(),
|
||||
): Promise<MissingDirectoryRelocation> {
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return { status: "stale" }
|
||||
const rootSession = getGlobalSessionSnapshot(sessionId)
|
||||
if (!rootSession) return { status: "unchanged" }
|
||||
|
||||
const relocation = await resolveMissingWorktreeRelocation(rootSession)
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return { status: "stale" }
|
||||
if (!relocation) return { status: "unchanged" }
|
||||
|
||||
const stranded = getGlobalSubtree(rootSession)
|
||||
.filter((entry) => entry.ownedDirectory === relocation.sourceDirectory)
|
||||
.map((entry) => entry.session)
|
||||
const movedSessionIds: string[] = []
|
||||
for (const session of stranded) {
|
||||
try {
|
||||
await moveSessionToDirectory(session, relocation.sourceDirectory, relocation.destinationDirectory, false, expectedRuntimeKey)
|
||||
} catch (error) {
|
||||
console.error("[session-actions] relocateSessionFromMissingDirectory failed", error)
|
||||
return { status: "failed", movedSessionIds, error }
|
||||
}
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return { status: "stale" }
|
||||
movedSessionIds.push(session.id)
|
||||
}
|
||||
return { status: "moved", ...relocation, movedSessionIds }
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore one archived session back to the active list.
|
||||
*
|
||||
@@ -1573,7 +1675,7 @@ export async function unarchiveSession(sessionId: string, expectedRuntimeKey = g
|
||||
const sessionDirectory = getSessionDirectory(sessionId)
|
||||
try {
|
||||
const restore = globalSession
|
||||
? await resolveMissingWorktreeRestore(globalSession)
|
||||
? await resolveMissingWorktreeRelocation(globalSession)
|
||||
: null
|
||||
if (isStaleRuntime(expectedRuntimeKey)) return false
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import { getRuntimeKey } from '@/lib/runtime-switch';
|
||||
import { getDeferredSafeStorage } from '@/stores/utils/safeStorage';
|
||||
import { CHAT_DRAFT_PROJECT_ID } from '@/lib/chatDirectories';
|
||||
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
|
||||
import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
|
||||
import { subscribeWorktreeTopologyChanged } from '@/lib/worktrees/worktreeManager';
|
||||
import { createContextPart } from '@/lib/messages/contextParts';
|
||||
|
||||
/**
|
||||
@@ -1264,3 +1266,148 @@ const originalHomeInfo = opencodeClient.getFilesystemHomeInfo;
|
||||
opencodeClient.getFilesystemHomeInfo = async () => ({ home: '/Users/tester' });
|
||||
await ensureChatsRootDirectory();
|
||||
opencodeClient.getFilesystemHomeInfo = originalHomeInfo;
|
||||
|
||||
describe('missing session directory recovery', () => {
|
||||
const missingWorktree = '/projects/main/.worktrees/gone';
|
||||
const projectDirectory = '/projects/main';
|
||||
const moves = [];
|
||||
const probes = [];
|
||||
let availability = 'missing';
|
||||
let originalGetDirectoryAvailability;
|
||||
let originalGetSdkClient;
|
||||
let originalProjects;
|
||||
let originalActiveProjectId;
|
||||
let originalDirectoryState;
|
||||
let originalClientDirectory;
|
||||
let originalGlobalState;
|
||||
|
||||
const worktreeSession = (id, directory, parentID = null) => ({
|
||||
id,
|
||||
parentID: parentID ?? undefined,
|
||||
projectID: 'project-main',
|
||||
directory,
|
||||
project: { worktree: projectDirectory },
|
||||
title: id,
|
||||
version: '1',
|
||||
time: { created: 1, updated: 1 },
|
||||
});
|
||||
|
||||
const settle = async () => {
|
||||
for (let index = 0; index < 10; index += 1) await Bun.sleep(0);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
moves.length = 0;
|
||||
probes.length = 0;
|
||||
availability = 'missing';
|
||||
originalGetDirectoryAvailability = opencodeClient.getDirectoryAvailability;
|
||||
originalGetSdkClient = opencodeClient.getSdkClient;
|
||||
originalProjects = useProjectsStore.getState().projects;
|
||||
originalActiveProjectId = useProjectsStore.getState().activeProjectId;
|
||||
originalDirectoryState = useDirectoryStore.getState();
|
||||
originalClientDirectory = opencodeClient.getDirectory();
|
||||
originalGlobalState = useGlobalSessionsStore.getState();
|
||||
|
||||
const childStore = {
|
||||
getState: () => ({ session: [], message: {}, part: {}, session_status: {} }),
|
||||
setState: () => {},
|
||||
};
|
||||
const childStores = { children: new Map(), ensureChild: () => childStore, getChild: () => childStore };
|
||||
setActionRefs({
|
||||
project: { list: async () => ({ data: [{ id: 'project-main', worktree: projectDirectory }] }) },
|
||||
session: { messages: async () => ({ data: [] }) },
|
||||
}, childStores, () => projectDirectory);
|
||||
setOptimisticRefs(() => {}, () => {});
|
||||
opencodeClient.getSdkClient = () => ({
|
||||
experimental: { controlPlane: { moveSession: async (params) => { moves.push(params); return {}; } } },
|
||||
});
|
||||
opencodeClient.getDirectoryAvailability = async (directory) => {
|
||||
probes.push(directory);
|
||||
return availability;
|
||||
};
|
||||
useProjectsStore.setState({
|
||||
projects: [{ id: 'project-main', path: projectDirectory, label: 'Main' }],
|
||||
activeProjectId: 'project-main',
|
||||
});
|
||||
useSessionUIStore.setState({
|
||||
currentSessionId: null,
|
||||
currentSessionDirectory: null,
|
||||
worktreeMetadata: new Map(),
|
||||
newSessionDraft: { open: false, directoryOverride: null, parentID: null },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
opencodeClient.getDirectoryAvailability = originalGetDirectoryAvailability;
|
||||
opencodeClient.getSdkClient = originalGetSdkClient;
|
||||
useProjectsStore.setState({ projects: originalProjects, activeProjectId: originalActiveProjectId });
|
||||
useDirectoryStore.setState(originalDirectoryState, true);
|
||||
useGlobalSessionsStore.setState(originalGlobalState, true);
|
||||
opencodeClient.setDirectory(originalClientDirectory ?? undefined);
|
||||
useSessionUIStore.setState({ currentSessionId: null, currentSessionDirectory: null, worktreeMetadata: new Map() });
|
||||
});
|
||||
|
||||
test('moves the current session to its project, drops the worktree hint, and shares one attempt between callers', async () => {
|
||||
const root = worktreeSession('root', missingWorktree);
|
||||
const child = worktreeSession('child', missingWorktree, 'root');
|
||||
useGlobalSessionsStore.setState({ activeSessions: [root, child], archivedSessions: [] });
|
||||
useSessionUIStore.setState({ currentSessionId: 'root', currentSessionDirectory: missingWorktree });
|
||||
useSessionUIStore.getState().setWorktreeMetadata('root', { path: missingWorktree, branch: 'gone' });
|
||||
useSessionUIStore.getState().setWorktreeMetadata('child', { path: missingWorktree, branch: 'gone' });
|
||||
|
||||
const topologyChanges = [];
|
||||
const unsubscribe = subscribeWorktreeTopologyChanged((directory) => topologyChanges.push(directory));
|
||||
const store = useSessionUIStore.getState();
|
||||
const [first, second] = await Promise.all([
|
||||
store.recoverMissingSessionDirectory('root'),
|
||||
store.recoverMissingSessionDirectory('root'),
|
||||
]);
|
||||
unsubscribe();
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(topologyChanges).toEqual([projectDirectory]);
|
||||
expect(first.status).toBe('moved');
|
||||
expect(moves.map((move) => move.sessionID)).toEqual(['root', 'child']);
|
||||
expect(moves.every((move) => move.destination.directory === projectDirectory && move.moveChanges === false)).toBe(true);
|
||||
expect(useSessionUIStore.getState().worktreeMetadata.has('root')).toBe(false);
|
||||
expect(useSessionUIStore.getState().worktreeMetadata.has('child')).toBe(false);
|
||||
expect(useSessionWorktreeStore.getState().getAttachment('root')).toBeUndefined();
|
||||
expect(useSessionUIStore.getState().getDirectoryForSession('root')).toBe(projectDirectory);
|
||||
expect(useSessionUIStore.getState().currentSessionDirectory).toBe(projectDirectory);
|
||||
expect(useDirectoryStore.getState().currentDirectory).toBe(projectDirectory);
|
||||
});
|
||||
|
||||
test('probes a worktree session on activation and relocates it only when the directory is confirmed missing', async () => {
|
||||
const root = worktreeSession('root', missingWorktree);
|
||||
useGlobalSessionsStore.setState({ activeSessions: [root], archivedSessions: [] });
|
||||
|
||||
availability = 'available';
|
||||
useSessionUIStore.getState().setCurrentSession('root', missingWorktree);
|
||||
await settle();
|
||||
expect(probes).toEqual([missingWorktree]);
|
||||
expect(moves).toEqual([]);
|
||||
expect(useSessionUIStore.getState().currentSessionDirectory).toBe(missingWorktree);
|
||||
|
||||
availability = 'missing';
|
||||
useSessionUIStore.getState().setCurrentSession('root', missingWorktree);
|
||||
await settle();
|
||||
expect(moves.map((move) => move.sessionID)).toEqual(['root']);
|
||||
expect(useSessionUIStore.getState().currentSessionDirectory).toBe(projectDirectory);
|
||||
});
|
||||
|
||||
test('never probes a session that lives in its project root or in a managed chat directory', async () => {
|
||||
const chatDirectory = '/Users/tester/.config/openchamber/chats/2026-09-05/session-abc';
|
||||
useGlobalSessionsStore.setState({
|
||||
activeSessions: [worktreeSession('in-root', projectDirectory), worktreeSession('chat', chatDirectory)],
|
||||
archivedSessions: [],
|
||||
});
|
||||
|
||||
useSessionUIStore.getState().setCurrentSession('in-root', projectDirectory);
|
||||
await settle();
|
||||
useSessionUIStore.getState().setCurrentSession('chat', chatDirectory);
|
||||
await settle();
|
||||
|
||||
expect(probes).toEqual([]);
|
||||
expect(moves).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,7 +31,8 @@ import { useSkillsStore } from "@/stores/useSkillsStore"
|
||||
import { getDeferredSafeStorage } from "@/stores/utils/safeStorage"
|
||||
import { markPendingUserSendAnimation } from "@/lib/userSendAnimation"
|
||||
import { normalizePath } from "@/lib/pathNormalization"
|
||||
import { CHAT_DRAFT_PROJECT_ID, createChatDirectory, deleteChatDirectory, getChatsRootFromDirectory, isChatDirectoryPath, warmChatsRootDirectory } from "@/lib/chatDirectories"
|
||||
import type { ProjectEntry } from "@/lib/api/types"
|
||||
import { CHAT_DRAFT_PROJECT_ID, createChatDirectory, deleteChatDirectory, getChatsRootFromDirectory, isChatDirectoryForHome, isChatDirectoryPath, warmChatsRootDirectory } from "@/lib/chatDirectories"
|
||||
import { isVSCodeRuntime } from "@/lib/desktop"
|
||||
import { composeForkSessionMessage } from "@/lib/messages/executionMeta"
|
||||
import { findLatestUserModelChoice } from "@/lib/messages/userModelChoice"
|
||||
@@ -71,7 +72,9 @@ import {
|
||||
unrevertSession as unrevertSessionAction,
|
||||
forkFromMessage as forkFromMessageAction,
|
||||
fetchMessagesForSession,
|
||||
relocateSessionFromMissingDirectory,
|
||||
type ArchiveSessionsOptions,
|
||||
type MissingDirectoryRelocation,
|
||||
type DeleteSessionOptions,
|
||||
type DeleteSessionsOptions,
|
||||
type UnarchiveSessionsOptions,
|
||||
@@ -375,6 +378,13 @@ export type SessionUIState = {
|
||||
transition?: "submitted-draft",
|
||||
) => void
|
||||
clearMaterializedDraftSession: (sessionId: string) => void
|
||||
/**
|
||||
* Move a session whose directory no longer exists (a worktree deleted
|
||||
* outside OpenChamber) into its project directory. Concurrent calls for the
|
||||
* same session share one attempt. Resolves `unchanged` when the directory is
|
||||
* available, unknown, or the session has no project to move to.
|
||||
*/
|
||||
recoverMissingSessionDirectory: (sessionId: string) => Promise<MissingDirectoryRelocation>
|
||||
prepareForRuntimeSwitch: (apiBaseUrl?: string | null) => void
|
||||
restoreForRuntimeSwitch: (apiBaseUrl?: string | null) => void
|
||||
openNewSessionDraft: (options?: Partial<NewSessionDraftState> & { automatic?: boolean }) => void
|
||||
@@ -758,6 +768,27 @@ const resolveCreatableDraftDirectory = async (
|
||||
}
|
||||
}
|
||||
|
||||
const pendingDirectoryRecoveries = new Map<string, Promise<MissingDirectoryRelocation>>()
|
||||
|
||||
/**
|
||||
* Only a directory that is neither a registered project root nor a managed
|
||||
* chat directory can be a deleted worktree. Project roots and chat directories
|
||||
* have nowhere to relocate to, so they are never probed.
|
||||
*/
|
||||
const isRelocatableSessionDirectory = (directory: string, projects: readonly ProjectEntry[]): boolean => {
|
||||
if (isChatDirectoryForHome(directory, useDirectoryStore.getState().homeDirectory)) return false
|
||||
return !projects.some((project) => normalizePath(project.path) === directory)
|
||||
}
|
||||
|
||||
const notifySessionRelocated = async (destinationDirectory: string): Promise<void> => {
|
||||
const { toast } = await import("sonner")
|
||||
const { useI18nStore, formatMessage } = await import("@/lib/i18n/store")
|
||||
const project = useProjectsStore.getState().projects.find((entry) => normalizePath(entry.path) === destinationDirectory)
|
||||
toast.info(formatMessage(useI18nStore.getState().dictionary, "sessions.missingDirectory.movedToProject", {
|
||||
project: project?.label ?? destinationDirectory,
|
||||
}))
|
||||
}
|
||||
|
||||
const recoverStaleDraftDirectory = async (openedDraft: NewSessionDraftState): Promise<void> => {
|
||||
const resolved = await resolveCreatableDraftDirectory(openedDraft, openedDraft.directoryOverride)
|
||||
if (resolved.status !== "ok") return
|
||||
@@ -1078,6 +1109,16 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
console.warn("Failed to set OpenCode directory for session switch:", e)
|
||||
}
|
||||
|
||||
// A worktree session may have lost its directory while it was in the
|
||||
// background. Probe on activation, the same way a reopened draft probes
|
||||
// its inherited directory, so the session is relocated before its tabs
|
||||
// and prompts run against a path that is gone. VS Code registers no
|
||||
// worktrees, so every session there is its workspace root.
|
||||
if (id && !isGuessedDir && resolvedDir && !isVSCodeRuntime()
|
||||
&& isRelocatableSessionDirectory(resolvedDir, projectsState.projects)) {
|
||||
void get().recoverMissingSessionDirectory(id)
|
||||
}
|
||||
|
||||
// Defer viewport anchor save for previous session — not needed for the
|
||||
// skeleton to render and reads messages which can be expensive.
|
||||
if (previousSessionId && previousSessionId !== id) {
|
||||
@@ -1169,6 +1210,40 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
// ---------------------------------------------------------------------------
|
||||
// openNewSessionDraft
|
||||
// ---------------------------------------------------------------------------
|
||||
recoverMissingSessionDirectory: (sessionId) => {
|
||||
const runtimeKey = getRuntimeKey()
|
||||
const key = `${runtimeKey}:${sessionId}`
|
||||
const pending = pendingDirectoryRecoveries.get(key)
|
||||
if (pending) return pending
|
||||
|
||||
const recovery = relocateSessionFromMissingDirectory(sessionId, runtimeKey)
|
||||
.then(async (result) => {
|
||||
if (result.status !== "moved" && result.status !== "failed") return result
|
||||
// The worktree hint was the first thing every directory lookup read;
|
||||
// with the worktree gone it would keep routing tabs to the dead path.
|
||||
for (const movedId of result.movedSessionIds) {
|
||||
get().setWorktreeMetadata(movedId, null)
|
||||
}
|
||||
if (result.status !== "moved") return result
|
||||
if (get().currentSessionId === sessionId) {
|
||||
// Re-select through the normal path so the active directory, project,
|
||||
// and OpenCode client all follow the session to its new home.
|
||||
get().setCurrentSession(sessionId, result.destinationDirectory)
|
||||
}
|
||||
// The server just confirmed a worktree directory is gone; the sidebar's
|
||||
// worktree topology for that project is stale, so let it rediscover.
|
||||
const { notifyWorktreeTopologyChanged } = await import("@/lib/worktrees/worktreeManager")
|
||||
notifyWorktreeTopologyChanged(result.destinationDirectory)
|
||||
await notifySessionRelocated(result.destinationDirectory)
|
||||
return result
|
||||
})
|
||||
.finally(() => {
|
||||
pendingDirectoryRecoveries.delete(key)
|
||||
})
|
||||
pendingDirectoryRecoveries.set(key, recovery)
|
||||
return recovery
|
||||
},
|
||||
|
||||
openNewSessionDraft: (options) => {
|
||||
// A USER-initiated draft open is a navigation choice: the next cold launch
|
||||
// should land on the draft, not re-open the session left behind — drop the
|
||||
|
||||
@@ -138,11 +138,11 @@ export function resolveSessionWorktreeState(
|
||||
|
||||
export function formatSessionWorktreeBadge(
|
||||
attachment: SessionWorktreeAttachment,
|
||||
labels?: { pending?: string }
|
||||
labels?: { pending?: string; missing?: string }
|
||||
): string {
|
||||
if (attachment.legacy) return 'Legacy session';
|
||||
if (attachment.worktreeStatus === 'pending') return labels?.pending ?? 'Needs attention';
|
||||
if (attachment.worktreeStatus === 'missing') return 'Worktree missing';
|
||||
if (attachment.worktreeStatus === 'missing') return labels?.missing ?? 'Worktree missing';
|
||||
if (attachment.worktreeStatus === 'not-a-repo') return 'Not a repo';
|
||||
if (attachment.worktreeStatus === 'invalid') return 'Needs attention';
|
||||
if (attachment.attentionReason) return 'Needs attention';
|
||||
|
||||
Reference in New Issue
Block a user