Skip to content

The agent that grows with you

fix(desktop): stop new chats inheriting the focused session's folder

David Metcalfe6dda0c91d9dc
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 a70cfedd8e3..85e8957ee1b 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(<Harness />)
+ 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 99ccc0564cb..3de644dc0fb 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/store/projects.test.ts b/apps/desktop/src/store/projects.test.ts
index 8ab7d165ee5..cd85c6e185a 100644
--- a/apps/desktop/src/store/projects.test.ts
+++ b/apps/desktop/src/store/projects.test.ts
@@ -144,15 +144,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 +167,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', () => {
diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts
index 5808abcad80..4471673c3d6 100644
--- a/apps/desktop/src/store/projects.ts
+++ b/apps/desktop/src/store/projects.ts
@@ -17,15 +17,12 @@ 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 +201,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,58 +226,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}/`)