Skip to content

The agent that grows with you

fix(webapp): send a session id only with the profile that owns it

unsupportedpastels0ecbd0415265
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 28cd1562feb..35361e5f2a4 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -809,3 +809,32 @@ export function sessionReadOwnerPin(id: string, profile?: ProfileScope): { conne
...(profile == null && ownerProfile ? { profile: ownerProfile } : {})
}
}
+
+/** The backend a gateway FILE request naming session `id` must go to: the owner's
+ * backend-facing profile, plus its connection when that is not the ambient one.
+ * Null when no owner profile is known. A file route looks `session_id` up in
+ * the profile the request names, so the id must never travel with another
+ * profile: a caller that gets null names no session at all. */
+export function sessionFileOwnerScope(id: string): { connectionId?: string; profile: string } | null {
+ const owner = _sessionOwnerResolver?.(id)
+
+ if (!owner) {
+ return null
+ }
+
+ if (typeof owner === 'string') {
+ const profile = owner.trim()
+
+ return profile ? { profile } : null
+ }
+
+ const profile = String(owner.targetProfile || owner.profile || '').trim()
+
+ if (!profile) {
+ return null
+ }
+
+ const connectionId = String(owner.connectionId ?? '').trim()
+
+ return connectionId && connectionId !== (ambientOwnerConnectionId() ?? 'local') ? { connectionId, profile } : { profile }
+}
diff --git a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx b/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
index 783a1a297f4..37543ef0505 100644
--- a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
+++ b/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
@@ -1,3 +1,5 @@
+import '@/store/session-states'
+
import { EditorView } from '@codemirror/view'
import { LOCAL_CONNECTION_ID } from '@hermes/shared'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
@@ -10,11 +12,12 @@ import { LocalFilePreview } from '@/app/chat/right-rail/preview-file'
import { SessionViewProvider } from '@/app/chat/session-view'
import { MarkdownImage } from '@/components/assistant-ui/markdown-text'
import { $previewTabs } from '@/store/preview'
-import { $connection } from '@/store/session'
+import { $connection, _resetSessionOwnerHintsForTests, setSessionOwnerHint } from '@/store/session'
import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'
import { installBrowserDesktopBridge } from './browser-desktop-bridge'
import { readDesktopFileText, writeDesktopFileText } from './desktop-fs'
+import { normalizeOrLocalPreviewTarget } from './local-preview'
import { resolveMediaPlaybackSrc } from './media'
// The pane's consent dialog needs a QueryClientProvider; these tests read files, not consent.
@@ -30,13 +33,36 @@ const CLIP = '/workspace/clip.mp4'
const win = window
let requests: { body: Record<string, unknown>; method: string; url: URL }[] = []
+// The profile each session belongs to. `ops-session` is a Bot's: the window stays on `default`.
+const SESSION_OWNERS: Record<string, string> = { 'ops-session': 'ops', 'sess-1': 'default', 'stored-1': 'default' }
+
+const profileOf = (request: (typeof requests)[number]) =>
+ request.url.searchParams.get('profile') ?? (request.body.profile as string | undefined) ?? null
+
+const sessionOf = (request: (typeof requests)[number]) =>
+ request.url.searchParams.get('session_id') ?? (request.body.session_id as string | undefined) ?? null
+
beforeEach(() => {
requests = []
seedWebappSession('served-token')
+ _resetSessionOwnerHintsForTests()
+
+ for (const [sessionId, profile] of Object.entries(SESSION_OWNERS)) {
+ setSessionOwnerHint(sessionId, { connectionId: LOCAL_CONNECTION_ID, profile })
+ }
+
vi.stubGlobal(
'fetch',
vi.fn(async (input: URL, init?: RequestInit) => {
- requests.push({ body: JSON.parse(String(init?.body ?? '{}')), method: init?.method ?? 'GET', url: input })
+ const request = { body: JSON.parse(String(init?.body ?? '{}')), method: init?.method ?? 'GET', url: input }
+
+ requests.push(request)
+ const sessionId = sessionOf(request)
+
+ // The gateway looks a session up in the profile the request names, nowhere else.
+ if (sessionId && SESSION_OWNERS[sessionId] !== (profileOf(request) ?? 'default')) {
+ return new Response(JSON.stringify({ detail: 'Session not found' }), { status: 404 })
+ }
const answers: Record<string, unknown> = {
'/api/files/ticket': { ticket: 'stream-ticket' },
@@ -55,6 +81,7 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ _resetSessionOwnerHintsForTests({ storage: true })
$previewTabs.set([])
clearWebappSession()
Reflect.deleteProperty(win, 'hermesDesktop')
@@ -193,6 +220,53 @@ describe('Save in a session sandbox', () => {
})
})
+describe('a session owned by another profile than the window', () => {
+ const OPS = 'ops-session'
+
+ it('reads its file with the profile that owns it', async () => {
+ await expect(readDesktopFileText(NOTE, { sessionId: OPS })).resolves.toMatchObject({ text: 'session note' })
+
+ const [read] = readsOf('/api/fs/read-text')
+
+ expect([profileOf(read), sessionOf(read)]).toEqual(['ops', OPS])
+ })
+
+ it('saves its file with the profile that owns it', async () => {
+ await expect(writeDesktopFileText(NOTE, 'edited', { sessionId: OPS })).resolves.toEqual({ path: NOTE })
+
+ const [save] = readsOf('/api/fs/write-text')
+
+ expect([profileOf(save), sessionOf(save)]).toEqual(['ops', OPS])
+ })
+
+ it('tickets its clip with the profile that owns it', async () => {
+ const src = new URL(await resolveMediaPlaybackSrc(CLIP, OWNER, OPS))
+
+ expect(requests[0].body).toEqual({ path: CLIP, profile: 'ops', route: 'stream', session_id: OPS })
+ expect(Object.fromEntries(src.searchParams)).toMatchObject({ profile: 'ops', session_id: OPS })
+ })
+
+ it('enriches a preview of its file with the profile that owns it', async () => {
+ await normalizeOrLocalPreviewTarget(NOTE, '/workspace', { sessionId: OPS })
+
+ const [read] = readsOf('/api/fs/read-text')
+
+ expect([profileOf(read), sessionOf(read)]).toEqual(['ops', OPS])
+ })
+
+ it('names no session when its owner is unknown, as a sessionless read does', async () => {
+ await readDesktopFileText(NOTE, { sessionId: 'unknown-session' })
+ await writeDesktopFileText(NOTE, 'edited', { sessionId: 'unknown-session' })
+ await resolveMediaPlaybackSrc(CLIP, OWNER, 'unknown-session')
+
+ expect(requests.map(request => [request.url.pathname, profileOf(request), sessionOf(request)])).toEqual([
+ ['/api/fs/read-text', 'default', null],
+ ['/api/fs/write-text', 'default', null],
+ ['/api/files/ticket', 'default', null]
+ ])
+ })
+})
+
describe('native Desktop reads', () => {
it('keeps a local save to its path', async () => {
globalThis.document.documentElement.removeAttribute('data-hermes-desktop-host')
diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.ts
index 3d282ade954..ac65dab2f05 100644
--- a/apps/desktop/src/lib/desktop-fs.ts
+++ b/apps/desktop/src/lib/desktop-fs.ts
@@ -1,4 +1,4 @@
-import { hermesApi } from '@/api/client'
+import { hermesApi, sessionFileOwnerScope } from '@/api/client'
import type {
HermesConnection,
HermesReadDirResult,
@@ -60,8 +60,23 @@ export interface DesktopFsSessionScope {
sessionId?: null | string
}
-function fsPath(endpoint: string, filePath: string, scope?: DesktopFsSessionScope) {
- const session = scope?.sessionId ? `&session_id=${encodeURIComponent(scope.sessionId)}` : ''
+interface FsRoute {
+ owner: { connectionId?: string; profile?: string }
+ sessionId?: string
+}
+
+/** Where a gateway file request goes. A session id travels only with the profile (and
+ * connection) that owns it: a Bot or pooled chat's owner can differ from the window's. With
+ * no known owner the request names no session and goes to the window's profile. */
+function fsRoute(scope?: DesktopFsSessionScope): FsRoute {
+ const sessionId = scope?.sessionId || undefined
+ const owner = sessionId ? sessionFileOwnerScope(sessionId) : null
+
+ return owner ? { owner, sessionId } : { owner: { profile: desktopFsProfile() } }
+}
+
+function fsPath(endpoint: string, filePath: string, sessionId?: string) {
+ const session = sessionId ? `&session_id=${encodeURIComponent(sessionId)}` : ''
return `/api/fs/${endpoint}?path=${encodeURIComponent(filePath)}${session}`
}
@@ -76,10 +91,8 @@ function bridge() {
return desktop
}
-function remoteFsApi<T>(path: string, body?: Record<string, unknown>): Promise<T> {
- return hermesApi<T>(
- body ? { body, method: 'POST', path, profile: desktopFsProfile() } : { path, profile: desktopFsProfile() }
- )
+function remoteFsApi<T>(path: string, body?: Record<string, unknown>, owner = fsRoute().owner): Promise<T> {
+ return hermesApi<T>(body ? { ...owner, body, method: 'POST', path } : { ...owner, path })
}
/** True when a bridge read returned the main process's structured "file is not
@@ -132,7 +145,9 @@ export async function readDesktopFileText(
return result
}
- return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path, scope))
+ const route = fsRoute(scope)
+
+ return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path, route.sessionId), undefined, route.owner)
}
// Save UTF-8 text back to a file. Local writes go through the hardened Electron
@@ -155,11 +170,13 @@ export async function writeDesktopFileText(
return desktop.writeTextFile(path, content)
}
- const result = await remoteFsApi<{ ok?: boolean; path?: string }>('/api/fs/write-text', {
- content,
- path,
- ...(scope?.sessionId ? { session_id: scope.sessionId } : {})
- })
+ const route = fsRoute(scope)
+
+ const result = await remoteFsApi<{ ok?: boolean; path?: string }>(
+ '/api/fs/write-text',
+ { content, path, ...(route.sessionId ? { session_id: route.sessionId } : {}) },
+ route.owner
+ )
return { path: result.path || path }
}
@@ -183,7 +200,13 @@ export async function readDesktopFileDataUrl(path: string, scope?: DesktopFsSess
return result
}
- const result = await remoteFsApi<string | { dataUrl?: string }>(fsPath('read-data-url', path, scope))
+ const route = fsRoute(scope)
+
+ const result = await remoteFsApi<string | { dataUrl?: string }>(
+ fsPath('read-data-url', path, route.sessionId),
+ undefined,
+ route.owner
+ )
return typeof result === 'string' ? result : result.dataUrl || ''
}
diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.ts
index f2b1fb8c32f..642b5d5b8a7 100644
--- a/apps/desktop/src/lib/media.ts
+++ b/apps/desktop/src/lib/media.ts
@@ -1,6 +1,6 @@
import { fileUrlToNativePath, LOCAL_CONNECTION_ID } from '@hermes/shared'
-import { capabilityScoped, hermesApi, type OwnerScope } from '@/api/client'
+import { capabilityScoped, hermesApi, type OwnerScope, sessionFileOwnerScope } from '@/api/client'
import type { HermesConnection } from '@/global'
import { translateNow } from '@/i18n'
import { desktopFsCacheKey, isReadFileErrorResult, readDesktopFileDataUrl } from '@/lib/desktop-fs'
@@ -247,15 +247,18 @@ export async function resolveMediaPlaybackSrc(path: string, owner?: OwnerScope,
if (window.hermesDesktop && ['audio', 'video'].includes(mediaKind(path))) {
if (window.hermesDesktop.getGatewayFileStreamUrl) {
const conn = $connection.get()
+ // A Docker agent's /workspace is its session's own sandbox. The session id goes only with
+ // the profile that owns it; with no known owner the clip names no session.
+ const session = sessionId ? sessionFileOwnerScope(sessionId) : null
+ const via = session ?? owner
// A tile keeps its owner's profile for every ticket, renewals included, as its image reads do.
return window.hermesDesktop.getGatewayFileStreamUrl({
- connectionId: owner?.connectionId || conn?.connectionId,
+ connectionId: via?.connectionId || conn?.connectionId,
// The gateway OS owns file-URI conversion, including drive letters and UNC hosts.
path,
- profile: owner?.profile || conn?.profile,
- // A Docker agent's /workspace is its session's own sandbox.
- ...(sessionId ? { sessionId } : {})
+ profile: via?.profile || conn?.profile,
+ ...(session ? { sessionId } : {})
})
}