The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): supersede displaced PTY viewer, route project tile by active source
teknium1ad4e349df77b
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 8d2dc587638..0538abe3f1f 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -23,10 +23,11 @@ import {import { createClientSessionState } from '@/lib/chat-runtime'import { $clarifyRequests, clearClarifyRequest, setClarifyRequest } from '@/store/clarify'import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'-import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForAgent } from '@/store/gateway'+import { activeGatewayConnectionId, requestGatewayForAgent, requestGatewayForProfile, retainGatewayForAgent } from '@/store/gateway'import { $pinnedSessionIds } from '@/store/layout'import {$activeGatewayProfile,+ $newChatConnectionId,$newChatProfile,$newChatRoute,$profiles,@@ -123,12 +124,18 @@ vi.mock('@/store/profile', async importOriginal => ({ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)}))-vi.mock('@/store/gateway', async importOriginal => ({- ...(await importOriginal<Record<string, unknown>>()),- requestGatewayForAgent: vi.fn(),- requestGatewayForProfile: vi.fn(),- retainGatewayForAgent: vi.fn(async () => () => undefined)-}))+vi.mock('@/store/gateway', async importOriginal => {+ const original = await importOriginal<Record<string, unknown>>()++ return {+ ...original,+ // Default-preserving spy: tests that route by the active source override it.+ activeGatewayConnectionId: vi.fn(original.activeGatewayConnectionId as () => null | string),+ requestGatewayForAgent: vi.fn(),+ requestGatewayForProfile: vi.fn(),+ retainGatewayForAgent: vi.fn(async () => () => undefined)+ }+})vi.mock('@/components/pane-shell/tree/store', async importOriginal => ({...(await importOriginal<Record<string, unknown>>()),@@ -5109,6 +5116,8 @@ describe('openNewSessionTile workspace target', () => {cleanup()$profiles.set([])$newChatProfile.set(null)+ $newChatConnectionId.set(null)+ vi.mocked(activeGatewayConnectionId).mockReset()$activeGatewayProfile.set('default')$projectScope.set(ALL_PROJECTS)$projectTree.set([])@@ -5345,6 +5354,55 @@ describe('openNewSessionTile workspace target', () => {expect($sessionTiles.get()).toContainEqual(expect.objectContaining({ ownerProfile: 'work', storedSessionId }))expect(knownOwnerForSession(storedSessionId)).toBe('work')})++ // Review of #124265: the stale pin may also have captured ANOTHER connection+ // ($newChatConnectionId). The project tree is rendered by the active source,+ // so the tile must pair the project profile with that source — not with the+ // pin's host (right profile, wrong host).+ it('pairs the project profile with the active source, not a stale pin captured on another connection', async () => {+ const storedSessionId = 'stored-project-tile-remote-work'+ setConnection({ mode: 'remote' } as never)+ $profiles.set([{ name: 'default' }, { name: 'work' }] as never)+ $activeGatewayProfile.set('work')+ $newChatProfile.set('work')+ $newChatConnectionId.set('homelab')+ vi.mocked(activeGatewayConnectionId).mockReturnValue('ssh-vps')++ vi.mocked(requestGatewayForAgent).mockImplementation(async (connectionId, profile, method) => {+ if (connectionId === 'ssh-vps' && profile === 'work' && method === 'session.create') {+ return {+ info: { cwd: '/repo/work', model: 'test-model', tools: {}, skills: {} },+ session_id: RUNTIME_SESSION_ID,+ stored_session_id: storedSessionId+ } as never+ }++ throw new Error(`Session create on the wrong host: ${connectionId}::${profile} (${method})`)+ })++ const requestGateway = vi.fn(async (method: string) => {+ throw new Error(`Unexpected ambient RPC: ${method}`)+ })++ let handle: HarnessHandle | null = null+ render(<Harness onReady={value => (handle = value)} requestGateway={requestGateway} />)+ await waitFor(() => expect(handle).not.toBeNull())++ await act(async () => {+ await handle!.openNewSessionTile('center', { cwd: '/repo/work', listed: false })+ })++ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'ssh-vps',+ 'work',+ 'session.create',+ expect.objectContaining({ cwd: '/repo/work' }),+ undefined,+ undefined,+ expect.anything()+ )+ expect(getSessionOwnerHint(storedSessionId)).toMatchObject({ connectionId: 'ssh-vps', profile: 'work' })+ })})describe('openNewSessionTile unlisted owner (#102792)', () => {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 dec91021f21..27db93fe0cd 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@@ -58,6 +58,7 @@ import {ensureGatewayProfile,isLegacyNewChatProfile,normalizeProfileKey,+ resolveActiveSourceOwnerRoute,resolveNewChatOwnerRoute} from '@/store/profile'import { $projectScope } from '@/store/project-scope'@@ -884,8 +885,10 @@ export function useSessionActions({// 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 optionProfile =- options?.profile ?? (typeof options?.cwd === 'string' ? (projectProfile() ?? undefined) : undefined)+ const projectOwnerProfile =+ options?.profile === undefined && typeof options?.cwd === 'string' ? (projectProfile() ?? undefined) : undefined++ const optionProfile = options?.profile ?? projectOwnerProfile// Fresh tile → the caller's workspace when one was named (the sidebar// "+" on a project/worktree lane), explicit null means Home/detached,@@ -898,11 +901,18 @@ export function useSessionActions({const defaultTarget = options?.route === undefined && !explicitTarget ? defaultNewSessionTarget() : null+ // The project tree is rendered by the ACTIVE source: its profile pairs+ // with that source, never with the source a stale new-chat pin captured+ // on another connection (right profile, wrong host).const capturedRoute =options?.route !== undefined? options.route: (options?.workspaceScope?.ownerRoute ??- (defaultTarget ? defaultTarget.route : resolveNewChatOwnerRoute(optionProfile)))+ (defaultTarget+ ? defaultTarget.route+ : projectOwnerProfile+ ? resolveActiveSourceOwnerRoute(projectOwnerProfile)+ : resolveNewChatOwnerRoute(optionProfile)))// A named local profile uses the legacy profile-only transport (no// connectionId). Tab-strip "+" omits `options.profile`; the draft ordiff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex 7ee23633982..08b3e98e39f 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -418,6 +418,20 @@ export function resolveNewChatOwnerRoute(forProfile?: string): AgentProfileRoute}}+/**+ * The owner route for a surface anchored to a profile the ACTIVE source is+ * rendering (a project tree's "+", #124265). Unlike resolveNewChatOwnerRoute+ * this never consults the new-chat pin's captured source, which a stale pick+ * on another connection would otherwise pair with this profile (right profile,+ * wrong host). null keeps the legacy profile-only path.+ */+export function resolveActiveSourceOwnerRoute(profile: string): AgentProfileRoute | null {+ const key = normalizeProfileKey(profile)+ const connectionId = (profilePickConnectionId(key) ?? '').trim()++ return connectionId ? { connectionId, profile: key } : null+}+// Bumped whenever the open session should be dropped for a fresh new-session// draft: a profile switch/create (below), or deleting the project that owns the// currently-open session (store/projects). The chat controller subscribes anddiff --git a/apps/desktop/src/store/windows.test.ts b/apps/desktop/src/store/windows.test.tsindex 4457419b3fb..ef300552055 100644--- a/apps/desktop/src/store/windows.test.ts+++ b/apps/desktop/src/store/windows.test.ts@@ -88,9 +88,12 @@ describe('openSessionInNewWindow', () => {await openSessionInNewWindow('s1')await openSessionInNewWindow('child-not-listed-yet', { watch: true, parentSessionId: 's1' })+ // No parent hint and not listed anywhere: falls back to the viewed profile.+ await openSessionInNewWindow('orphan-not-listed-yet', { watch: true })expect(open).toHaveBeenCalledWith('s1', { profile: 'research', connectionId: 'remote-a', watch: undefined })expect(open).toHaveBeenCalledWith('child-not-listed-yet', { profile: 'research', connectionId: 'remote-a', watch: true })+ expect(open).toHaveBeenCalledWith('orphan-not-listed-yet', { profile: 'work', connectionId: null, watch: true })expect(notifyError).not.toHaveBeenCalled()// The owner resolver's lazy import is the heavy session-actions module.}, 60_000)diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 5f69c3cea1e..c10ebccb3db 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -219,6 +219,10 @@ class PtySessionRegistry:for key in keys:session = self._sessions.pop(key, None)if session is not None:+ # A sibling tab sharing the attach token may still be viewing this+ # PTY: supersede it explicitly (4409) instead of leaving it silent+ # until its next keystroke fails with 1013.+ await _close_ws(session._ws, WS_CLOSE_SUPERSEDED)await session.close()def detach(self, key: str, ws) -> None:diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.pyindex cd5a8c4346f..0dce3616b83 100644--- a/tests/hermes_cli/test_pty_session.py+++ b/tests/hermes_cli/test_pty_session.py@@ -431,7 +431,7 @@ async def test_close_all_survives_key_popped_by_concurrent_reap():@pytest.mark.asyncioasync def test_close_other_sessions_removes_old_profile_session():- from hermes_cli.pty_session import PtySession+ from hermes_cli.pty_session import WS_CLOSE_SUPERSEDED, PtySessionreg = make_registry()old_bridge = FakeBridge([b""])@@ -440,7 +440,9 @@ async def test_close_other_sessions_removes_old_profile_session():current = PtySession("token\0beta\0session-b", current_bridge, buffer_cap=1024, read_timeout=0.01)await old.start()await current.start()- old.detach(None)+ # A sibling tab (same attach token, other profile) is still viewing the old PTY.+ old_ws = FakeWS()+ assert await old.attach(old_ws)reg._sessions[old.key] = oldreg._sessions[current.key] = current@@ -449,4 +451,6 @@ async def test_close_other_sessions_removes_old_profile_session():assert old_bridge.closedassert old.key not in reg._sessionsassert reg._sessions[current.key] is current+ # The displaced viewer gets the documented supersede code rather than going silent.+ assert old_ws.close_code == WS_CLOSE_SUPERSEDEDawait reg.close_all()