Skip to content

The agent that grows with you

fix(desktop): tag project-tree session rows with their registry source

unsupportedpastelsf6c15b097178
diff --git a/apps/desktop/src/store/projects-connection-tag.test.ts b/apps/desktop/src/store/projects-connection-tag.test.ts
new file mode 100644
index 00000000000..27262012ff3
--- /dev/null
+++ b/apps/desktop/src/store/projects-connection-tag.test.ts
@@ -0,0 +1,162 @@
+import { atom } from 'nanostores'
+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 { $activeGatewayProfile, setShowAllProfiles } from '@/store/profile'
+import { $sessions } from '@/store/session'
+import { sessionOwnerRouteFromRow } from '@/store/session-request-router'
+import { deferred } from '@/test/deferred'
+
+import { $projectTree, fetchProjectSessions, refreshProjectTree } from './projects'
+
+vi.mock('@/store/gateway', () => ({
+ $gateway: atom(null),
+ activeGateway: vi.fn(),
+ activeGatewayConnectionId: vi.fn(),
+ ensureActiveGatewayOpen: vi.fn()
+}))
+vi.mock('@/i18n', () => ({ translateNow: (key: string) => key }))
+vi.mock('@/hermes', () => ({
+ getHermesConfig: vi.fn(),
+ getProfiles: vi.fn(),
+ hermesApi: vi.fn(),
+ setApiRequestProfile: vi.fn(),
+ STARTUP_REQUEST_TIMEOUT_MS: 1000
+}))
+
+function treeProject(): SidebarProjectTree {
+ // Neither row is in the recents store; opening it must use tree provenance.
+ const row = { id: 'tree-only', profile: 'default', title: 'Outside recents' }
+
+ return {
+ id: 'project',
+ label: 'Project',
+ path: '/project',
+ sessionCount: 1,
+ previewSessions: [row as never],
+ repos: [
+ {
+ id: 'repo',
+ label: 'Repo',
+ path: '/project',
+ sessionCount: 1,
+ groups: [{ id: 'lane', label: 'main', path: '/project', sessions: [row as never] }]
+ }
+ ]
+ }
+}
+
+function selectConnection(connectionId: string | null) {
+ vi.mocked(activeGatewayConnectionId).mockReturnValue(connectionId)
+}
+
+function rows(project: SidebarProjectTree) {
+ return [
+ ...(project.previewSessions ?? []),
+ ...project.repos.flatMap(repo => repo.groups.flatMap(group => group.sessions))
+ ]
+}
+
+function connect(request = vi.fn()) {
+ const gateway = { connectionState: 'open', request }
+ vi.mocked(activeGateway).mockReturnValue(gateway as never)
+ $gateway.set(gateway as never)
+
+ return request
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ $activeGatewayProfile.set('default')
+ setShowAllProfiles(false)
+ $sessions.set([])
+ $projectTree.set([])
+ selectConnection('home')
+})
+
+describe('project session connection provenance', () => {
+ it('tags tree-only overview and hydrated rows across Home → local → Home', async () => {
+ for (const connectionId of ['home', 'local', 'home']) {
+ const project = treeProject()
+ connect(vi.fn().mockResolvedValue({ projects: [project], project, scoped_session_ids: [] }))
+ selectConnection(connectionId)
+
+ await refreshProjectTree()
+ const hydrated = await fetchProjectSessions(project.id)
+
+ expect($sessions.get()).toEqual([])
+ expect(hydrated).not.toBeNull()
+
+ for (const row of [...rows($projectTree.get()[0]), ...rows(hydrated!)]) {
+ expect(sessionOwnerRouteFromRow(row)).toEqual({ connectionId, profile: row.profile })
+ }
+
+ // Stamp renderer copies, not the response object shared by transport caches.
+ expect(rows(project).every(row => row.connection_id === undefined)).toBe(true)
+ const before = $projectTree.get()
+ await refreshProjectTree()
+ expect($projectTree.get()).toBe(before)
+ }
+ })
+
+ it.each(['overview', 'hydrated', 'all-profiles'])(
+ 'drops a late %s response when only the connection identity changes',
+ async surface => {
+ const pending = deferred<unknown>()
+ const started = deferred<void>()
+
+ const request = vi.fn(() => {
+ started.resolve()
+
+ return pending.promise
+ })
+
+ connect(request)
+ vi.mocked(hermesApi).mockImplementation(request as never)
+ setShowAllProfiles(surface === 'all-profiles')
+
+ const result = surface === 'hydrated' ? fetchProjectSessions('project') : refreshProjectTree()
+ await started.promise
+ // Same profile and socket object: the registry identity itself must be guarded.
+ selectConnection('local')
+ pending.resolve({ projects: [treeProject()], project: treeProject(), scoped_session_ids: [] })
+ const value = await result
+
+ expect($projectTree.get()).toEqual([])
+
+ if (surface === 'hydrated') {
+ expect(value).toBeNull()
+ }
+ }
+ )
+
+ it('tags the all-profiles tree without replacing each row profile', async () => {
+ const project = treeProject()
+ project.previewSessions![0].profile = 'coder'
+ vi.mocked(hermesApi).mockResolvedValue({ projects: [project], scoped_session_ids: [] })
+ selectConnection('local')
+ setShowAllProfiles(true)
+
+ await refreshProjectTree()
+
+ for (const row of rows($projectTree.get()[0])) {
+ expect(sessionOwnerRouteFromRow(row)).toEqual({ connectionId: 'local', profile: 'coder' })
+ }
+ })
+
+ it('leaves legacy rows untagged when no registry identity exists', async () => {
+ const project = treeProject()
+ connect(vi.fn().mockResolvedValue({ projects: [project], project, scoped_session_ids: [] }))
+ selectConnection(null)
+
+ 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()
+ }
+ })
+})
diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.ts
index b18dad0f185..fa7f45cc18f 100644
--- a/apps/desktop/src/store/projects.test.ts
+++ b/apps/desktop/src/store/projects.test.ts
@@ -58,6 +58,7 @@ vi.mock('@/lib/desktop-fs', () => ({
vi.mock('@/store/gateway', () => ({
$gateway: atom(null),
activeGateway: vi.fn(),
+ activeGatewayConnectionId: vi.fn(() => null),
ensureActiveGatewayOpen: vi.fn()
}))
diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts
index 92f69bcad96..473ebd6581e 100644
--- a/apps/desktop/src/store/projects.ts
+++ b/apps/desktop/src/store/projects.ts
@@ -17,7 +17,7 @@ import { desktopGit } from '@/lib/desktop-git'
import { isMissingRestEndpoint, isMissingRpcMethod } from '@/lib/gateway-rpc'
import { isUnderPath } from '@/lib/path-compare'
import { revealFile } from '@/store/file-actions'
-import { $gateway, activeGateway, ensureActiveGatewayOpen } from '@/store/gateway'
+import { $gateway, activeGateway, activeGatewayConnectionId, ensureActiveGatewayOpen } from '@/store/gateway'
import { $sidebarShowAllSessions, setSidebarAgentsGrouped } from '@/store/layout'
import { notify } from '@/store/notifications'
import {
@@ -340,21 +340,28 @@ function isRetryableProjectTreeReadError(error: unknown): boolean {
}
interface ActiveProjectsContext {
+ connectionId: null | string
gateway: HermesGateway
profile: string
}
function stillOnProjectsContext(context: ActiveProjectsContext): boolean {
- return activeGateway() === context.gateway && projectProfile() === context.profile
+ 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 {
- return activeGateway() === context.gateway && normalizeProfileKey($activeGatewayProfile.get()) === context.profile
+ return (
+ activeGateway() === context.gateway &&
+ normalizeProfileKey($activeGatewayProfile.get()) === context.profile &&
+ activeGatewayConnectionId() === context.connectionId
+ )
}
async function activeProjectsContext(profile = projectProfile()): Promise<ActiveProjectsContext> {
+ const connectionId = activeGatewayConnectionId()
+
if (!profile || profile === ALL_PROFILES) {
throw new Error('Projects are unavailable while viewing all profiles')
}
@@ -365,11 +372,11 @@ async function activeProjectsContext(profile = projectProfile()): Promise<Active
gateway = await ensureActiveGatewayOpen()
}
- if (!gateway || !stillOnWritableProjectOwner({ gateway, profile })) {
+ if (!gateway || !stillOnWritableProjectOwner({ connectionId, gateway, profile })) {
throw new Error('Active Hermes profile changed while connecting')
}
- return { gateway, profile }
+ return { connectionId, gateway, profile }
}
function applyPayload(payload: ProjectsPayload): void {
@@ -424,12 +431,36 @@ const PROJECT_TREE_REQUEST_TIMEOUT_MS = 60_000
let projectTreeRefreshGeneration = 0
-function applyProjectTreePayload(res: ProjectTreePayload): void {
+// 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
+ }
+
+ const tag = (session: SessionInfo): SessionInfo => ({ ...session, connection_id: connectionId })
+
+ return {
+ ...project,
+ ...(project.previewSessions ? { previewSessions: project.previewSessions.map(tag) } : {}),
+ repos: project.repos.map(repo => ({
+ ...repo,
+ groups: repo.groups.map(group => ({ ...group, sessions: group.sessions.map(tag) }))
+ }))
+ }
+}
+
+function applyProjectTreePayload(res: ProjectTreePayload, connectionId: null | string): 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
// entered project doesn't refetch and rebuild on a no-op (#77591).
- $projectTree.set(replaceEqualDeep($projectTree.get(), res.projects ?? []))
+ $projectTree.set(
+ replaceEqualDeep(
+ $projectTree.get(),
+ (res.projects ?? []).map(project => tagProjectSessionConnection(project, connectionId))
+ )
+ )
$activeProjectId.set(res.active_id ?? null)
const tombstones = $removedSessionIds.get()
@@ -483,7 +514,7 @@ async function refreshProjectTreeOn(context: ActiveProjectsContext): Promise<voi
return
}
- applyProjectTreePayload(res)
+ applyProjectTreePayload(res, context.connectionId)
markProjectsRpcSuccess()
} catch (err) {
if (generation === projectTreeRefreshGeneration && stillOnProjectsContext(context)) {
@@ -518,6 +549,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 generation = ++projectTreeRefreshGeneration
$projectTreeLoading.set(true)
@@ -529,11 +561,15 @@ async function refreshProjectTreeAcrossProfiles(): Promise<void> {
// A profile switch mid-flight leaves this payload describing the wrong
// scope; the newer refresh owns the tree.
- if (generation !== projectTreeRefreshGeneration || $profileScope.get() !== ALL_PROFILES) {
+ if (
+ generation !== projectTreeRefreshGeneration ||
+ $profileScope.get() !== ALL_PROFILES ||
+ activeGatewayConnectionId() !== connectionId
+ ) {
return
}
- applyProjectTreePayload(res)
+ applyProjectTreePayload(res, connectionId)
markProjectsRpcSuccess()
} catch (err) {
markProjectsRpcFailure(err)
@@ -604,7 +640,10 @@ export async function fetchProjectSessions(
return null
}
- return dropRemovedProjectSessions(res.project ?? null, removalSnapshot)
+ return dropRemovedProjectSessions(
+ res.project ? tagProjectSessionConnection(res.project, context.connectionId) : null,
+ removalSnapshot
+ )
} catch (error) {
if (
(generation !== null && generation !== projectSessionsRefreshGeneration) ||