The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): route composer completions to the session owner (#141583)
Teknium14ccc81b2dbb
diff --git a/apps/desktop/src/app/chat/composer/hooks/completion-route.ts b/apps/desktop/src/app/chat/composer/hooks/completion-route.tsnew file mode 100644index 00000000000..b62f7660cec--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/completion-route.ts@@ -0,0 +1,43 @@+import type { HermesGateway } from '@/hermes'+import { ambientRequestFor } from '@/store/session-gone-latch'+import { sessionOwnerIsKnown } from '@/store/session-owner-resolution'+import { isSessionOwnerRoute, requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'+import { knownOwnerForSession } from '@/store/session-states'++/**+ * Where a composer completion RPC (`commands.catalog`, `complete.slash`,+ * `complete.path`) for `sessionId` goes: the session's OWNER, never the+ * window's ambient socket. On a multiplexed local gateway the ambient socket's+ * authority is the launch profile's, which refuses another profile's+ * `session_id` as not_found — so a non-primary-profile window's palette said+ * "No matches" for every `/` and `@` (#141583). Resolved at call time, like+ * every session-scoped RPC (requestForSessionProfile).+ *+ * Completions are advisory: an owner nothing can name yet (a runtime whose+ * row/hint has not landed) rides the ambient socket instead of failing+ * closed — the worst case is the same empty list the user would see anyway.+ */+export function completionOwner(sessionId: null | string | undefined): SessionOwnerScope {+ const owner = sessionId ? knownOwnerForSession(sessionId) : undefined++ return sessionOwnerIsKnown(owner) ? owner : undefined+}++/** Cache-key fragment naming the backend that answered, so a result cached+ * from one owner (or the ambient socket) is never served for another. */+export function completionOwnerKey(owner: SessionOwnerScope): string {+ if (isSessionOwnerRoute(owner)) {+ return `${owner.connectionId}::${owner.targetProfile ?? owner.profile}`+ }++ return owner ? `profile:${owner}` : 'ambient'+}++export function requestCompletion<T>(+ gateway: HermesGateway,+ owner: SessionOwnerScope,+ method: string,+ params: Record<string, unknown>+): Promise<T> {+ return requestForSessionProfile<T>(owner, ambientRequestFor(gateway), method, params)+}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-at-completions.tsindex 505e0e646ef..f0b96541195 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts@@ -10,6 +10,7 @@ import { normalize } from '@/lib/text'import type { ComposerAtCompletionSource } from '../contrib'import { COMPOSER_AREAS } from '../contrib'+import { completionOwner, completionOwnerKey, requestCompletion } from './completion-route'import type { CompletionEntry, CompletionPayload } from './use-live-completion-adapter'import { useLiveCompletionAdapter } from './use-live-completion-adapter'@@ -195,8 +196,12 @@ export function useAtCompletions(options: {// Cache key: the completion depends on the query AND the directory it's// resolved against, so a cwd or session change can't serve another tree's- // listing.- const cacheKey = useCallback((query: string) => `${cwd ?? ''}|${sessionId ?? ''}|${query}`, [cwd, sessionId])+ // listing. The owner is part of it too: the listing comes from the session's+ // owning backend (#141583), and an ambient answer must not stand in for it.+ const cacheKey = useCallback(+ (query: string) => `${completionOwnerKey(completionOwner(sessionId))}|${cwd ?? ''}|${sessionId ?? ''}|${query}`,+ [cwd, sessionId]+ )const fetcher = useCallback(async (query: string): Promise<CompletionPayload> => {@@ -225,7 +230,7 @@ export function useAtCompletions(options: {// `git ls-files` + rank on the backend (~40ms of the ~50ms round trip// measured on this repo's 8k files).const result = await cachedPathCompletion(cacheKey(query), () =>- gateway.request<{ items?: CompletionEntry[] }>('complete.path', params)+ requestCompletion<{ items?: CompletionEntry[] }>(gateway, completionOwner(sessionId), 'complete.path', params))const items = result.items ?? []diff --git a/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsxnew file mode 100644index 00000000000..7adf5210b65--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-completions-owner-route.test.tsx@@ -0,0 +1,137 @@+import type { Unstable_TriggerItem } from '@assistant-ui/core'+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { HermesGateway } from '@/hermes'+import { queryClient } from '@/lib/query-client'+import type * as GatewayStore from '@/store/gateway'+import { _resetSessionOwnerHintsForTests, setSessionOwnerHint } from '@/store/session'++import { useAtCompletions } from './use-at-completions'+import { useSlashCompletions } from './use-slash-completions'++const routed = vi.hoisted(() => ({+ requestGatewayForAgent: vi.fn()+}))++vi.mock('@/store/gateway', async importOriginal => ({+ ...(await importOriginal<typeof GatewayStore>()),+ requestGatewayForAgent: routed.requestGatewayForAgent+}))++const SESSION = 'sess-research-1'+const OWNER = { connectionId: 'local', profile: 'research' }++const CATALOG = {+ categories: [{ name: 'Session', pairs: [['/new', 'Start a new session']] }],+ pairs: [['/new', 'Start a new session']]+}++// The ambient (launch-profile) socket of a multiplexed local gateway: its+// authority refuses another profile's session_id, exactly like+// gateway/session_discovery.py and gateway/session_complete_path.py do.+function ambientGateway() {+ return {+ request: vi.fn(async () => {+ throw new Error('not_found')+ })+ } as unknown as HermesGateway & { request: ReturnType<typeof vi.fn> }+}++function ownerAnswers(method: string, params: Record<string, unknown>) {+ if (method === 'commands.catalog') {+ return CATALOG+ }++ if (method === 'complete.slash') {+ return { items: [{ text: '/research-only', display: '/research-only' }], replace_from: 1 }+ }++ return { items: [{ text: `@file:${String(params.word).slice(1)}notes.md`, display: 'notes.md' }] }+}++type Search = (query: string) => readonly Unstable_TriggerItem[]++/** Read through `api` each time: the adapter re-renders with its results. */+async function settle(api: { search?: Search }, query: string) {+ await act(async () => {+ api.search!(query)+ await Promise.resolve()+ })+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 150))+ })++ return api.search!(query)+}++beforeEach(() => {+ routed.requestGatewayForAgent.mockImplementation(+ async (_connectionId: string, _profile: string, method: string, params: Record<string, unknown>) =>+ ownerAnswers(method, params)+ )+ setSessionOwnerHint(SESSION, OWNER)+})++afterEach(() => {+ cleanup()+ queryClient.clear()+ _resetSessionOwnerHintsForTests()+ routed.requestGatewayForAgent.mockReset()+})++// #141583: a non-primary-profile window's composer sent completion RPCs on the+// window's ambient socket, whose authority is the launch profile's — every `/`+// and `@` lookup for another profile's session came back not_found and the+// palette said "No matches". Completions must go to the session's owner.+describe('composer completions route to the session owner', () => {+ it('serves / catalog and typed lookups from the owning profile, not the ambient socket', async () => {+ const gateway = ambientGateway()+ const api: { search?: Search } = {}++ function Probe() {+ api.search = useSlashCompletions({ gateway, sessionId: SESSION }).adapter.search++ return null+ }++ render(<Probe />)++ const bare = await settle(api, '')+ const typed = await settle(api, 'res')++ expect(bare.map(item => (item.metadata as { command?: string }).command)).toContain('/new')+ expect(typed.map(item => (item.metadata as { command?: string }).command)).toContain('/research-only')+ expect(gateway.request).not.toHaveBeenCalled()+ expect(routed.requestGatewayForAgent).toHaveBeenCalledWith('local', 'research', 'commands.catalog', {+ session_id: SESSION+ })+ expect(routed.requestGatewayForAgent).toHaveBeenCalledWith('local', 'research', 'complete.slash', {+ session_id: SESSION,+ text: '/res'+ })+ })++ it('serves @ path completions from the owning profile, not the ambient socket', async () => {+ const gateway = ambientGateway()+ const api: { search?: Search } = {}++ function Probe() {+ api.search = useAtCompletions({ cwd: '/repo', gateway, sessionId: SESSION }).adapter.search++ return null+ }++ render(<Probe />)++ const items = await settle(api, 'no')++ expect(items.map(item => (item.metadata as { rawText?: string }).rawText)).toContain('@file:nonotes.md')+ expect(gateway.request).not.toHaveBeenCalled()+ expect(routed.requestGatewayForAgent).toHaveBeenCalledWith('local', 'research', 'complete.path', {+ cwd: '/repo',+ session_id: SESSION,+ word: '@no'+ })+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.tsindex 7ebc6130550..a6102dfde21 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts@@ -21,6 +21,7 @@ import { $slashCompletionsEpoch, cachedSlashCompletion, hasCachedSlashCompletionimport { normalize } from '@/lib/text'import { $sessions } from '@/store/session'+import { completionOwner, completionOwnerKey, requestCompletion } from './completion-route'import type { CompletionEntry, CompletionPayload } from './use-live-completion-adapter'import { useLiveCompletionAdapter } from './use-live-completion-adapter'@@ -83,8 +84,15 @@ export function useSlashCompletions(options: {[sessionId, profile])- const scopeKey = sessionId ?? (profile ? `profile:${profile}` : '')- const catalogKey = scopeKey ? `catalog:${scopeKey}` : 'catalog'+ // Session-scoped lookups go to the session's owner (#141583); the owner is+ // resolved per call and folded into every cache key, so an answer from one+ // backend is never replayed for another.+ const keysFor = useCallback(() => {+ const owner = completionOwner(sessionId)+ const scopeKey = sessionId ? `${completionOwnerKey(owner)}:${sessionId}` : profile ? `profile:${profile}` : ''++ return { catalogKey: scopeKey ? `catalog:${scopeKey}` : 'catalog', owner, scopeKey }+ }, [sessionId, profile])// Warm argument_mode before the first `/` so Space treats /review as text.useEffect(() => {@@ -92,8 +100,10 @@ export function useSlashCompletions(options: {return}+ const { catalogKey, owner } = keysFor()+void cachedSlashCompletion(catalogKey, () =>- gateway.request<CommandsCatalogLike>('commands.catalog', sessionParams)+ requestCompletion<CommandsCatalogLike>(gateway, owner, 'commands.catalog', sessionParams)).then(catalog => {filterDesktopCommandsCatalog(catalog)@@ -101,7 +111,7 @@ export function useSlashCompletions(options: {.catch(() => {// Next keystroke retries; don't block the composer on a warm-up miss.})- }, [gateway, epoch, catalogKey, sessionParams])+ }, [gateway, epoch, keysFor, sessionParams])const fetcher = useCallback(async (query: string): Promise<CompletionPayload> => {@@ -170,11 +180,13 @@ export function useSlashCompletions(options: {return { items, query }}+ const { catalogKey, owner, scopeKey } = keysFor()+try {if (!query) {const catalog = filterDesktopCommandsCatalog(await cachedSlashCompletion(catalogKey, () =>- gateway.request<CommandsCatalogLike>('commands.catalog', sessionParams)+ requestCompletion<CommandsCatalogLike>(gateway, owner, 'commands.catalog', sessionParams)))@@ -216,7 +228,7 @@ export function useSlashCompletions(options: {}const result = await cachedSlashCompletion(`slash:${scopeKey}:${text.toLowerCase()}`, () =>- gateway.request<{ items?: CompletionEntry[]; replace_from?: number }>('complete.slash', {+ requestCompletion<{ items?: CompletionEntry[]; replace_from?: number }>(gateway, owner, 'complete.slash', {text,...sessionParams})@@ -289,7 +301,7 @@ export function useSlashCompletions(options: {return { items: [], query }}},- [gateway, skinThemes, activeSkin, scopeKey, catalogKey, sessionParams]+ [gateway, skinThemes, activeSkin, keysFor, sessionParams])const toItem = useCallback((entry: CompletionEntry, index: number): Unstable_TriggerItem => {@@ -331,9 +343,11 @@ export function useSlashCompletions(options: {return true}+ const { catalogKey, scopeKey } = keysFor()+return hasCachedSlashCompletion(query ? `slash:${scopeKey}:${text.toLowerCase()}` : catalogKey)},- [skinThemes, scopeKey, catalogKey]+ [skinThemes, keysFor])return useLiveCompletionAdapter({ enabled, epoch: `${epoch}:${locale}`, fetcher, isCached, toItem })diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsxindex c534b27b930..db97f9bf6c5 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx@@ -122,7 +122,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sessconst expanded = draft.includes('\n')const canSubmit = draft.trim().length > 0const at = useAtCompletions({ cwd, gateway, sessionId })- const slash = useSlashCompletions({ gateway })+ const slash = useSlashCompletions({ gateway, sessionId })const emoji = useEmojiCompletions()// Timers this composer schedules must not outlive it. Every callback below