Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): use discovered RPC endpoint for active sessions
Josué555a5f59cb25
diff --git a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.tsindex 9897b9233..91b600459 100644--- a/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts+++ b/desktop-app/src/__tests__/appService.runtimeConfigResolution.test.ts@@ -52,7 +52,7 @@ describe('AppService runtime config discovery ownership', () => {)})- it('defers late RPC discovery until logout and the next login boundary', async () => {+ it('uses late RPC discovery for the active session without rebinding its durable identity', async () => {const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()await runtimeConfig.saveDesktopRuntimeConfig({externalRestApiBaseUrl: restA,@@ -76,6 +76,7 @@ describe('AppService runtime config discovery ownership', () => {health: ReturnType<typeof vi.fn>}rpcClient: { health: ReturnType<typeof vi.fn> }+ getEffectiveRpcProxyBaseUrl: () => stringgetDependenciesHealth: () => Promise<unknown>getChatDeletionFenceAuthority: () => {authorityScope: { environmentKey: string }@@ -102,10 +103,14 @@ describe('AppService runtime config discovery ownership', () => {restOnlyEnvKey)+ await app.getDependenciesHealth()+ await app.getDependenciesHealth()await app.getDependenciesHealth()expect(runtimeConfig.getDesktopRuntimeConfigState().envKey).toBe(restOnlyEnvKey)expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('')+ expect(app.getEffectiveRpcProxyBaseUrl()).toBe('https://rpc-discovered.example.test')+ expect(getDesktopEnvironment).toHaveBeenCalledTimes(2)expect(service.tokenStore.setSessionToken).toHaveBeenCalledTimes(1)expect(vi.mocked(bindChatStoreForUser)).toHaveBeenCalledTimes(activeBindingCount)expect(app.getChatDeletionFenceAuthority().authorityScope.environmentKey).toBe(restOnlyEnvKey)@@ -210,6 +215,99 @@ describe('AppService runtime config discovery ownership', () => {expect(app.gfsScopeIdentity).toBeNull()})+ it('commits a restore-pending discovery before an interactive login captures its binding', async () => {+ const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: '',+ appName: 'Environment A',+ })+ const restOnlyEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ const app = service as unknown as {+ authClient: {+ getDesktopEnvironment: ReturnType<typeof vi.fn>+ googleLogin: ReturnType<typeof vi.fn>+ }+ restoreSavedSessionInFlight: Promise<unknown>+ restoreSavedSessionReservationStarted: boolean+ pendingRuntimeConfigDiscovery:+ | (DesktopEnvironmentDiscovery & { profileId: string | null })+ | null+ }+ app.restoreSavedSessionInFlight = Promise.resolve({ authenticated: false })+ app.restoreSavedSessionReservationStarted = true+ app.pendingRuntimeConfigDiscovery = {+ profileId: runtimeConfig.getDesktopRuntimeConfigState().activeOptionId,+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ }+ app.authClient = {+ getDesktopEnvironment: vi.fn().mockResolvedValue({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ }),+ googleLogin: vi.fn().mockResolvedValue(testLoginResult('session-token-a', testSessionMe())),+ }++ await service.googleLogin('google-token-a')++ const rpcAwareEnvKey = runtimeConfig.getDesktopRuntimeConfigState().envKey+ expect(rpcAwareEnvKey).not.toBe(restOnlyEnvKey)+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('https://rpc-discovered.example.test')+ expect(service.tokenStore.setSessionToken).toHaveBeenCalledWith(+ 'session-token-a',+ rpcAwareEnvKey+ )+ })++ it('discards a stale effective endpoint when a different REST-only profile is selected', async () => {+ const { service, runtimeConfig, restA, restB } = await createNativeCommitTestHarness()+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: '',+ appName: 'Environment A',+ })+ await runtimeConfig.saveDesktopRuntimeConfig({+ externalRestApiBaseUrl: restB,+ rpcProxyBaseUrl: '',+ appName: 'Environment B',+ })+ const optionA = runtimeConfig+ .getDesktopRuntimeConfigState()+ .options.find(option => option.externalRestApiBaseUrl === restA)+ const optionB = runtimeConfig+ .getDesktopRuntimeConfigState()+ .options.find(option => option.externalRestApiBaseUrl === restB)+ if (!optionA || !optionB) throw new Error('test runtime profiles were not created')+ await runtimeConfig.selectDesktopRuntimeConfigOption(optionA.id)+ const app = service as unknown as {+ effectiveRuntimeRpcEndpoint:+ | (DesktopEnvironmentDiscovery & { profileId: string | null })+ | null+ pendingRuntimeConfigDiscovery:+ | (DesktopEnvironmentDiscovery & { profileId: string | null })+ | null+ getEffectiveRpcProxyBaseUrl: () => string+ }+ app.effectiveRuntimeRpcEndpoint = {+ profileId: optionA.id,+ externalRestApiBaseUrl: restA,+ rpcProxyBaseUrl: 'https://rpc-discovered.example.test',+ appName: 'Environment A',+ }+ app.pendingRuntimeConfigDiscovery = app.effectiveRuntimeRpcEndpoint++ await service.selectRuntimeConfig(optionB.id)++ expect(runtimeConfig.config.externalRestApiBaseUrl).toBe(restB)+ expect(runtimeConfig.config.rpcProxyBaseUrl).toBe('')+ expect(app.getEffectiveRpcProxyBaseUrl()).toBe('')+ expect(app.effectiveRuntimeRpcEndpoint).toBeNull()+ expect(app.pendingRuntimeConfigDiscovery).toBeNull()+ })+it('shares a pending discovery for the same profile and REST endpoint', async () => {const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()await runtimeConfig.saveDesktopRuntimeConfig({diff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.tsindex a1183212c..a64c3a389 100644--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { ApiError } from '../httpClient.js'import { RpcProxyClient, SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'-// Mock the config module so the module-level url() helper uses a fixed base URL+// Mock the config module so default clients use a fixed persisted base URL.vi.mock('../config.js', () => ({config: {rpcProxyBaseUrl: 'http://proxy',@@ -13,6 +13,26 @@ vi.mock('../config.js', () => ({},}))+describe('RpcProxyClient endpoint provider', () => {+ it('uses its supplied endpoint provider instead of the persisted configuration', async () => {+ const client = new RpcProxyClient(() => 'https://effective-rpc.example.test/')+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ status: 'ok' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ )+ vi.stubGlobal('fetch', fetchMock)++ await expect(client.health()).resolves.toEqual({ status: 'ok' })++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://effective-rpc.example.test/health',+ expect.any(Object)+ )+ })+})+describe('RpcProxyClient.listSessions', () => {let client: RpcProxyClientdiff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 604875fc1..3bc44d093 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -107,6 +107,13 @@ const HOST_WAKE_SCOPE: RpcScope = 'host:wake:write'const PROFILE_UI_BASE_URL_ORIGIN_ERROR ='PROFILE_UI_BASE_URL must be an origin URL with a root pathname and no search parameters'+type RuntimeConfigDiscovery = {+ profileId: string | null+ externalRestApiBaseUrl: string+ rpcProxyBaseUrl: string+ appName: string+}+function parseEntityChangeRetryAfterMs(value: string | undefined,nowMs = Date.now()@@ -874,7 +881,7 @@ export interface AppServiceOptions {export class AppService {private readonly authClient = new AuthClient()private readonly memberRegistrationServiceClient = new MemberRegistrationServiceClient()- private readonly rpcClient = new RpcProxyClient()+ private readonly rpcClient = new RpcProxyClient(() => this.getEffectiveRpcProxyBaseUrl())private readonly sharedFilesClient = new SharedFilesClient()private readonly gfsClient = new GfsClient({get baseUrl() {@@ -894,12 +901,8 @@ export class AppService {private restoreSavedSessionInFlight: Promise<SessionState> | null = nullprivate restoreSavedSessionReservationStarted = falseprivate runtimeConfigResolutionInFlight = new Map<string, { promise: Promise<void> }>()- private pendingRuntimeConfigDiscovery: {- profileId: string | null- externalRestApiBaseUrl: string- rpcProxyBaseUrl: string- appName: string- } | null = null+ private effectiveRuntimeRpcEndpoint: RuntimeConfigDiscovery | null = null+ private pendingRuntimeConfigDiscovery: RuntimeConfigDiscovery | null = nullprivate savedSessionRestoreAttemptedEnvKey: string | null = nullprivate savedSessionRestoreAttemptedAtMs = 0private interactiveLoginAttempts = 0@@ -1121,6 +1124,57 @@ export class AppService {}}+ private runtimeConfigDiscoveryMatchesCurrentBinding(discovery: RuntimeConfigDiscovery): boolean {+ const currentBinding = this.captureAuthEnvironmentBinding()+ return (+ currentBinding.profileId === discovery.profileId &&+ sameDesktopRestEndpoint(currentBinding.restBaseUrl, discovery.externalRestApiBaseUrl)+ )+ }++ private getEffectiveRpcProxyBaseUrl(): string {+ const effectiveEndpoint = this.effectiveRuntimeRpcEndpoint+ if (effectiveEndpoint && this.runtimeConfigDiscoveryMatchesCurrentBinding(effectiveEndpoint)) {+ return effectiveEndpoint.rpcProxyBaseUrl+ }+ return config.rpcProxyBaseUrl+ }++ /** Caller must hold the native auth/environment commit owner. */+ private setEffectiveRuntimeRpcEndpoint(discovery: RuntimeConfigDiscovery): void {+ const previousEndpoint = this.getEffectiveRpcProxyBaseUrl()+ this.effectiveRuntimeRpcEndpoint = discovery+ if (previousEndpoint !== discovery.rpcProxyBaseUrl) this.rpcTokenManager.clear()+ }++ /** Caller must hold the native auth/environment commit owner. */+ private clearEffectiveRuntimeRpcEndpoint(): void {+ const effectiveEndpoint = this.effectiveRuntimeRpcEndpoint+ if (!effectiveEndpoint) return+ this.effectiveRuntimeRpcEndpoint = null+ if (effectiveEndpoint.rpcProxyBaseUrl !== config.rpcProxyBaseUrl) this.rpcTokenManager.clear()+ }++ /** Caller must hold the native auth/environment commit owner. */+ private discardRuntimeConfigDiscoveryOutsideCurrentBinding(): void {+ if (+ this.pendingRuntimeConfigDiscovery &&+ !this.runtimeConfigDiscoveryMatchesCurrentBinding(this.pendingRuntimeConfigDiscovery)+ ) {+ this.pendingRuntimeConfigDiscovery = null+ }+ if (+ this.effectiveRuntimeRpcEndpoint &&+ !this.runtimeConfigDiscoveryMatchesCurrentBinding(this.effectiveRuntimeRpcEndpoint)+ ) {+ this.clearEffectiveRuntimeRpcEndpoint()+ }+ if (config.rpcProxyBaseUrl?.trim()) {+ this.pendingRuntimeConfigDiscovery = null+ this.clearEffectiveRuntimeRpcEndpoint()+ }+ }+getChatDeletionFenceAuthority(): {authorityScope: ChatAuthorityScopesessionGeneration: number@@ -1991,11 +2045,13 @@ export class AppService {try {await operation()this.assertSessionGeneration(transitionGeneration)+ this.discardRuntimeConfigDiscoveryOutsideCurrentBinding()} catch (error) {const environmentUnchanged =getActiveEnvKey() === oldEnvKey &&normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl) === oldBaseUrlif (!environmentUnchanged) {+ this.discardRuntimeConfigDiscoveryOutsideCurrentBinding()this.clearAuthenticatedSessionState()await this.tokenStore.clearSessionToken(oldEnvKey, { legacyEnvKeys: oldLegacyEnvKeys })@@ -2074,6 +2130,7 @@ export class AppService {const transitionGeneration = this.sessionGenerationawait selectDesktopRuntimeConfigOption(optionId)this.assertSessionGeneration(transitionGeneration)+ this.discardRuntimeConfigDiscoveryOutsideCurrentBinding()this.sessionGeneration += 1} else {await this.applyRuntimeEnvironmentChange(@@ -2109,8 +2166,10 @@ export class AppService {nextEnvKey === getActiveEnvKey() &&normalizeDesktopUploadBaseUrl(next.externalRestApiBaseUrl) ===normalizeDesktopUploadBaseUrl(config.externalRestApiBaseUrl)- if (sameUploadBoundary) await saveDesktopRuntimeConfig(next)- else await this.applyRuntimeEnvironmentChange(() => saveDesktopRuntimeConfig(next))+ if (sameUploadBoundary) {+ await saveDesktopRuntimeConfig(next)+ this.discardRuntimeConfigDiscoveryOutsideCurrentBinding()+ } else await this.applyRuntimeEnvironmentChange(() => saveDesktopRuntimeConfig(next))})await this.resolveRuntimeConfigIfNeeded().catch(() => undefined)return getDesktopRuntimeConfigState()@@ -2455,6 +2514,21 @@ export class AppService {const request = await this.withNativeAuthEnvironmentCommit(async () => {hydrateDesktopRuntimeConfig()if (!isDesktopRuntimeConfigured() || config.rpcProxyBaseUrl?.trim()) return null+ if (+ this.pendingRuntimeConfigDiscovery &&+ this.interactiveLoginAttempts > 0 &&+ !this.sessionToken &&+ !this.me+ ) {+ await this.applyRuntimeConfigDiscovery(this.pendingRuntimeConfigDiscovery)+ }+ if (config.rpcProxyBaseUrl?.trim()) return null+ if (+ this.effectiveRuntimeRpcEndpoint &&+ this.runtimeConfigDiscoveryMatchesCurrentBinding(this.effectiveRuntimeRpcEndpoint)+ ) {+ return null+ }return {externalRestApiBaseUrl: canonicalizeDesktopRestEndpoint(config.externalRestApiBaseUrl),appName: config.appName,@@ -2511,19 +2585,10 @@ export class AppService {}/** Caller must hold the native auth/environment commit owner. */- private async applyRuntimeConfigDiscovery(discovery: {- profileId: string | null- externalRestApiBaseUrl: string- rpcProxyBaseUrl: string- appName: string- }): Promise<void> {+ private async applyRuntimeConfigDiscovery(discovery: RuntimeConfigDiscovery): Promise<void> {this.pendingRuntimeConfigDiscovery = discoveryhydrateDesktopRuntimeConfig()- const currentBinding = this.captureAuthEnvironmentBinding()- if (- currentBinding.profileId !== discovery.profileId ||- !sameDesktopRestEndpoint(currentBinding.restBaseUrl, discovery.externalRestApiBaseUrl)- ) {+ if (!this.runtimeConfigDiscoveryMatchesCurrentBinding(discovery)) {if (this.pendingRuntimeConfigDiscovery === discovery) {this.pendingRuntimeConfigDiscovery = null}@@ -2533,12 +2598,17 @@ export class AppService {if (this.pendingRuntimeConfigDiscovery === discovery) {this.pendingRuntimeConfigDiscovery = null}+ this.clearEffectiveRuntimeRpcEndpoint()return}const restoreHasReservedEnvironment =this.restoreSavedSessionInFlight !== null && this.restoreSavedSessionReservationStarted- if (this.sessionToken || this.me || restoreHasReservedEnvironment) {+ if (this.sessionToken || this.me) {+ this.setEffectiveRuntimeRpcEndpoint(discovery)+ return+ }+ if (restoreHasReservedEnvironment && this.interactiveLoginAttempts === 0) {return}@@ -2554,6 +2624,7 @@ export class AppService {if (this.pendingRuntimeConfigDiscovery === discovery) {this.pendingRuntimeConfigDiscovery = null}+ this.clearEffectiveRuntimeRpcEndpoint()}/** Caller must hold the native auth/environment commit owner. */diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 6bdae4ae8..2a49e7dee 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -437,8 +437,8 @@ async function parseApprovalDecisionResponse(response: Response): Promise<Approv// embed's click without any answer for a minute.export const SANDBOX_UI_MINT_TIMEOUT_MS = 15_000-function url(path: string): string {- return `${config.rpcProxyBaseUrl.replace(/\/+$/, '')}${path}`+function rpcProxyUrl(baseUrl: string, path: string): string {+ return `${baseUrl.replace(/\/+$/, '')}${path}`}/**@@ -502,12 +502,18 @@ function hostAccessDenialError(status: number, body: string): ApiError | null {}export class RpcProxyClient {+ constructor(private readonly getRpcProxyBaseUrl: () => string = () => config.rpcProxyBaseUrl) {}++ private url(path: string): string {+ return rpcProxyUrl(this.getRpcProxyBaseUrl(), path)+ }+async health(): Promise<{ status: string }> {- return requestJson<{ status: string }>('GET', url('/health'))+ return requestJson<{ status: string }>('GET', this.url('/health'))}async listServers(rpcAccessToken: string): Promise<RpcAllowedServersResult> {- return requestJson<RpcAllowedServersResult>('GET', url('/api/v1/rpc/servers'), {+ return requestJson<RpcAllowedServersResult>('GET', this.url('/api/v1/rpc/servers'), {token: rpcAccessToken,})}@@ -521,7 +527,7 @@ export class RpcProxyClient {* `AppService.shouldRefreshRpcToken` can drive the retry-after-refresh.*/async getConnectors(rpcAccessToken: string): Promise<RpcConnectorsResult> {- return requestJson<RpcConnectorsResult>('GET', url('/api/v1/rpc/connectors'), {+ return requestJson<RpcConnectorsResult>('GET', this.url('/api/v1/rpc/connectors'), {token: rpcAccessToken,})}@@ -541,7 +547,7 @@ export class RpcProxyClient {): Promise<void> {await requestJson<unknown>('DELETE',- url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/grant`),+ this.url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/grant`),{token: rpcAccessToken,// Body is optional; only send `contextId` when present. `userId` is NEVER@@ -560,7 +566,7 @@ export class RpcProxyClient {const query = options?.async ? '?async=true' : ''return requestJson<HostMessageResponse>('POST',- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/messages${query}`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/messages${query}`),{token: rpcAccessToken,body: payload,@@ -575,7 +581,7 @@ export class RpcProxyClient {): Promise<HostMessageResponse> {return requestJson<HostMessageResponse>('GET',- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/tasks/${encodeURIComponent(taskId)}/result`),{ token: rpcAccessToken }@@ -585,7 +591,7 @@ export class RpcProxyClient {async getHostStatus(rpcAccessToken: string, hostRef: string): Promise<HostRuntimeStatus> {return requestJson<HostRuntimeStatus>('GET',- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/status`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/status`),{token: rpcAccessToken,}@@ -602,10 +608,13 @@ export class RpcProxyClient {* Anything else (401/403/404/5xx) is an error for the caller to log.*/async prewarmHost(rpcAccessToken: string, hostRef: string): Promise<{ status: string }> {- const response = await fetch(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/wake`), {- method: 'POST',- headers: { authorization: `Bearer ${rpcAccessToken}` },- })+ const response = await fetch(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/wake`),+ {+ method: 'POST',+ headers: { authorization: `Bearer ${rpcAccessToken}` },+ }+ )if (response.status === 200 || response.status === 202 || response.status === 409) {const payload = (await response.json()) as { status?: string }const status = payload?.status@@ -629,7 +638,7 @@ export class RpcProxyClient {async getHostHealth(rpcAccessToken: string, hostRef: string): Promise<HostRuntimeHealth> {return requestJson<HostRuntimeHealth>('GET',- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/health`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/health`),{token: rpcAccessToken,}@@ -647,7 +656,9 @@ export class RpcProxyClient {const query = params.toString()return requestJson<HostActivitySnapshot>('GET',- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/activity${query ? `?${query}` : ''}`),+ this.url(+ `/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/activity${query ? `?${query}` : ''}`+ ),{ token: rpcAccessToken })}@@ -660,7 +671,7 @@ export class RpcProxyClient {* mint — this list is purely the picker payload.*/async listSandboxUiApps(rpcAccessToken: string): Promise<{ apps: SandboxUiApp[] }> {- return requestJson<{ apps: SandboxUiApp[] }>('GET', url('/api/v1/sandbox-ui/apps'), {+ return requestJson<{ apps: SandboxUiApp[] }>('GET', this.url('/api/v1/sandbox-ui/apps'), {token: rpcAccessToken,})}@@ -683,7 +694,7 @@ export class RpcProxyClient {recipeName: string): Promise<{ setCookie: string }> {const response = await fetch(- url(+ this.url(`/api/v1/sandbox-ui/${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/session`),{@@ -720,7 +731,7 @@ export class RpcProxyClient {background = false): Promise<{ authorizeUrl: string }> {const response = await fetch(- url(+ this.url(`/api/v1/sandbox-ui/${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/oauth/authorize-url`),{@@ -771,7 +782,7 @@ export class RpcProxyClient {contextId?: string): Promise<{ authorizeUrl: string }> {const response = await fetch(- url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/authorize-url`),+ this.url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/authorize-url`),{method: 'POST',headers: {@@ -810,7 +821,7 @@ export class RpcProxyClient {// falsely time out during a long, semantically-silent tool run.onKeepalive?: () => void): Promise<void> {- const response = await fetch(url(path), {+ const response = await fetch(this.url(path), {method: 'GET',headers: {accept: 'text/event-stream',@@ -929,7 +940,7 @@ export class RpcProxyClient {toolCallId: string): Promise<ApprovalDecisionResult> {const response = await fetch(- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/approvals/approve`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/approvals/approve`),{method: 'POST',headers: {@@ -961,7 +972,7 @@ export class RpcProxyClient {reason: string): Promise<ApprovalDecisionResult> {const response = await fetch(- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/approvals/deny`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/approvals/deny`),{method: 'POST',headers: {@@ -985,7 +996,7 @@ export class RpcProxyClient {async cancelTask(rpcToken: string, hostRef: string, taskId: string): Promise<void> {const response = await fetch(- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/tasks/${encodeURIComponent(taskId)}/cancel`),{@@ -1014,7 +1025,7 @@ export class RpcProxyClient {artifacts: Array<{ name: string; format: string; sizeBytes: number; createdAt: string }>}> {const response = await fetch(- url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/artifacts`),+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/artifacts`),{headers: { authorization: `Bearer ${rpcToken}` },signal: withTimeout(),@@ -1035,7 +1046,7 @@ export class RpcProxyClient {async downloadArtifact(rpcToken: string, hostRef: string, filename: string): Promise<Buffer> {const response = await fetch(- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/artifacts/${encodeURIComponent(filename)}/download`),{@@ -1055,7 +1066,9 @@ export class RpcProxyClient {query: SessionsListQuery = {}): Promise<SessionsListResult> {assertSafeRouteSegment('hostRef', hostRef)- const requestUrl = new URL(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`))+ const requestUrl = new URL(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`)+ )if (query.agent) requestUrl.searchParams.set('agent', query.agent)if (query.limit !== undefined) requestUrl.searchParams.set('limit', String(query.limit))if (query.cursor) requestUrl.searchParams.set('cursor', query.cursor)@@ -1087,7 +1100,7 @@ export class RpcProxyClient {assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })assertSafeRouteSegment('chatId', chatId)const requestUrl = new URL(- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`))@@ -1142,7 +1155,7 @@ export class RpcProxyClient {assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })assertSafeRouteSegment('chatId', chatId)const response = await fetch(- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/context-breakdown`),{ headers: { authorization: `Bearer ${rpcToken}` }, signal: withTimeout() }@@ -1186,7 +1199,7 @@ export class RpcProxyClient {const modelsPath = trimmedChatId? `/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/models?chatId=${encodeURIComponent(trimmedChatId)}`: `/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/models`- const response = await fetch(url(modelsPath), {+ const response = await fetch(this.url(modelsPath), {headers: { authorization: `Bearer ${rpcToken}` },signal: withTimeout(),})@@ -1220,20 +1233,23 @@ export class RpcProxyClient {model: string,expectedRevision?: number): Promise<SetHostModelResult> {- const response = await fetch(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/model`), {- method: 'POST',- headers: {- authorization: `Bearer ${rpcToken}`,- 'content-type': 'application/json',- },- // `expectedRevision` is omitted unless the host projected a revision- // (issue #654 CAS), so an older host keeps receiving the exact body it- // accepts today.- body: JSON.stringify(- expectedRevision === undefined ? { chatId, model } : { chatId, model, expectedRevision }- ),- signal: withTimeout(),- })+ const response = await fetch(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/model`),+ {+ method: 'POST',+ headers: {+ authorization: `Bearer ${rpcToken}`,+ 'content-type': 'application/json',+ },+ // `expectedRevision` is omitted unless the host projected a revision+ // (issue #654 CAS), so an older host keeps receiving the exact body it+ // accepts today.+ body: JSON.stringify(+ expectedRevision === undefined ? { chatId, model } : { chatId, model, expectedRevision }+ ),+ signal: withTimeout(),+ }+ )if (!response.ok) {const body = await readErrorBody(response)// Disambiguate the two failure sources by the body's `error` code — NOT@@ -1288,7 +1304,7 @@ export class RpcProxyClient {assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })assertSafeRouteSegment('chatId', chatId)const response = await fetch(- url(+ this.url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/name`),{@@ -1320,7 +1336,7 @@ export class RpcProxyClient {): Promise<{ hostRef: string; status: string; message?: string }> {return requestJson<{ hostRef: string; status: string; message?: string }>('GET',- url(`/api/v1/desktop/${encodeURIComponent(hostRef)}`),+ this.url(`/api/v1/desktop/${encodeURIComponent(hostRef)}`),{token: rpcAccessToken,}@@ -1336,7 +1352,7 @@ export class RpcProxyClient {rpcAccessToken: string,hostRef: string): Promise<{ ok: true; hostRef: string; setCookie: string[] }> {- const res = await fetch(url(`/api/v1/desktop/${encodeURIComponent(hostRef)}/session`), {+ const res = await fetch(this.url(`/api/v1/desktop/${encodeURIComponent(hostRef)}/session`), {method: 'POST',headers: {authorization: `Bearer ${rpcAccessToken}`,