Skip to content

The agent that grows with you

fix(webapp): read a new session's folder under the profile that owns it

Adolanium514b95b45117
diff --git a/apps/desktop/src/app/session/hooks/browser-profile-folder.test.ts b/apps/desktop/src/app/session/hooks/browser-profile-folder.test.ts
new file mode 100644
index 00000000000..f66f64f3a3a
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/browser-profile-folder.test.ts
@@ -0,0 +1,191 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { requestGatewayForAgent } from '@/store/gateway'
+import {
+ $activeGatewayProfile,
+ $newChatProfile,
+ $newChatRoute,
+ captureNewChatSource,
+ selectProfile
+} from '@/store/profile'
+import {
+ $connection,
+ $currentCwd,
+ applyConfiguredDefaultProjectDir,
+ setActiveSessionId,
+ setConnection,
+ syncConfiguredDefaultProjectDir
+} from '@/store/session'
+import { $sessionTiles } from '@/store/session-states'
+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'
+
+import { useSessionActions } from './use-session-actions'
+
+// A Webapp tab keeps each profile's default folder under its own key. The
+// window also caches ONE folder, filled at boot for the profile it booted on,
+// and a profile picked from the rail never refills it. These cases drive the
+// real browser bridge, the real rail switch and the real session actions; only
+// the gateway sockets are faked.
+
+const gateway = vi.hoisted(() => ({
+ ensureGatewayForProfile: vi.fn(async (_profile: string) => undefined)
+}))
+
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ activeGatewayConnectionId: vi.fn(() => null),
+ activeGatewayProfileKey: () => gateway.ensureGatewayForProfile.mock.lastCall?.[0] ?? 'alpha',
+ ensureGatewayForAgent: vi.fn(async () => true),
+ ensureGatewayForProfile: gateway.ensureGatewayForProfile,
+ requestGatewayForAgent: vi.fn(),
+ retainGatewayForAgent: vi.fn(async () => () => undefined)
+}))
+
+const FOREGROUND_CREATE_DIAL = [undefined, undefined, { spawnPriority: 'foreground' }] as const
+
+const host = window as Window & { __HERMES_BASE_PATH__?: string; __HERMES_DASHBOARD_PROFILE__?: string }
+
+const created = (id: string) => ({ info: {}, session_id: `${id}-runtime`, stored_session_id: `${id}-stored` })
+
+function mountActions() {
+ const ref = <T>(current: T) => ({ current })
+ const state = createClientSessionState()
+
+ const requestGateway = vi.fn(
+ async (method: string, _params?: Record<string, unknown>) =>
+ (method === 'session.create' ? created('tab') : {}) as never
+ )
+
+ const result = renderHook(() =>
+ useSessionActions({
+ activeSessionId: null,
+ activeSessionIdRef: ref<string | null>(null),
+ busyRef: ref(false),
+ creatingSessionRef: ref(false),
+ ensureSessionState: () => state,
+ getRouteToken: () => 'route',
+ getRoutedStoredSessionId: () => null,
+ navigate: vi.fn(),
+ requestGateway,
+ resetViewSync: vi.fn(),
+ routedSessionId: null,
+ runtimeIdByStoredSessionIdRef: ref(new Map()),
+ selectedStoredSessionId: null,
+ selectedStoredSessionIdRef: ref<string | null>(null),
+ sessionStateByRuntimeIdRef: ref(new Map()),
+ syncSessionStateToView: vi.fn(),
+ updateSessionState: () => state
+ })
+ )
+
+ return { ...result, requestGateway }
+}
+
+// Settings saves through the bridge for whichever profile the tab is on.
+async function saveFolderOn(profile: string, dir: string) {
+ const booted = $connection.get()
+ setConnection(await window.hermesDesktop.getConnection(profile))
+ await window.hermesDesktop.settings.setDefaultProjectDir(dir)
+ setConnection(booted)
+}
+
+beforeEach(async () => {
+ // A gateway launched as `alpha`, opened at its plain address: the tab boots
+ // on the gateway's own profile with no `?profile=`, as adoptPrimaryProfile
+ // leaves it, and the boot sync fills the window's folder cache.
+ host.__HERMES_BASE_PATH__ = '/hermes'
+ host.__HERMES_DASHBOARD_PROFILE__ = 'alpha'
+ seedWebappSession('served-token')
+ window.history.replaceState(null, '', '/hermes#/')
+ expect(installBrowserDesktopBridge()).toBe(true)
+ setConnection(await window.hermesDesktop.getConnection())
+ $activeGatewayProfile.set('alpha')
+ await window.hermesDesktop.settings.setDefaultProjectDir('/srv/alpha')
+ await syncConfiguredDefaultProjectDir()
+})
+
+afterEach(() => {
+ cleanup()
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ delete host.__HERMES_BASE_PATH__
+ delete host.__HERMES_DASHBOARD_PROFILE__
+ clearWebappSession()
+ document.documentElement.removeAttribute('data-hermes-desktop-host')
+ window.localStorage.clear()
+ window.history.replaceState(null, '', '/')
+ applyConfiguredDefaultProjectDir(null)
+ setActiveSessionId(null)
+ setConnection(null)
+ $sessionTiles.set([])
+ $activeGatewayProfile.set('default')
+ $newChatProfile.set(null)
+ $newChatRoute.set(null)
+ captureNewChatSource(null)
+ vi.clearAllMocks()
+})
+
+describe('browser default folder follows the profile a new session belongs to', () => {
+ it('uses the folder Settings saved on the gateway own profile', () => {
+ const { result } = mountActions()
+
+ act(() => result.current.startFreshSessionDraft())
+
+ expect($currentCwd.get()).toBe('/srv/alpha')
+ })
+
+ it.each([
+ { expected: '/srv/beta', pick: 'beta', saved: '/srv/beta' },
+ { expected: '', pick: 'beta', saved: null },
+ // The booted profile's folder is not the `default` profile's.
+ { expected: '', pick: 'default', saved: null }
+ ])(
+ 'after a rail switch to $pick (folder $saved), a new chat and a new tab start in $expected',
+ async ({ expected, pick, saved }) => {
+ if (saved) {
+ await saveFolderOn(pick, saved)
+ }
+
+ const { result, requestGateway } = mountActions()
+
+ selectProfile(pick)
+ await vi.waitFor(() => expect(new URLSearchParams(window.location.search).get('profile')).toBe(pick))
+ expect($connection.get()?.profile).toBe(pick)
+
+ act(() => result.current.startFreshSessionDraft())
+ expect($currentCwd.get()).toBe(expected)
+
+ await act(() => result.current.openNewSessionTile('center', { listed: false }))
+
+ const params = requestGateway.mock.calls.find(([method]) => method === 'session.create')?.[1]
+ expect(params).toMatchObject({ profile: pick })
+ expect(params?.cwd ?? '').toBe(expected)
+ }
+ )
+
+ it('starts a Bot Mode "+" tab in the bot profile folder, not the active profile one', async () => {
+ await saveFolderOn('writer', '/srv/writer')
+ vi.mocked(requestGatewayForAgent).mockResolvedValue(created('bot'))
+ const { result } = mountActions()
+ // The shape the tab-strip "+" sends in Bot Mode: a route, no profile.
+ const route = { connectionId: 'local', profile: 'writer' }
+
+ await act(() =>
+ result.current.openNewSessionTile('center', {
+ listed: false,
+ route,
+ workspaceScope: { ownerRoute: route, workspaceMode: 'bots', workspaceOwnerKey: 'bot:local::writer' }
+ })
+ )
+
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'local',
+ 'writer',
+ 'session.create',
+ expect.objectContaining({ cwd: '/srv/writer', profile: 'writer' }),
+ ...FOREGROUND_CREATE_DIAL
+ )
+ })
+})
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 cad56caf91f..291480e83ba 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
@@ -23,7 +23,6 @@ import { useI18n } from '@/i18n'
import {
type ChatMessage,
preserveLocalAssistantErrors,
- QUESTION_CARD_TOOLS,
restorePendingClarifyToolCall,
settlePendingClarifyToolCall,
stripPendingClarifyProjectionForCache,
@@ -163,7 +162,11 @@ import { reconcilePersistedLiveTurn } from './persisted-live-turn'
import { provisionalTranscriptPaint, transcriptRestScope } from './provisional-transcript'
import { rememberedOwnerForResume } from './remembered-owner'
import { restorePendingApproval } from './restore-pending-approval'
-import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'
+import {
+ pendingClarifyToolPayload,
+ restorePendingClarifyFromSnapshot,
+ withoutEarlyClarifyProjection
+} from './restore-pending-clarify'
import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'
import {
ambientResumeConnectionId,
@@ -172,7 +175,7 @@ import {
rememberResolvedResumeOwner,
resolveResumeOwner
} from './resume-owner'
-import { backgroundRuntimeOptions, runtimeOwner } from './runtime-owner'
+import { backgroundRuntimeOptions, runtimeOwner, runtimeOwnerProfile } from './runtime-owner'
import { createGatewaySession, desktopSessionCreateParams } from './session-create-request'
import {
createPersistedDisplayTranscriptProvenance,
@@ -301,39 +304,6 @@ interface FreshSessionDraftOptions {
workspaceTarget?: NewChatWorkspaceTarget
}
-/** Drop the pre-hydration request-id row without copying the other messages.
- * A copied clarify row looks like a concurrent edit and hydration keeps both. */
-function withoutEarlyClarifyProjection(messages: ChatMessage[], requestId: string): ChatMessage[] {
- let changed = false
- const next: ChatMessage[] = []
-
- for (const message of messages) {
- const parts = message.parts.filter(
- part =>
- !(
- part.type === 'tool-call' &&
- QUESTION_CARD_TOOLS.has(part.toolName) &&
- part.result === undefined &&
- part.toolCallId === requestId
- )
- )
-
- if (parts.length === message.parts.length) {
- next.push(message)
-
- continue
- }
-
- changed = true
-
- if (parts.length > 0) {
- next.push({ ...message, parts })
- }
- }
-
- return changed ? next : messages
-}
-
/** Session-state patch for a restored blocking prompt row; the first non-null projection is used. */
function livePromptStreamId(
...projections: ({ streamId: string } | null)[]
@@ -1004,8 +974,12 @@ export function useSessionActions({
const listed = options?.listed ?? true
try {
- // Project-path tiles take the tree's profile (#79005 / #124265). A stale
- // $newChatProfile pin must not win for the occupied-chat "+" or a project drag.
+ // A tile anchored at a project path belongs to the profile the project
+ // tree is rendered under — the same owner the fresh-draft "+" pins
+ // (#79005). The occupied-chat "+" and project-row drags reach this
+ // path instead, where a stale $newChatProfile pin would otherwise win
+ // and land the session in the wrong profile (#124265). All-profiles
+ // view has no owner and keeps the ordinary fallback.
const projectOwnerProfile =
options?.profile === undefined && typeof options?.cwd === 'string'
? (projectProfile() ?? undefined)
@@ -1060,12 +1034,15 @@ export function useSessionActions({
...(legacyOwnerProfile ? { ownerProfile: legacyOwnerProfile } : {})
}
+ // The default folder belongs to the profile the session is created in.
+ // A dialled route names it: the Bot Mode "+" aims at the bot's profile
+ // while requestedProfile still holds the window's.
const cwd =
options?.cwd === null
? ''
: typeof options?.cwd === 'string'
? options.cwd.trim()
- : resolveNewSessionCwd(requestedProfile)
+ : resolveNewSessionCwd(runtimeOwnerProfile(capturedRoute, requestedProfile))
// #52589 provenance for the tile path: an explicitly-passed cwd is a
// deliberate workspace pick; a resolved default is inherited.
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts
index feac3b91428..9e98fd7cc52 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts
@@ -1,4 +1,4 @@
-import { type GatewayEventPayload, QUESTION_CARD_TOOLS } from '@/lib/chat-messages'
+import { type ChatMessage, type GatewayEventPayload, QUESTION_CARD_TOOLS } from '@/lib/chat-messages'
import { $clarifyRequests, type ClarifyRequest, clearClarifyRequest } from '@/store/clarify'
import type { SessionResumeResult } from '@/types/hermes'
@@ -64,3 +64,36 @@ export function pendingClarifyToolPayload(request: ClarifyRequest): GatewayEvent
tool_id: request.requestId
}
}
+
+/** Drop the pre-hydration request-id row without copying the other messages.
+ * A copied clarify row looks like a concurrent edit and hydration keeps both. */
+export function withoutEarlyClarifyProjection(messages: ChatMessage[], requestId: string): ChatMessage[] {
+ let changed = false
+ const next: ChatMessage[] = []
+
+ for (const message of messages) {
+ const parts = message.parts.filter(
+ part =>
+ !(
+ part.type === 'tool-call' &&
+ QUESTION_CARD_TOOLS.has(part.toolName) &&
+ part.result === undefined &&
+ part.toolCallId === requestId
+ )
+ )
+
+ if (parts.length === message.parts.length) {
+ next.push(message)
+
+ continue
+ }
+
+ changed = true
+
+ if (parts.length > 0) {
+ next.push({ ...message, parts })
+ }
+ }
+
+ return changed ? next : messages
+}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts
index d9482892418..5c0056206bb 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts
@@ -60,3 +60,9 @@ export function runtimeOwner(
): SessionOwnerScope {
return route ?? profile
}
+
+/** The profile a create's runtime lives in: the dialled route's backend
+ * profile, else the requested one. */
+export function runtimeOwnerProfile(route: null | SessionOwnerRoute | undefined, profile: string): string {
+ return route ? route.targetProfile || route.profile : profile
+}
diff --git a/apps/desktop/src/lib/browser-profile-prefs.test.ts b/apps/desktop/src/lib/browser-profile-prefs.test.ts
index de175a3833a..4903f03c477 100644
--- a/apps/desktop/src/lib/browser-profile-prefs.test.ts
+++ b/apps/desktop/src/lib/browser-profile-prefs.test.ts
@@ -126,16 +126,31 @@ describe('browser profile prefs follow rename and delete', () => {
expect(resolveNewSessionCwd('alpha')).toBe('')
})
- it('keeps a folder the destination profile already chose', () => {
- host()
- putFolder('alpha', '/srv/alpha')
- putFolder('renamed', '/srv/kept')
-
- migrateTilesForProfile('alpha', 'renamed')
-
- expect(localStorage.getItem(browserDefaultProjectDirKey('/hermes', 'renamed'))).toBe('/srv/kept')
- expect(localStorage.getItem(browserDefaultProjectDirKey('/hermes', 'alpha'))).toBeNull()
- })
+ // A rename never lands on a live profile, so prefs already under the new name
+ // were left by a deleted profile (a delete before this fix kept them).
+ it.each([
+ { expected: '/srv/research', research: '/srv/research' },
+ { expected: '', research: null }
+ ])(
+ 'gives the renamed profile its own folder ($research), not what a deleted profile left',
+ ({ expected, research }) => {
+ host()
+ putFolder('work', '/srv/deleted-work')
+ putStartup('work', '/hermes', 'local')
+ $defaultProfileRoute.set({ connectionId: 'local', profile: 'work' })
+
+ if (research) {
+ putFolder('research', research)
+ }
+
+ migrateTilesForProfile('research', 'work')
+
+ expect(resolveNewSessionCwd('work')).toBe(expected)
+ expect(localStorage.getItem(browserDefaultProjectDirKey('/hermes', 'research'))).toBeNull()
+ expect(localStorage.getItem(browserStartupProfileKey('/hermes'))).toBeNull()
+ expect($defaultProfileRoute.get()).toBeNull()
+ }
+ )
it('drops a blank folder instead of carrying it to the new name', () => {
host()
diff --git a/apps/desktop/src/lib/browser-profile-prefs.ts b/apps/desktop/src/lib/browser-profile-prefs.ts
index 084ce879911..2d6325dbd02 100644
--- a/apps/desktop/src/lib/browser-profile-prefs.ts
+++ b/apps/desktop/src/lib/browser-profile-prefs.ts
@@ -25,6 +25,10 @@ export function migrateBrowserProfilePrefs(from: string, to: string): void {
return
}
+ // A rename never lands on a live profile's name, so a folder or startup
+ // profile already stored under the new name was left by a deleted profile.
+ // The renamed profile's own prefs, or their absence, replace it.
+ dropBrowserProfilePrefs(toName)
migrateBrowserFolderPref(basePath, fromName, toName)
const movedStartup = migrateBrowserStartupProfile(basePath, fromName, toName)
diff --git a/apps/desktop/src/lib/browser-settings.ts b/apps/desktop/src/lib/browser-settings.ts
index af862ebfc7d..baa04932c8e 100644
--- a/apps/desktop/src/lib/browser-settings.ts
+++ b/apps/desktop/src/lib/browser-settings.ts
@@ -1,6 +1,6 @@
import { normalizeBasePath } from '@hermes/shared'
-import type { BrowserHostGlobals } from './platform'
+import { type BrowserHostGlobals, browserLaunchProfile } from './platform'
import { readKey, writeKey } from './storage'
interface BrowserSettingsOptions {
@@ -13,8 +13,12 @@ export function browserPageBasePath(): string {
return normalizeBasePath((window as Window & BrowserHostGlobals).__HERMES_BASE_PATH__)
}
+/** A profile not named is the one the serving gateway runs as, the profile its
+ * REST answers for when a request names none. */
export function browserDefaultProjectDirKey(basePath: string, profile: string): string {
- return `hermes:browser:default-project-dir:${JSON.stringify([basePath || '/', profile.trim() || 'default'])}`
+ const owner = profile.trim() || browserLaunchProfile() || 'default'
+
+ return `hermes:browser:default-project-dir:${JSON.stringify([basePath || '/', owner])}`
}
/** The profile's own default folder, or '' when it never chose one. */
@@ -22,8 +26,7 @@ export function readBrowserDefaultProjectDir(basePath: string, profile: string):
return readKey(browserDefaultProjectDirKey(basePath, profile))?.trim() || ''
}
-/** Rename keeps the folder with the profile. A destination that already chose
- * one keeps it; the old key is dropped either way so the name can be reused. */
+/** Rename moves the folder with the profile, or the lack of one. */
export function migrateBrowserFolderPref(basePath: string, from: string, to: string): void {
const sourceKey = browserDefaultProjectDirKey(basePath, from)
const destKey = browserDefaultProjectDirKey(basePath, to)
@@ -32,18 +35,7 @@ export function migrateBrowserFolderPref(basePath: string, from: string, to: str
return
}
- const source = readKey(sourceKey)
-
- if (source === null) {
- return
- }
-
- const next = source.trim()
-
- if (next && readKey(destKey) === null) {
- writeKey(destKey, next)
- }
-
+ writeKey(destKey, readKey(sourceKey)?.trim() || null)
writeKey(sourceKey, null)
}
@@ -64,7 +56,7 @@ export function createBrowserSettings({
basePath,
currentProfile
}: BrowserSettingsOptions): Window['hermesDesktop']['settings'] {
- const key = () => browserDefaultProjectDirKey(basePath, currentProfile()?.trim() || 'default')
+ const key = () => browserDefaultProjectDirKey(basePath, currentProfile() ?? '')
return {
getDefaultProjectDir: async () => ({
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.ts
index 0a1fd46096c..f8015d7e10b 100644
--- a/apps/desktop/src/store/session-states.test.ts
+++ b/apps/desktop/src/store/session-states.test.ts
@@ -46,7 +46,6 @@ import {
markSelectionRestore,
nextSessionTileForWorkspace,
openSessionTile,
- orderTilesByTree,
patchSessionTile,
recordSessionEventScope,
rekeySessionTile,
@@ -60,6 +59,7 @@ import {
setSessionTileDelegate,
setSessionTileWorkspaceScope
} from '@/store/session-states'
+import { orderTilesByTree } from '@/store/session-tile-order'
const tile = (storedSessionId: string): SessionTile => ({ storedSessionId })
const tilePane = (id: string) => `session-tile:${id}`
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index ae8d5a908a7..89f749ffa8f 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -22,7 +22,7 @@ import { atom, computed } from 'nanostores'
import { setSessionOwnerResolver } from '@/api/client'
import { routeSessionId } from '@/app/routes'
import type { ClientSessionState } from '@/app/types'
-import { findGroupOfPane, type LayoutNode } from '@/components/pane-shell/tree/model'
+import { findGroupOfPane } from '@/components/pane-shell/tree/model'
import {
$layoutTree,
focusedSessionTabAnchor,
@@ -94,6 +94,7 @@ import {
type SessionOwnerScope,
type SessionProfileRoute
} from './session-request-router'
+import { orderTilesByTree } from './session-tile-order'
import { ackStoredSessionId, isMessagingCompletion, markSessionUnreadFinished } from './session-unread'
import { migrateTranscriptTailsForProfile } from './transcript-tail-cache'
import { isBrowserWindow, isSecondaryWindow } from './windows'
@@ -2248,48 +2249,6 @@ export function sessionTileDelegate(): SessionTileDelegate | null {
return delegate
}
-/** Reorder tiles to match layout-tree encounter order (stored ids in the order
- * their `session-tile:` panes are walked). Restore replays the array through
- * sequential adoption (each center tile APPENDS after the ones before it), so
- * array order IS strip order — no `before` stamping needed; a stale `before`
- * naming an absent pane falls back to append anyway (see insertAtGroup). Tiles
- * not yet adopted sort after placed ones, stably. Returns `null` when nothing
- * moves so callers can skip a needless persist. */
-export function orderTilesByTree<T extends { storedSessionId: string }>(
- tree: LayoutNode | null,
- tiles: readonly T[]
-): null | T[] {
- if (!tree || tiles.length < 2) {
- return null
- }
-
- const order: string[] = []
-
- const walk = (node: LayoutNode) => {
- if (node.type === 'group') {
- for (const id of node.panes) {
- if (id.startsWith(TILE_PANE_PREFIX)) {
- order.push(id.slice(TILE_PANE_PREFIX.length))
- }
- }
-
- return
- }
-
- node.children.forEach(walk)
- }
-
- walk(tree)
-
- const rank = new Map(order.map((id, i) => [id, i]))
-
- const next = [...tiles].sort(
- (a, b) => (rank.get(a.storedSessionId) ?? Infinity) - (rank.get(b.storedSessionId) ?? Infinity)
- )
-
- return next.some((t, i) => t !== tiles[i]) ? next : null
-}
-
function syncTileStripOrder() {
const next = orderTilesByTree($layoutTree.get(), $sessionTiles.get())
@@ -2833,6 +2792,8 @@ export function dropTilesForProfile(
}
persistTiles()
+ // The rail is a profile-keyed family too: a deleted profile's tabs must not
+ // outlive it, or a later profile of the same name inherits them.
dropPreviewTabsForProfile(name)
dropBrowserProfilePrefs(name)
}
@@ -2898,6 +2859,8 @@ export function migrateTilesForProfile(oldProfile: string, newProfile: string):
migrateSessionOwnerHintsForProfile(from, to)
migratePreviewArtifactsForProfile(from, to)
migrateStatusDrawersForProfile(from, to)
+ // Sibling family: the rail's profile-keyed buckets move with the rename, or
+ // the renamed profile opens with an empty rail and the old name keeps them.
migratePreviewTabsForProfile(from, to)
migrateBrowserProfilePrefs(from, to)
}
diff --git a/apps/desktop/src/store/session-tile-order.ts b/apps/desktop/src/store/session-tile-order.ts
new file mode 100644
index 00000000000..1eeb70beaf6
--- /dev/null
+++ b/apps/desktop/src/store/session-tile-order.ts
@@ -0,0 +1,45 @@
+import type { LayoutNode } from '@/components/pane-shell/tree/model'
+
+import { TILE_PANE_PREFIX } from './session-focus'
+
+/** Reorder tiles to match layout-tree encounter order (stored ids in the order
+ * their `session-tile:` panes are walked). Restore replays the array through
+ * sequential adoption (each center tile APPENDS after the ones before it), so
+ * array order IS strip order — no `before` stamping needed; a stale `before`
+ * naming an absent pane falls back to append anyway (see insertAtGroup). Tiles
+ * not yet adopted sort after placed ones, stably. Returns `null` when nothing
+ * moves so callers can skip a needless persist. */
+export function orderTilesByTree<T extends { storedSessionId: string }>(
+ tree: LayoutNode | null,
+ tiles: readonly T[]
+): null | T[] {
+ if (!tree || tiles.length < 2) {
+ return null
+ }
+
+ const order: string[] = []
+
+ const walk = (node: LayoutNode) => {
+ if (node.type === 'group') {
+ for (const id of node.panes) {
+ if (id.startsWith(TILE_PANE_PREFIX)) {
+ order.push(id.slice(TILE_PANE_PREFIX.length))
+ }
+ }
+
+ return
+ }
+
+ node.children.forEach(walk)
+ }
+
+ walk(tree)
+
+ const rank = new Map(order.map((id, i) => [id, i]))
+
+ const next = [...tiles].sort(
+ (a, b) => (rank.get(a.storedSessionId) ?? Infinity) - (rank.get(b.storedSessionId) ?? Infinity)
+ )
+
+ return next.some((t, i) => t !== tiles[i]) ? next : null
+}
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index b23672914f7..ef592992c1a 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -1869,9 +1869,9 @@ export const workspaceCwdForNewSession = (profile?: string): string => {
// remote-keyed and intentionally sticky).
//
// A browser host stores that default folder per profile. The process cache
- // was last filled for whichever profile the window synced, so a chat aimed
- // at another profile reads that profile's key and stays detached when it
- // never chose one.
+ // holds the folder of the profile the window last synced (boot, a connection
+ // apply, Settings), and a rail switch does not refill it, so a browser new
+ // chat reads its own profile's key and stays detached when it never chose one.
const owner = profile?.trim()
if (owner && isBrowserHostedDesktop()) {