The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep review-flagged owner rules in the gateway-switch fixes
unsupportedpastels2b5abdfafedc
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.tsxindex 24ed0ff2e76..57a48014d15 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@@ -1940,7 +1940,7 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>// recorded route — same contract as the sleep/wake reconnect: neither the// active profile nor main's foreground route may retarget the primary.const lastCall = desktop.getConnection.mock.calls.at(-1) ?? []- expect(lastCall[0] ?? 'default').toBe('default')+ expect(lastCall[0]).toBe('default')expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(3)expect(oldPrimary.readyState).toBe(FakeWebSocket.CLOSED)expect(backgroundSocket.readyState).toBe(FakeWebSocket.OPEN)@@ -2176,7 +2176,8 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>const reconnectCalls = desktop.getConnection.mock.calls.slice(callsBeforeDrop)expect(reconnectCalls.some(args => (args[0] ?? '').trim() === 'coder')).toBe(false)- expect(reconnectCalls.some(args => (args[0] ?? 'default') === 'default')).toBe(true)+ expect(reconnectCalls.every(args => args[0] === 'default')).toBe(true)+ expect(reconnectCalls.length).toBeGreaterThan(0)const primaryReconnectSockets = FakeWebSocket.instances.slice(socketsBeforeDrop)@@ -2749,6 +2750,64 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>expect(FakeWebSocket.instances.length).toBeGreaterThan(socketCountBefore)expect($gatewayState.get()).toBe('open')})++ it.each([false, true])(+ 'primary reconnect preserves its source while a secondary is foregrounded (registry=%s)',+ async registryScoped => {+ const primary = { ...remotePrimaryConn, registryScoped }+ const secondary = { ...coderConn, profile: 'default', registryScoped: true }+ let foreground: { connectionId: string | null; profile: string; registryScoped: boolean } | null = null++ const desktop = {+ ...fakeDesktop(),+ setActiveConnectionRoute: vi.fn(route => {+ foreground = route+ }),+ // Main's rule (electron/desktop-profile resolveDesktopConnectionRequest):+ // a profile-less request follows the sender's foreground route, an+ // explicit profile keeps the legacy route.+ getConnection: vi.fn(async (profile?: null | string) =>+ !profile?.trim() && foreground?.registryScoped && foreground.connectionId === secondary.connectionId+ ? secondary+ : primary+ ),+ getConnectionFor: vi.fn(async ({ connectionId }: { connectionId: string; profile: string }) =>+ connectionId === secondary.connectionId ? secondary : primary+ ),+ getGatewayWsUrlFor: vi.fn(async ({ connectionId }: { connectionId: string; profile: string }) =>+ connectionId === secondary.connectionId ? secondary.wsUrl : primary.wsUrl+ )+ }++ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop+ render(<Harness />)+ await flushAsync()+ const primarySocket = FakeWebSocket.instances[0]+ expect(primarySocket.url).toBe(primary.wsUrl)+ let opening!: Promise<boolean>+ act(() => {+ opening = ensureGatewayForAgent(secondary.connectionId, secondary.profile)+ })+ await flushAsync()+ await opening+ expect(foreground).toMatchObject({ connectionId: secondary.connectionId, registryScoped: true })+ expect(isActivePrimary()).toBe(false)+ act(() => primarySocket.drop())+ await advanceBackoff()+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(primary.wsUrl)+ expect($connection.get()?.connectionId).toBe(secondary.connectionId)+ expect(isActivePrimary()).toBe(false)++ // Explicit connection apply must still follow main's rewritten foreground+ // route, and replace the reconnect target rather than pinning it forever.+ act(() => connectionApplied?.())+ await flushAsync()+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(secondary.wsUrl)+ act(() => FakeWebSocket.instances.at(-1)!.drop())+ await advanceBackoff()+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(secondary.wsUrl)+ }+ )})describe('window-state IPC before the first connection publishes (#108641)', () => {@@ -2787,61 +2846,3 @@ describe('window-state IPC before the first connection publishes (#108641)', ()expect($connection.get()?.windowButtonPosition).toBeNull()})})--it.each([false, true])(- 'primary reconnect preserves its source while a secondary is foregrounded (registry=%s)',- async registryScoped => {- // Keep Electron's Node-only dependency graph outside the renderer TS project.- const resolverModule = '../../../../electron/desktop-profile'- const { resolveDesktopConnectionRequest } = await import(resolverModule)- const primary = { ...remotePrimaryConn, registryScoped }- const secondary = { ...coderConn, profile: 'default', registryScoped: true }- let foreground: { connectionId: string | null; profile: string; registryScoped: boolean } | null = null-- const desktop = {- ...fakeDesktop(),- setActiveConnectionRoute: vi.fn(route => {- foreground = route- }),- getConnection: vi.fn(async (profile?: null | string) => {- const route = resolveDesktopConnectionRequest(profile, foreground, 'default')-- return route.connectionId === secondary.connectionId ? secondary : primary- }),- getConnectionFor: vi.fn(async ({ connectionId }: { connectionId: string; profile: string }) =>- connectionId === secondary.connectionId ? secondary : primary- ),- getGatewayWsUrlFor: vi.fn(async ({ connectionId }: { connectionId: string; profile: string }) =>- connectionId === secondary.connectionId ? secondary.wsUrl : primary.wsUrl- )- }-- ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop- render(<Harness />)- await flushAsync()- const primarySocket = FakeWebSocket.instances[0]- expect(primarySocket.url).toBe(primary.wsUrl)- let opening!: Promise<boolean>- act(() => {- opening = ensureGatewayForAgent(secondary.connectionId, secondary.profile)- })- await flushAsync()- await opening- expect(foreground).toMatchObject({ connectionId: secondary.connectionId, registryScoped: true })- expect(isActivePrimary()).toBe(false)- act(() => primarySocket.drop())- await advanceBackoff()- expect(FakeWebSocket.instances.at(-1)?.url).toBe(primary.wsUrl)- expect($connection.get()?.connectionId).toBe(secondary.connectionId)- expect(isActivePrimary()).toBe(false)-- // Explicit connection apply must still follow main's rewritten foreground- // route, and replace the reconnect target rather than pinning it forever.- act(() => connectionApplied?.())- await flushAsync()- expect(FakeWebSocket.instances.at(-1)?.url).toBe(secondary.wsUrl)- act(() => FakeWebSocket.instances.at(-1)!.drop())- await advanceBackoff()- expect(FakeWebSocket.instances.at(-1)?.url).toBe(secondary.wsUrl)- }-)diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.tsindex f2dc308b8b5..37324b326ca 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts@@ -318,42 +318,39 @@ describe('useGatewayRequest', () => {expect(gateway.connect).toHaveBeenLastCalledWith(expect.stringContaining('ticket=fresh-2'))})- it.each(['default', 'research'])(- 'does not replay a delayed local failure onto another source (%s)',- async profile => {- installRemoteDesktop()- const primary = makePrimaryGateway()- const failure = new Error('connection closed')- let rejectRequest!: (error: Error) => void- primary.request.mockImplementationOnce(- () =>- new Promise((_resolve, reject) => {- rejectRequest = reject- })- )- setPrimaryGateway(primary as unknown as HermesGateway, 'default')- $gateway.set(primary as unknown as HermesGateway)- $gatewayState.set('open')- const { result } = renderHook(() => useGatewayRequest())+ it('does not replay a delayed local failure onto a same-named profile on another source', async () => {+ installRemoteDesktop()+ const primary = makePrimaryGateway()+ const failure = new Error('connection closed')+ let rejectRequest!: (error: Error) => void+ primary.request.mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectRequest = reject+ })+ )+ setPrimaryGateway(primary as unknown as HermesGateway, 'default')+ $gateway.set(primary as unknown as HermesGateway)+ $gatewayState.set('open')+ const { result } = renderHook(() => useGatewayRequest())- const pending = result.current- .requestGateway('prompt.submit', { session_id: 'local-only', text: 'private' })- .catch(error => error)+ const pending = result.current+ .requestGateway('prompt.submit', { session_id: 'local-only', text: 'private' })+ .catch(error => error)- await act(async () => {- await ensureGatewayForAgent('home', profile)- })- const destination = $gateway.get() as unknown as TestGateway- destination.request.mockResolvedValue({ sent: true })- await act(async () => {- rejectRequest(failure)- })+ await act(async () => {+ await ensureGatewayForAgent('home', 'default')+ })+ const destination = $gateway.get() as unknown as TestGateway+ destination.request.mockResolvedValue({ sent: true })+ await act(async () => {+ rejectRequest(failure)+ })- expect(await pending).toBe(failure)- expect(primary.request).toHaveBeenCalledTimes(1)- expect(destination.request).not.toHaveBeenCalled()- }- )+ expect(await pending).toBe(failure)+ expect(primary.request).toHaveBeenCalledTimes(1)+ expect(destination.request).not.toHaveBeenCalled()+ })it('does not replay when the source changes while recovery is pending', async () => {const desktop = installRemoteDesktop()diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.tsindex c7442aaf249..f462e490c4a 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts@@ -158,7 +158,7 @@ export function useGatewayRequest() {try {return await gateway.request<T>(method, params, timeoutMs, signal)} catch (error) {- if (!isGatewayTransportError(error) || !isDispatchRouteActive()) {+ if (!isGatewayTransportError(error)) {throw error}@@ -168,6 +168,9 @@ export function useGatewayRequest() {// sources.const recovered = isActivePrimary() ? await ensureGatewayOpen() : await ensureActiveGatewayOpen()+ // Recovery follows the CURRENT route (ensureGatewayOpen resolves+ // profile-less through main's foreground route, unlike the boot hook's+ // own-route reconnect), so replay only on the socket that was dispatched.if (!isDispatchRouteActive() || (recovered && recovered !== gateway)) {throw error}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/ambient-local-owner.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions/ambient-local-owner.test.tsxindex 783d292c5db..42cfc371ee8 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/ambient-local-owner.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions/ambient-local-owner.test.tsx@@ -163,6 +163,28 @@ describe('untagged resume ambient owner', () => {})+ it('does not remember the foreground source for a session it could not resolve', async () => {+ const primary = { connectionState: 'open', request: vi.fn(async (method: string) => rpcResult(method)) }+ gateways.setPrimaryGateway(primary as never, 'default')+ gateways.setPrimaryGatewayConnection(descriptor('home'))+ setConnection(descriptor('home'))+ await gateways.ensureGatewayForAgent('local', 'default')+ expect(gateways.isActivePrimary()).toBe(false)+ // No listed row and no reachable detail endpoint: the owner is unknown.+ setSessions([])+ let resume!: Resume+ render(+ <Harness+ onReady={ready => {+ resume = ready+ }}+ />+ )+ await act(() => resume('stored', true))++ expect(getSessionOwnerHint('stored')).toBeUndefined()+ })+it.each([false, true])('preserves the profile-only door on a local primary (registryScoped=%s)',async registryScoped => {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.tsindex d22d45e7b41..c69468271ac 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@@ -1501,7 +1501,16 @@ export function useSessionActions({// Preserve this resolved source for later prompt/approval RPCs too;// otherwise an untagged row falls back to its bare profile after resume.- if (!ownerRoute && !storedForProfile?.connection_id && sessionOwner && typeof sessionOwner === 'object') {+ // Only for a row the ambient source actually returned: an id that did not+ // resolve (deep link, routed restore) proves nothing about its owner, and+ // a persisted hint would pin it to whichever source was in front.+ if (+ !ownerRoute &&+ storedForProfile &&+ !storedForProfile.connection_id &&+ sessionOwner &&+ typeof sessionOwner === 'object'+ ) {setSessionOwnerHint(storedSessionId, sessionOwner)}diff --git a/apps/desktop/src/store/connections-new-chat-route.test.ts b/apps/desktop/src/store/connections-new-chat-route.test.tsindex a4ee7529daf..abfa74e3bca 100644--- a/apps/desktop/src/store/connections-new-chat-route.test.ts+++ b/apps/desktop/src/store/connections-new-chat-route.test.ts@@ -123,6 +123,16 @@ it('re-homes a fresh draft when leaving All profiles on the already active sourcexpect(resolveNewChatOwnerRoute()).toEqual({ connectionId: 'homelab', profile: 'default' })})+it('keeps a draft the user pinned while the silent boot restore was in flight', async () => {+ // No active source yet: selectConnection runs as the boot-time restore.+ setConnection(null)+ expect($activeConnectionId.get()).toBeNull()+ const route = $newChatRoute.get()+ await selectConnection('local')+ expect($newChatRoute.get()).toEqual(route)+ expect(resolveNewChatOwnerRoute()).toEqual(route)+})+it('preserves the explicit draft when the target dial fails', async () => {const route = $newChatRoute.get()getConnectionFor.mockRejectedValueOnce(new Error('offline'))diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 16709796416..41a8c3708ab 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -132,6 +132,22 @@ export function _resetConnectionsForTests(): void {$pendingConnectionId.set(null)}+// A connection switch is a new-chat intent on THAT source: keep the registry+// identity with the profile so the next create names local::x / <source>::x+// exactly, never a bare profile string. An older explicit agent route must not+// override the selected source. The silent boot restore is not a user choice,+// so it keeps a route the user pinned (gateway-group +) while it was in flight.+function rehomeNewChatDraft(profile: string, keepExplicitRoute = false): void {+ $newChatProfile.set(profile)++ if (!keepExplicitRoute) {+ $newChatRoute.set(null)+ }++ captureNewChatSource()+ requestFreshSession()+}+export function setConnectionsRegistry(registry: DesktopConnectionsRegistry): void {$connectionsRegistry.set(registry)}@@ -402,14 +418,7 @@ export async function selectConnection(connectionId: string, options: SelectConnif (pendingTarget === null && currentConnectionId === connectionId && currentProfile === targetProfile) {$showAllProfiles.set(false)- $newChatProfile.set(targetProfile)- // A connection switch is a new-chat intent on THAT source: keep the- // registry identity with the profile so the next create names local::x /- // <source>::x exactly, never a bare profile string.- // An older explicit agent route must not override the selected source.- $newChatRoute.set(null)- captureNewChatSource()- requestFreshSession()+ rehomeNewChatDraft(targetProfile)await rememberConnection(connectionId)return@@ -545,11 +554,7 @@ export async function selectConnection(connectionId: string, options: SelectConn$showAllProfiles.set(false)}- $newChatProfile.set(targetProfile)- // An older explicit agent route must not override the selected source.- $newChatRoute.set(null)- captureNewChatSource()- requestFreshSession()+ rehomeNewChatDraft(targetProfile, restoreOnBoot)await refreshActiveProfile()}} catch (error) {diff --git a/apps/desktop/src/store/projects-connection-tag.test.ts b/apps/desktop/src/store/projects-connection-tag.test.tsindex 27262012ff3..e5f80a54c64 100644--- a/apps/desktop/src/store/projects-connection-tag.test.ts+++ b/apps/desktop/src/store/projects-connection-tag.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import type { SidebarProjectTree } from '@/app/chat/sidebar/projects/workspace-groups'import { hermesApi } from '@/hermes'-import { $gateway, activeGateway, activeGatewayConnectionId } from '@/store/gateway'+import { $gateway, activeGateway, activeGatewayConnectionId, isActivePrimary } from '@/store/gateway'import { $activeGatewayProfile, setShowAllProfiles } from '@/store/profile'import { $sessions } from '@/store/session'import { sessionOwnerRouteFromRow } from '@/store/session-request-router'@@ -15,6 +15,7 @@ vi.mock('@/store/gateway', () => ({$gateway: atom(null),activeGateway: vi.fn(),activeGatewayConnectionId: vi.fn(),+ isActivePrimary: vi.fn(),ensureActiveGatewayOpen: vi.fn()}))vi.mock('@/i18n', () => ({ translateNow: (key: string) => key }))@@ -48,8 +49,10 @@ function treeProject(): SidebarProjectTree {}}-function selectConnection(connectionId: string | null) {+// Default topology: Home is the window primary, so `local` is a secondary.+function selectConnection(connectionId: string | null, primary = connectionId !== 'local') {vi.mocked(activeGatewayConnectionId).mockReturnValue(connectionId)+ vi.mocked(isActivePrimary).mockReturnValue(primary)}function rows(project: SidebarProjectTree) {@@ -146,6 +149,38 @@ describe('project session connection provenance', () => {}})+ it('leaves This device rows bare on the primary path (legacy profile door)', async () => {+ const project = treeProject()+ connect(vi.fn().mockResolvedValue({ projects: [project], project, scoped_session_ids: [] }))+ selectConnection('local', true)++ await refreshProjectTree()+ const hydrated = await fetchProjectSessions(project.id)++ for (const row of [...rows($projectTree.get()[0]), ...rows(hydrated!)]) {+ expect(row).not.toHaveProperty('connection_id')+ expect(sessionOwnerRouteFromRow(row)).toBeUndefined()+ }+ })++ it.each(['home', 'local'])('never re-owns a row that already names its connection (%s active)', async active => {+ const project = treeProject()++ for (const row of rows(project)) {+ row.connection_id = 'elsewhere'+ }++ vi.mocked(hermesApi).mockResolvedValue({ projects: [project], scoped_session_ids: [] })+ selectConnection(active)+ setShowAllProfiles(true)++ await refreshProjectTree()++ for (const row of rows($projectTree.get()[0])) {+ expect(sessionOwnerRouteFromRow(row)).toEqual({ connectionId: 'elsewhere', profile: 'default' })+ }+ })+it('leaves legacy rows untagged when no registry identity exists', async () => {const project = treeProject()connect(vi.fn().mockResolvedValue({ projects: [project], project, scoped_session_ids: [] }))diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.tsindex fa7f45cc18f..9f720ea8873 100644--- a/apps/desktop/src/store/projects.test.ts+++ b/apps/desktop/src/store/projects.test.ts@@ -59,6 +59,7 @@ vi.mock('@/store/gateway', () => ({$gateway: atom(null),activeGateway: vi.fn(),activeGatewayConnectionId: vi.fn(() => null),+ isActivePrimary: vi.fn(() => true),ensureActiveGatewayOpen: vi.fn()}))diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex 473ebd6581e..3d9a5cd3964 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -16,8 +16,15 @@ import { desktopDefaultCwd, isDesktopFsRemoteMode, selectDesktopPaths, writeDeskimport { desktopGit } from '@/lib/desktop-git'import { isMissingRestEndpoint, isMissingRpcMethod } from '@/lib/gateway-rpc'import { isUnderPath } from '@/lib/path-compare'+import { stampRowsWithOwningConnection } from '@/lib/session-owner-stamp'import { revealFile } from '@/store/file-actions'-import { $gateway, activeGateway, activeGatewayConnectionId, ensureActiveGatewayOpen } from '@/store/gateway'+import {+ $gateway,+ activeGateway,+ activeGatewayConnectionId,+ ensureActiveGatewayOpen,+ isActivePrimary+} from '@/store/gateway'import { $sidebarShowAllSessions, setSidebarAgentsGrouped } from '@/store/layout'import { notify } from '@/store/notifications'import {@@ -339,19 +346,31 @@ function isRetryableProjectTreeReadError(error: unknown): boolean {return message.includes('request timed out') || message.includes('gateway connection closed')}-interface ActiveProjectsContext {+interface ProjectRowOwner {connectionId: null | string+ // `local` served as an active registry SECONDARY: its bare rows would+ // resolve to the window primary, so they need the owner tag.+ stampLocal: boolean+}++interface ActiveProjectsContext extends ProjectRowOwner {gateway: HermesGatewayprofile: string}+function projectRowOwner(): ProjectRowOwner {+ const connectionId = activeGatewayConnectionId()++ return { connectionId, stampLocal: connectionId === 'local' && !isActivePrimary() }+}+function stillOnProjectsContext(context: ActiveProjectsContext): boolean {return stillOnWritableProjectOwner(context) && projectProfile() === context.profile}// Writes follow the selected gateway/profile even if the sidebar is showing// All profiles. That filter changes the view, not the destination.-function stillOnWritableProjectOwner(context: ActiveProjectsContext): boolean {+function stillOnWritableProjectOwner(context: Omit<ActiveProjectsContext, 'stampLocal'>): boolean {return (activeGateway() === context.gateway &&normalizeProfileKey($activeGatewayProfile.get()) === context.profile &&@@ -360,7 +379,7 @@ function stillOnWritableProjectOwner(context: ActiveProjectsContext): boolean {}async function activeProjectsContext(profile = projectProfile()): Promise<ActiveProjectsContext> {- const connectionId = activeGatewayConnectionId()+ const { connectionId, stampLocal } = projectRowOwner()if (!profile || profile === ALL_PROFILES) {throw new Error('Projects are unavailable while viewing all profiles')@@ -376,7 +395,7 @@ async function activeProjectsContext(profile = projectProfile()): Promise<Activethrow new Error('Active Hermes profile changed while connecting')}- return { connectionId, gateway, profile }+ return { connectionId, gateway, profile, stampLocal }}function applyPayload(payload: ProjectsPayload): void {@@ -431,26 +450,37 @@ const PROJECT_TREE_REQUEST_TIMEOUT_MS = 60_000let projectTreeRefreshGeneration = 0-// Like REST session-list rows, tree-only rows need the exact registry owner.-// Tag copies at the response boundary; never derive ownership when clicked.-function tagProjectSessionConnection(project: SidebarProjectTree, connectionId: null | string): SidebarProjectTree {- if (!connectionId) {- return project+// Like REST session-list rows, tree-only rows need their registry owner, stamped+// at the response boundary rather than derived on click. The canonical stamper+// owns the rules: a row that already names an owner is never re-owned, and+// `local` stays bare so the primary keeps the legacy profile door (#94166).+// The one addition is `local` as a registry secondary (see ProjectRowOwner).+function stampProjectSessions(sessions: SessionInfo[], owner: ProjectRowOwner): SessionInfo[] {+ if (owner.connectionId !== 'local') {+ return stampRowsWithOwningConnection(sessions, owner.connectionId)}- const tag = (session: SessionInfo): SessionInfo => ({ ...session, connection_id: connectionId })+ return owner.stampLocal+ ? sessions.map(session => (session.connection_id?.trim() ? session : { ...session, connection_id: 'local' }))+ : sessions+}++function tagProjectSessionConnection(project: SidebarProjectTree, owner: ProjectRowOwner): SidebarProjectTree {+ if (!owner.connectionId || (owner.connectionId === 'local' && !owner.stampLocal)) {+ return project+ }return {...project,- ...(project.previewSessions ? { previewSessions: project.previewSessions.map(tag) } : {}),+ ...(project.previewSessions ? { previewSessions: stampProjectSessions(project.previewSessions, owner) } : {}),repos: project.repos.map(repo => ({...repo,- groups: repo.groups.map(group => ({ ...group, sessions: group.sessions.map(tag) }))+ groups: repo.groups.map(group => ({ ...group, sessions: stampProjectSessions(group.sessions, owner) }))}))}}-function applyProjectTreePayload(res: ProjectTreePayload, connectionId: null | string): void {+function applyProjectTreePayload(res: ProjectTreePayload, owner: ProjectRowOwner): void {const scoped = new Set(res.scoped_session_ids ?? [])// The tree refreshes on every sessions.changed and window focus, and most of// those answers are unchanged. Keep unchanged nodes by reference so the@@ -458,7 +488,7 @@ function applyProjectTreePayload(res: ProjectTreePayload, connectionId: null | s$projectTree.set(replaceEqualDeep($projectTree.get(),- (res.projects ?? []).map(project => tagProjectSessionConnection(project, connectionId))+ (res.projects ?? []).map(project => tagProjectSessionConnection(project, owner))))$activeProjectId.set(res.active_id ?? null)@@ -514,7 +544,7 @@ async function refreshProjectTreeOn(context: ActiveProjectsContext): Promise<voireturn}- applyProjectTreePayload(res, context.connectionId)+ applyProjectTreePayload(res, context)markProjectsRpcSuccess()} catch (err) {if (generation === projectTreeRefreshGeneration && stillOnProjectsContext(context)) {@@ -549,7 +579,7 @@ export async function refreshProjectTree(): Promise<void> {// the REST fan-out reads every profile's databases directly instead of asking// us to hold a backend open per profile just to draw lanes.async function refreshProjectTreeAcrossProfiles(): Promise<void> {- const connectionId = activeGatewayConnectionId()+ const owner = projectRowOwner()const generation = ++projectTreeRefreshGeneration$projectTreeLoading.set(true)@@ -564,12 +594,12 @@ async function refreshProjectTreeAcrossProfiles(): Promise<void> {if (generation !== projectTreeRefreshGeneration ||$profileScope.get() !== ALL_PROFILES ||- activeGatewayConnectionId() !== connectionId+ activeGatewayConnectionId() !== owner.connectionId) {return}- applyProjectTreePayload(res, connectionId)+ applyProjectTreePayload(res, owner)markProjectsRpcSuccess()} catch (err) {markProjectsRpcFailure(err)@@ -641,7 +671,7 @@ export async function fetchProjectSessions(}return dropRemovedProjectSessions(- res.project ? tagProjectSessionConnection(res.project, context.connectionId) : null,+ res.project ? tagProjectSessionConnection(res.project, context) : null,removalSnapshot)} catch (error) {