diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx index a70cfedd8e..85e8957ee1 100644 --- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx +++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, render } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { $desktopBoot } from '@/store/boot' -import { $gatewayState } from '@/store/session' +import { $currentCwd, $gatewayState } from '@/store/session' import { takeGatewaySurvivor } from './gateway-hmr-survivor' import { useGatewayBoot } from './use-gateway-boot' @@ -180,6 +180,8 @@ afterEach(() => { vi.useRealTimers() ;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket delete (window as { hermesDesktop?: unknown }).hermesDesktop + window.localStorage.removeItem('hermes.desktop.workspace-cwd') + $currentCwd.set('') }) // Let pending microtasks (awaits) AND the queued 0ms socket open/error fire. @@ -337,4 +339,47 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () => expect($desktopBoot.get().visible).toBe(false) expect($desktopBoot.get().phase).toBe('renderer.ready') }) + + it('seeds the configured default project dir pre-connect — no route-resume race (#71873)', async () => { + // The reporter's scenario: a configured default project dir must be applied + // at boot regardless of route-resume timing. The seed now runs BEFORE the + // gateway opens, so no session restore can race it (route-resume is gated + // on gatewayState === 'open'). + const desktop = fakeDesktop() as { + sanitizeWorkspaceCwd?: unknown + settings?: unknown + } + + desktop.settings = { + getDefaultProjectDir: vi.fn(async () => ({ + defaultLabel: 'C:\\Users\\sonny', + dir: 'C:\\Hermes', + resolvedCwd: 'C:\\Hermes' + })), + pickDefaultProjectDir: vi.fn(async () => undefined), + setDefaultProjectDir: vi.fn(async () => undefined) + } + desktop.sanitizeWorkspaceCwd = vi.fn(async (cwd: string) => ({ cwd })) + ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop + + // Record the cwd at the exact moment the gateway opens its WebSocket: if + // the seed moved back post-connect, this would still be '' here and the + // end-state assertion would pass anyway (the seed would run later in the + // same flush). The construction-time snapshot is what proves ordering. + let cwdAtConnect = '' + class RecordingSocket extends FakeWebSocket { + constructor(url: string) { + super(url) + cwdAtConnect = $currentCwd.get() + } + } + + ;(globalThis as { WebSocket: unknown }).WebSocket = RecordingSocket + + render() + await flushAsync() + + expect(cwdAtConnect).toBe('C:\\Hermes') + expect($currentCwd.get()).toBe('C:\\Hermes') + }) }) diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts index 99ccc0564c..3de644dc0f 100644 --- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts +++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts @@ -500,6 +500,19 @@ export function useGatewayBoot({ progress: 95 }) publish(conn) + // Seed the workspace BEFORE the gateway opens: every session-restore + // path is gated on gatewayState === 'open', so nothing can be active yet + // and ensureDefaultWorkspaceCwd's live-session guard passes. The + // post-connect seed could lose that race on a slow start (#71873). A + // resumed session's own cwd still supersedes this once its runtime + // arrives. Non-fatal: the remembered cwd is a fine fallback and the + // post-connect pass retries the sync. + try { + await ensureDefaultWorkspaceCwd() + } catch (err) { + console.warn('Failed to seed default workspace cwd pre-connect', err) + } + // Mint a fresh WS URL right before connecting. For OAuth gateways the // ticket is single-use with a short TTL, so the ticket baked into // conn.wsUrl is stale; resolveGatewayWsUrl() re-mints it rather than @@ -526,7 +539,10 @@ export function useGatewayBoot({ }) await Promise.all([ - seedDefaultCwd(), + // The pre-connect seed already applied the configured default; this + // post-connect pass covers the remote backend default. Non-fatal: a + // failed sync must not abort boot (the remembered cwd remains). + seedDefaultCwd().catch(err => console.warn('Failed to sync default workspace cwd post-connect', err)), callbacksRef.current.refreshHermesConfig(), // Session-list population is never boot-fatal. The gateway WS is // already open by this point — a failed sidebar fetch (transient diff --git a/apps/desktop/src/app/right-sidebar/files/ipc.ts b/apps/desktop/src/app/right-sidebar/files/ipc.ts index 29fc468592..3141b23281 100644 --- a/apps/desktop/src/app/right-sidebar/files/ipc.ts +++ b/apps/desktop/src/app/right-sidebar/files/ipc.ts @@ -3,6 +3,7 @@ import ignore from 'ignore' import type { HermesReadDirEntry, HermesReadDirResult } from '@/global' import { desktopFsCacheKey, desktopGitRoot, readDesktopDir, readDesktopFileDataUrl } from '@/lib/desktop-fs' import { ALWAYS_EXCLUDED } from '@/lib/excluded-paths' +import { cleanPath, comparisonPath } from '@/lib/path-compare' export type ProjectTreeEntry = HermesReadDirEntry @@ -28,21 +29,10 @@ function decodeDataUrl(dataUrl: string) { return new TextDecoder().decode(bytes) } -function clean(path: string) { - return path.replace(/\\/g, '/').replace(/\/+$/, '') || '/' -} - -// Windows path identity is case-insensitive. Fold only comparison keys so the -// relative path returned below keeps the filesystem's original spelling; -// POSIX paths remain case-sensitive. -function comparisonPath(path: string) { - return /^[A-Za-z]:(?:\/|$)/.test(path) || path.startsWith('//') ? path.toLowerCase() : path -} - /** Strict POSIX-style relative path; null if `child` is not inside `root`. */ function relativeTo(root: string, child: string) { - const r = clean(root) - const c = clean(child) + const r = cleanPath(root) + const c = cleanPath(child) const rKey = comparisonPath(r) const cKey = comparisonPath(c) @@ -55,7 +45,7 @@ function relativeTo(root: string, child: string) { /** Repo-root → repo-root/a → repo-root/a/b → … for every dir between root and `dir`. */ function ancestorDirs(root: string, dir: string) { - const r = clean(root) + const r = cleanPath(root) const rel = relativeTo(r, dir) if (rel === null || rel === '') { @@ -74,11 +64,11 @@ function ancestorDirs(root: string, dir: string) { } async function gitRootFor(start: string) { - const key = `${desktopFsCacheKey()}:${clean(start)}` + const key = `${desktopFsCacheKey()}:${cleanPath(start)}` let cached = gitRootCache.get(key) if (!cached) { - cached = desktopGitRoot(clean(start)) + cached = desktopGitRoot(cleanPath(start)) gitRootCache.set(key, cached) } @@ -103,11 +93,11 @@ async function readGitignore(dir: string): Promise { } async function gitignoreFor(dir: string) { - const key = `${desktopFsCacheKey()}:${clean(dir)}` + const key = `${desktopFsCacheKey()}:${cleanPath(dir)}` let cached = gitignoreCache.get(key) if (!cached) { - cached = readGitignore(clean(dir)) + cached = readGitignore(cleanPath(dir)) gitignoreCache.set(key, cached) } @@ -159,7 +149,7 @@ export function clearProjectDirCache(rootPath?: string) { return } - const key = `${desktopFsCacheKey()}:${clean(rootPath)}` + const key = `${desktopFsCacheKey()}:${cleanPath(rootPath)}` gitRootCache.delete(key) gitignoreCache.delete(key) } diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts index 2389b17ca1..ee13f48521 100644 --- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts +++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts @@ -51,7 +51,7 @@ import { $sessions, sessionMatchesStoredId, setCurrentBranch, - setCurrentCwd, + setCurrentCwdTransient, setCurrentFastMode, setCurrentPersonality, setCurrentReasoningEffort, @@ -446,7 +446,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) { const sameSession = !!sessionId && sessionId === lastCwdInfoSessionRef.current lastCwdInfoSessionRef.current = sessionId - setCurrentCwd(payload.cwd) + setCurrentCwdTransient(payload.cwd) // The backend just confirmed the selected conversation's real // workspace, so it owns the path we wrote. Without the claim the diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts index bfa2950151..23781c4942 100644 --- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts +++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts @@ -344,7 +344,9 @@ export function useSessionActions({ if (!hasWorkspaceTarget) { // In a project → the repo's default-branch checkout; not in a project → // detached. So cmd-n does not inherit an unrelated linked worktree. - setCurrentCwd(resolveNewSessionCwd()) + // Transient: a resolved default is not the user naming a workspace, and + // remembering it here would make the NEXT new chat inherit it. + setCurrentCwdTransient(resolveNewSessionCwd()) } else if (workspaceTarget === null) { setCurrentCwdTransient('') } else if (typeof workspaceTarget === 'string') { @@ -498,7 +500,7 @@ export function useSessionActions({ try { // Fresh tile → the caller's workspace when one was named (the sidebar // "+" on a project/worktree lane), else the resolved new-session cwd - // (focused session's project → project scope → default). + // (project scope → configured default). const params = await desktopSessionCreateParams((options?.cwd || resolveNewSessionCwd()).trim()) const created = await requestGateway('session.create', params) const stored = created.stored_session_id @@ -533,7 +535,7 @@ export function useSessionActions({ patchSessionTile(stored, { runtimeId: created.session_id }) if (dir === 'center' && runtimeInfo?.cwd) { - setCurrentCwd(runtimeInfo.cwd) + setCurrentCwdTransient(runtimeInfo.cwd) setWorkspaceCwdOwner(stored) } @@ -716,7 +718,7 @@ export function useSessionActions({ setActiveSessionId(cachedRuntimeId) activeSessionIdRef.current = cachedRuntimeId syncSessionStateToView(cachedRuntimeId, cachedViewState) - setCurrentCwd(cachedViewState.cwd) + setCurrentCwdTransient(cachedViewState.cwd) // The warm cache IS this conversation's own workspace truth, so the // switch is already re-homed here. This claim cannot wait for // `session.activate`: its missing-RPC compat branch returns before diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts index 4648ca5ff1..29e8d105dd 100644 --- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts +++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts @@ -13,7 +13,7 @@ import { releaseWorkspaceCwdOwner, sessionMatchesStoredId, setCurrentBranch, - setCurrentCwd, + setCurrentCwdTransient, setCurrentFastMode, setCurrentModel, setCurrentPersonality, @@ -968,9 +968,8 @@ function publishRuntimeToComposer(state: SessionRuntimeStatePatch): void { commitWorkspaceCwdForSelectedSession(state.cwd) } else { // A detached session: the path on screen is provably still the previous - // conversation's. Release rather than write `''` — `setCurrentCwd` - // persists, so blanking here would also wipe the remembered workspace - // that seeds `$currentCwd` on next boot. + // conversation's. Release rather than write `''` — clearing it collapses + // the workspace/review panes on every switch. releaseWorkspaceCwdOwner() } } @@ -1098,7 +1097,7 @@ export function applyStoredSessionPreviewRuntimeInfo( const storedCwd = stored?.cwd?.trim() || '' if (storedCwd) { - setCurrentCwd(storedCwd) + setCurrentCwdTransient(storedCwd) setWorkspaceCwdOwner(storedSessionId) } else { // Either a genuinely detached session, or a row outside the loaded sidebar diff --git a/apps/desktop/src/lib/path-compare.test.ts b/apps/desktop/src/lib/path-compare.test.ts new file mode 100644 index 0000000000..30e3184f88 --- /dev/null +++ b/apps/desktop/src/lib/path-compare.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' + +import { cleanPath, comparisonPath, isUnderPath } from './path-compare' + +describe('cleanPath', () => { + it('unifies separators and drops trailing slashes', () => { + expect(cleanPath('C:\\Repos\\App\\')).toBe('C:/Repos/App') + expect(cleanPath(' /home/user/repo// ')).toBe('/home/user/repo') + }) + + it('keeps root rather than collapsing to empty', () => { + expect(cleanPath('/')).toBe('/') + }) +}) + +describe('comparisonPath', () => { + it('folds case for Windows drive and UNC paths only', () => { + expect(comparisonPath('C:/Repos/App')).toBe('c:/repos/app') + expect(comparisonPath('//server/Share')).toBe('//server/share') + expect(comparisonPath('/home/User/Repo')).toBe('/home/User/Repo') + }) +}) + +describe('isUnderPath', () => { + it('matches a nested path across separator and case differences', () => { + expect(isUnderPath('C:\\Repos\\App', 'c:/repos/app/src')).toBe(true) + expect(isUnderPath('C:/Repos/App/', 'C:\\Repos\\App')).toBe(true) + }) + + it('stays case-sensitive on POSIX', () => { + expect(isUnderPath('/home/user/repo', '/home/user/repo/src')).toBe(true) + expect(isUnderPath('/home/user/repo', '/home/user/Repo/src')).toBe(false) + }) + + it('does not treat a sibling with a shared prefix as nested', () => { + expect(isUnderPath('/repos/app', '/repos/app-retry')).toBe(false) + }) +}) diff --git a/apps/desktop/src/lib/path-compare.ts b/apps/desktop/src/lib/path-compare.ts new file mode 100644 index 0000000000..e477a578cf --- /dev/null +++ b/apps/desktop/src/lib/path-compare.ts @@ -0,0 +1,23 @@ +/** Comparing two paths for identity or containment, across host spellings. + * + * A cwd reaches us from the backend, a picker, a session row and a project + * record, and the four don't agree on separator, trailing slash or drive-letter + * case. Compare through these rather than `===` / `startsWith`. + */ + +/** POSIX-style spelling: one separator, no trailing slash. */ +export const cleanPath = (path: string): string => path.trim().replace(/\\/g, '/').replace(/\/+$/, '') || '/' + +/** Case-folded comparison key. Windows drive/UNC paths are case-insensitive; + * POSIX paths are not, and callers that display a path want its real spelling, + * so fold only the key. Expects an already-`cleanPath`ed value. */ +export const comparisonPath = (path: string): string => + /^[A-Za-z]:(?:\/|$)/.test(path) || path.startsWith('//') ? path.toLowerCase() : path + +/** True when `child` IS `parent` or lives underneath it. */ +export const isUnderPath = (parent: string, child: string): boolean => { + const p = comparisonPath(cleanPath(parent)) + const c = comparisonPath(cleanPath(child)) + + return c === p || c.startsWith(`${p}/`) +} diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.ts index 8ab7d165ee..5071485195 100644 --- a/apps/desktop/src/store/projects.test.ts +++ b/apps/desktop/src/store/projects.test.ts @@ -22,6 +22,7 @@ import { exitProjectScope, openProjectCreate, pickProjectFolder, + projectIdForCwd, projectNameForCwd, refreshProjects, refreshProjectTree, @@ -144,15 +145,16 @@ describe('resolveNewSessionCwd', () => { expect(resolveNewSessionCwd()).toBe('/home/user/configured') }) - it('inherits the focused session workspace when not drilled into a project', () => { - // Simulate a primary session whose stored row carries a project cwd — - // the common case: you're in a chat that has a pwd, hit ⌘N/⌘T, and - // expect the new draft to stay in that project without sidebar drill-in. + it('does not inherit the focused session workspace — new chat uses the configured default', () => { + // Regression for #71873 / #80213: after a restart the focused session is + // usually the just-resumed one, whose stored cwd can be a stale fallback + // (e.g. the user's home dir on Windows). A new chat must NOT land there — + // it falls through to the configured default project dir. $selectedStoredSessionId.set('sess-a') $sessions.set([ { archived: false, - cwd: '/Users/me/www/hermes-agent', + cwd: 'C:\\Users\\sonny', ended_at: null, id: 'sess-a', input_tokens: 0, @@ -166,7 +168,7 @@ describe('resolveNewSessionCwd', () => { } as never ]) - expect(resolveNewSessionCwd()).toBe('/Users/me/www/hermes-agent') + expect(resolveNewSessionCwd()).toBe('/home/user/configured') }) it('does not re-attach a remembered cwd when the focused session is detached', () => { @@ -240,6 +242,13 @@ describe('projectNameForCwd', () => { expect(projectNameForCwd('/elsewhere/mono-feature/src')).toBe('Monorepo') }) + it('matches nested Windows paths across separator and case differences', () => { + $projectTree.set([treeNode({ id: 'p_win', label: 'Windows app', path: 'C:\\Repos\\App' })]) + + expect(projectIdForCwd('c:/repos/app/src')).toBe('p_win') + expect(projectNameForCwd('c:/repos/app/src')).toBe('Windows app') + }) + it('ignores auto-projects and the No-project bucket (no named identity)', () => { $projectTree.set([ treeNode({ id: '/repos/loose', label: 'loose', path: '/repos/loose', isAuto: true }), diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts index 5808abcad8..5d7a0a222d 100644 --- a/apps/desktop/src/store/projects.ts +++ b/apps/desktop/src/store/projects.ts @@ -11,21 +11,19 @@ import { translateNow } from '@/i18n' import { desktopDefaultCwd, isDesktopFsRemoteMode, selectDesktopPaths, writeDesktopFileText } from '@/lib/desktop-fs' import { desktopGit } from '@/lib/desktop-git' import { isMissingRpcMethod } from '@/lib/gateway-rpc' +import { isUnderPath } from '@/lib/path-compare' import { persistentAtom } from '@/lib/persisted' import { $gateway, activeGateway, ensureActiveGatewayOpen } from '@/store/gateway' import { setSidebarAgentsGrouped } from '@/store/layout' import { notify } from '@/store/notifications' import { $activeGatewayProfile, requestFreshSession } from '@/store/profile' import { - $currentCwd, $selectedStoredSessionId, $sessions, - idsShareLineage, sessionMatchesStoredId, setSessions, workspaceCwdForNewSession } from '@/store/session' -import { $focusedSessionState, $focusedStoredSessionId } from '@/store/session-states' import type { ProjectInfo, ProjectsPayload } from '@/types/hermes' // First-class, per-profile Projects (named, multi-folder workspaces). State is @@ -204,15 +202,14 @@ export function goToProject(id: string, options?: { newSession?: boolean }): voi // // Priority (first hit wins): // 1. Explicit sidebar project scope (drilled into a project / Home bucket) -// 2. The FOCUSED session's workspace — so ⌘N / ⌘T from a chat that's already -// in a project/worktree stay there without requiring a sidebar drill-in -// 3. Configured default project dir / remote remembered cwd (detached otherwise) +// 2. Configured default project dir / remote remembered cwd (detached otherwise) // -// The "active project" is just an atom ($projectScope) — so when you're inside -// a project, a new session (cmd-n, the trunk "+") starts at that project's root -// (its primary repo = the default-branch checkout). Outside a project it used -// to fall straight to the plain default (detached), which dropped the workspace -// of the chat you were looking at — that's the case (2) covers. +// The "active project" is just an atom ($projectScope) — so inside a project a +// new session (cmd-n, the trunk "+") starts at that project's root (its primary +// repo = the default-branch checkout). Outside one it does NOT inherit the chat +// you were looking at: after a restart that's the just-resumed session, whose +// stored cwd is often a home-dir fallback, so every new chat landed there +// instead of the configured default (#71873, #80213, #77496). export function resolveNewSessionCwd(): string { const scope = $projectScope.get() @@ -230,61 +227,9 @@ export function resolveNewSessionCwd(): string { } } - // Inherit the focused chat's workspace. ⌘N/⌘T from a session that already - // has a project/pwd should stay there — drilling into the sidebar project - // is the uncommon path, not the requirement. - const focusedCwd = focusedSessionWorkspaceCwd() - - if (focusedCwd) { - return focusedCwd - } - return workspaceCwdForNewSession() } -/** Live workspace of the session the user is looking at (tile or primary). */ -function focusedSessionWorkspaceCwd(): string { - const focusedStoredId = $focusedStoredSessionId.get() - const state = $focusedSessionState.get() - - // Prefer the live runtime slice when it belongs to the focused chat - // (agent can relocate mid-turn). Cold tabs / mid-switch lag fall through - // to the stored session row. - const stateCwd = state?.cwd?.trim() || '' - const stateStoredId = state?.storedSessionId?.trim() || '' - - if ( - stateCwd && - (!focusedStoredId || - !stateStoredId || - stateStoredId === focusedStoredId || - idsShareLineage(focusedStoredId, stateStoredId, $sessions.get())) - ) { - return stateCwd - } - - if (focusedStoredId) { - const row = $sessions.get().find(s => sessionMatchesStoredId(s, focusedStoredId)) - const rowCwd = row?.cwd?.trim() || '' - - if (rowCwd) { - return rowCwd - } - - // Focused a real session with no workspace → stay detached. Do NOT fall - // through to `$currentCwd` (it may still hold a remembered path from an - // earlier chat and would re-attach a project the user left). - return '' - } - - // No focused stored session: primary draft. The composer atom is the draft's - // workspace target (set by startFreshSession / startSessionInWorkspace). - return $currentCwd.get().trim() -} - -const underPath = (parent: string, child: string): boolean => - child === parent || child.startsWith(parent.endsWith('/') ? parent : `${parent}/`) - // The project (explicit or auto) that owns `cwd`, by longest path match across // the live tree. Null when no project covers it (it'll surface as a fresh // auto-project on the next tree refresh). @@ -301,7 +246,7 @@ export function projectIdForCwd(cwd: string): null | string { for (const path of paths) { const p = (path || '').trim() - if (p && underPath(p, cwd) && p.length > bestLen) { + if (p && isUnderPath(p, cwd) && p.length > bestLen) { bestLen = p.length best = project.id } @@ -339,7 +284,7 @@ export function projectNameForCwd(cwd: string): null | string { for (const path of paths) { const p = (path || '').trim() - if (p && underPath(p, target) && p.length > bestLen) { + if (p && isUnderPath(p, target) && p.length > bestLen) { bestLen = p.length best = project.label } diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.ts index 891795821c..5bc19f5f78 100644 --- a/apps/desktop/src/store/session.test.ts +++ b/apps/desktop/src/store/session.test.ts @@ -13,6 +13,7 @@ import { $unreadFinishedSessionIds, _resetLegacyDiscardForTests, applyConfiguredDefaultProjectDir, + commitWorkspaceCwdForSelectedSession, getRememberedRoute, getRememberedSessionId, mergeSessionPage, @@ -21,6 +22,7 @@ import { sessionBelongsToProfile, sessionPinId, setCurrentCwd, + setCurrentCwdTransient, setRememberedRoute, setRememberedSessionId, setSelectedStoredSessionId, @@ -371,6 +373,34 @@ describe('workspaceCwdForNewSession', () => { $connection.set(null) expect(workspaceCwdForNewSession()).toBe('') }) + + it('remembers only the workspace the user picked, not the one they looked at', () => { + // The reported bug (#77496 / #80213): on a remote backend a new chat starts + // in the remembered workspace, and every session resume used to write that + // key — so opening a project chat silently made it the destination for the + // next "New session". Following a conversation must leave the memory alone. + $connection.set({ baseUrl: 'http://backend-a', mode: 'remote' } as never) + setCurrentCwd('/backend/picked') + + setCurrentCwdTransient('/backend/some-other-project') + + expect($currentCwd.get()).toBe('/backend/some-other-project') + expect(workspaceCwdForNewSession()).toBe('/backend/picked') + }) + + it('settling a resumed session does not move where the next new chat starts', () => { + // The reporter's exact sequence: work in a project, open a chat from it, + // then ask for a new session. Resume settling publishes the conversation's + // cwd through commitWorkspaceCwdForSelectedSession — which must not claim + // that folder as the user's chosen workspace. + $connection.set({ baseUrl: 'http://backend-a', mode: 'remote' } as never) + setCurrentCwd('/backend/picked') + + setSelectedStoredSessionId('sess-in-project') + commitWorkspaceCwdForSelectedSession('/backend/last-project') + + expect(workspaceCwdForNewSession()).toBe('/backend/picked') + }) }) function makeState(over: Partial = {}): ClientSessionState { diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts index 953745f811..cb84c2c9c6 100644 --- a/apps/desktop/src/store/session.ts +++ b/apps/desktop/src/store/session.ts @@ -197,9 +197,12 @@ export async function ensureDefaultWorkspaceCwd(): Promise { await syncConfiguredDefaultProjectDir() const configured = getConfiguredDefaultProjectDir() + // Transient: each source below is already remembered or comes from config, so + // persisting would only promote a configured default into the per-backend + // memory of what the user picked. const seedLiveCwd = (cwd: string) => { if (cwd && !$activeSessionId.get()) { - setCurrentCwd(cwd) + setCurrentCwdTransient(cwd) } } @@ -649,6 +652,14 @@ export const setCurrentFastMode = (next: Updater) => { export const setYoloActive = (next: Updater) => updateAtom($yoloActive, next) +/** Move the live workspace AND remember it as this backend's workspace. + * + * Only for a path the user chose — a folder pick, a project/worktree entry, an + * explicit workspace target. The remembered value is where a new chat starts on + * a remote backend, so writing it from a path the user merely *looked at* makes + * every new chat land in the last session's folder (#77496, #80213). To follow + * a conversation's cwd, use `setCurrentCwdTransient`. + */ export const setCurrentCwd = (next: Updater) => { updateAtom($currentCwd, next) persistString(workspaceCwdKey(), $currentCwd.get().trim() || null) @@ -656,6 +667,11 @@ export const setCurrentCwd = (next: Updater) => { export const setTerminalBackend = (next: Updater) => updateAtom($terminalBackend, next) +/** Move the live workspace without claiming it as the user's chosen one. + * + * For paths that come from a conversation rather than from the user: resume + * settling, a warm switch, the agent relocating mid-turn, detaching a draft. + */ export const setCurrentCwdTransient = (next: Updater) => updateAtom($currentCwd, next) // Released-ownership marker: the live path belongs to no conversation. `null` @@ -688,12 +704,12 @@ export const releaseWorkspaceCwdOwner = () => updateAtom($workspaceCwdOwner, WOR * * The single primitive for "this path IS the selected conversation's" — a folder * pick, a project entry, the agent relocating itself. Prefer it over a bare - * `setCurrentCwd`, which moves the path while leaving ownership naming whatever - * held it before; workspace-derived slices then stay hidden even though the - * path is correct (#71254). + * `setCurrentCwdTransient`, which moves the path while leaving ownership naming + * whatever held it before; workspace-derived slices then stay hidden even though + * the path is correct (#71254). */ export const commitWorkspaceCwdForSelectedSession = (cwd: string) => { - setCurrentCwd(cwd) + setCurrentCwdTransient(cwd) setWorkspaceCwdOwner($selectedStoredSessionId.get()) }