π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(llm-relay): browser executor for one-shot relayed calls (#20454)
Arvin Xu53761bad629e
diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex 34a5b85a28c..cfbc0b8be9f 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -1,7 +1,7 @@import superjson from 'superjson';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { lambdaClient } from './lambda';+import { lambdaClient, withLlmRelay } from './lambda';vi.mock('@/const/version', () => ({ isDesktop: false }));vi.mock('@/services/_auth', () => ({ createHeaderWithAuth: async () => ({}) }));@@ -151,6 +151,31 @@ describe('lambdaClient transport lanes', () => {expect(tokenUrl).not.toContain('batch=1');expect(tokenUrl).not.toContain('agent.getAgentConfigById');});++ // One-shot relay: the server reads the channel this tab subscribed from the+ // request headers, so the call carries its own headers and never shares a+ // batch with calls that must not be relayed.+ it('sends a call with one-shot relay headers unbatched, with its headers', async () => {+ fetchMock.mockImplementation(respondByLane);+ const relay = {+ headers: { 'x-lobe-client-id': 'tab-1', 'x-lobe-llm-relay-channel': 'llmcall:u:abcdefgh' },+ };++ await Promise.all([+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }, withLlmRelay(relay)),+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_other' }),+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(2);+ const relayed = fetchMock.mock.calls.find(([, init]) =>+ new Headers((init as RequestInit).headers).has('x-lobe-llm-relay-channel'),+ );+ expect(relayed).toBeDefined();+ expect(String(relayed![0])).not.toContain('batch=1');+ const headers = new Headers((relayed![1] as RequestInit).headers);+ expect(headers.get('x-lobe-llm-relay-channel')).toBe('llmcall:u:abcdefgh');+ expect(headers.get('x-lobe-client-id')).toBe('tab-1');+ });});describe('lambdaClient unreadable response handling', () => {diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 034444d015e..aa7ec3fb59c 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -241,8 +241,22 @@ const LARGE_INPUT_QUERY_PROCEDURES = new Set(['message.getToolResultPayloads',]);+/**+ * Operation context key for the one-shot LLM relay headers (`withLlmRelay`):+ * the tab subscribed a gateway channel for this call's LLM requests, and the+ * server must see which. Per call, so such a call never shares a batch.+ */+export const LLM_RELAY_HEADERS_CONTEXT_KEY = 'llmRelayHeaders';++const getLlmRelayHeaders = (op: { context: Record<string, unknown> }) =>+ op.context?.[LLM_RELAY_HEADERS_CONTEXT_KEY] as Record<string, string> | undefined;++/** TRPC call options carrying a one-shot relay's headers; none without a relay. */+export const withLlmRelay = (relay?: { headers: Record<string, string> }) =>+ relay ? { context: { [LLM_RELAY_HEADERS_CONTEXT_KEY]: relay.headers } } : undefined;+// 3. splitLink to conditionally disable batching-const buildHttpLinks = (options: typeof linkOptions) =>+const buildBatchedHttpLinks = (options: typeof linkOptions) =>splitLink({condition: (op) => LARGE_INPUT_QUERY_PROCEDURES.has(op.path),false: splitLink({@@ -260,6 +274,20 @@ const buildHttpLinks = (options: typeof linkOptions) =>true: httpLink({ ...options, methodOverride: 'POST' }),});+const buildHttpLinks = (options: typeof linkOptions) =>+ splitLink({+ condition: (op) => !!getLlmRelayHeaders(op),+ false: buildBatchedHttpLinks(options),+ true: httpLink({+ ...options,+ headers: async ({ op }) => ({+ ...(await options.headers()),+ ...getLlmRelayHeaders(op),+ }),+ methodOverride: 'POST',+ }),+ });+const customSplitLink = splitLink({condition: (op) => op.type === 'subscription',false: buildHttpLinks(linkOptions),diff --git a/src/services/llmRelay/channelSubscription.test.ts b/src/services/llmRelay/channelSubscription.test.tsnew file mode 100644index 00000000000..d94af77f1c9--- /dev/null+++ b/src/services/llmRelay/channelSubscription.test.ts@@ -0,0 +1,111 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getGatewayMux,+ markGatewayMuxUnavailable,+} from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';++import { subscribeLlmRelayChannel } from './channelSubscription';++vi.mock('@/helpers/gatewayProtocol', () => ({ canUseGatewayProtocolV2: () => true }));+vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { issueGatewayUserToken: vi.fn(async () => ({ token: 'jwt' })) },+}));++const v1Clients = vi.hoisted(() => [] as any[]);+vi.mock('@lobechat/agent-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ AgentStreamClient: vi.fn(function (this: any, options: unknown) {+ const listeners: Record<string, ((...args: any[]) => void)[]> = {};+ this.options = options;+ this.emit = (event: string, ...args: any[]) => listeners[event]?.forEach((fn) => fn(...args));+ this.on = vi.fn((event: string, fn: (...args: any[]) => void) => {+ (listeners[event] ??= []).push(fn);+ });+ this.connect = vi.fn();+ this.disconnect = vi.fn();+ v1Clients.push(this);+ }),+}));+vi.mock('@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry', () => ({+ getGatewayMux: vi.fn(),+ isGatewayMuxUnavailable: () => false,+ markGatewayMuxUnavailable: vi.fn(),+}));++const createMux = () => {+ const listeners: Record<string, ((...args: any[]) => void)[]> = {};+ return {+ emit: (event: string, ...args: any[]) => listeners[event]?.forEach((fn) => fn(...args)),+ listeners,+ on: vi.fn((event: string, fn: (...args: any[]) => void) => {+ (listeners[event] ??= []).push(fn);+ return () => {+ listeners[event] = listeners[event].filter((other) => other !== fn);+ };+ }),+ subscribe: vi.fn(() => ({ on: vi.fn(), unsubscribe: vi.fn() })),+ };+};++describe('subscribeLlmRelayChannel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ v1Clients.length = 0;+ });++ // A tab that never started a gateway run owns a mux nobody watches: the mux+ // only gives up on protocol v2 (and lets later calls use v1) when someone+ // listens for `unavailable`.+ it('marks protocol v2 unavailable for this gateway when the mux gives up, once per mux', async () => {+ const mux = createMux();+ vi.mocked(getGatewayMux).mockReturnValue(mux as any);++ (await subscribeLlmRelayChannel('https://gw', 'llmcall:u:1', vi.fn())).close();+ (await subscribeLlmRelayChannel('https://gw', 'llmcall:u:2', vi.fn())).close();+ expect(mux.listeners.unavailable).toHaveLength(1);++ mux.emit('unavailable', 'dial_failed');+ expect(markGatewayMuxUnavailable).toHaveBeenCalledWith({ gatewayUrl: 'https://gw' });+ });++ // The mux leaves its subscriptions for their owner to hand off: the channel+ // a request is waiting on moves to a v1 socket, or that request would go+ // out with nobody subscribed.+ it('moves the channel in flight to a v1 socket when the mux gives up', async () => {+ const mux = createMux();+ const v2Subscription = { on: vi.fn(), unsubscribe: vi.fn() };+ mux.subscribe.mockReturnValue(v2Subscription);+ vi.mocked(getGatewayMux).mockReturnValue(mux as any);+ const onEvent = vi.fn();++ const subscription = await subscribeLlmRelayChannel('https://gw', 'llmcall:u:1', onEvent);+ let ready = false;+ void subscription.ready.then(() => (ready = true));++ mux.emit('unavailable', 'dial_failed');+ await vi.waitFor(() => expect(v1Clients).toHaveLength(1));+ expect(v2Subscription.unsubscribe).toHaveBeenCalled();+ expect(v1Clients[0].options).toMatchObject({ operationId: 'llmcall:u:1', token: 'jwt' });+ expect(v1Clients[0].connect).toHaveBeenCalled();++ v1Clients[0].emit('connected');+ await vi.waitFor(() => expect(ready).toBe(true));+ v1Clients[0].emit('agent_event', { type: 'llm_execute' });+ expect(onEvent).toHaveBeenCalledWith({ type: 'llm_execute' });++ subscription.close();+ expect(v1Clients[0].disconnect).toHaveBeenCalled();+ });++ it('does not hand off a channel that was already released', async () => {+ const mux = createMux();+ vi.mocked(getGatewayMux).mockReturnValue(mux as any);++ (await subscribeLlmRelayChannel('https://gw', 'llmcall:u:1', vi.fn())).close();+ mux.emit('unavailable', 'dial_failed');+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(v1Clients).toHaveLength(0);+ });+});diff --git a/src/services/llmRelay/channelSubscription.ts b/src/services/llmRelay/channelSubscription.tsnew file mode 100644index 00000000000..94d2f5fd01e--- /dev/null+++ b/src/services/llmRelay/channelSubscription.ts@@ -0,0 +1,103 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { AgentStreamClient } from '@lobechat/agent-gateway-client';++import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';+import { aiAgentService } from '@/services/aiAgent';+import {+ getGatewayMux,+ isGatewayMuxUnavailable,+ markGatewayMuxUnavailable,+} from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';++import { getLlmRelayClientId } from './clientId';+import type { OneShotChannelSubscription } from './oneShot';++/**+ * Muxes this module watches for `unavailable`. A tab that never started a+ * gateway run owns a mux no transport watches, and a mux only gives up on+ * protocol v2 when someone listens; marking it here sends later one-shot+ * calls to v1.+ */+const watchedMuxes = new WeakSet<object>();++/** Subscribe on a v1 socket of its own; `ready` once the socket authenticated. */+const subscribeV1 = async (+ gatewayUrl: string,+ channel: string,+ onEvent: (event: AgentStreamEvent) => void,+): Promise<OneShotChannelSubscription> => {+ const { token } = await aiAgentService.issueGatewayUserToken();+ const client = new AgentStreamClient({+ clientId: getLlmRelayClientId(),+ gatewayUrl,+ operationId: channel,+ token,+ });+ client.on('agent_event', onEvent);+ const ready = new Promise<void>((resolve) => {+ client.on('connected', () => resolve());+ });+ client.connect();+ return { close: () => client.disconnect(), ready };+};++/**+ * Subscribe this tab to a one-shot relay channel as its executor: on the+ * page-wide multiplexed socket (protocol v2) when this tab uses it, else on a+ * v1 socket of its own (self-hosted Go gateway, v2 unavailable).+ *+ * `ready` resolves once the gateway has the subscription β v2 answers+ * `resume_complete` (pending: the server has not opened the channel yet), v1+ * authenticates the socket β so the server's dispatch cannot outrun it. A mux+ * that gives up on v2 while the channel is live hands it to a v1 socket.+ */+export const subscribeLlmRelayChannel = async (+ gatewayUrl: string,+ channel: string,+ onEvent: (event: AgentStreamEvent) => void,+): Promise<OneShotChannelSubscription> => {+ const identity = { gatewayUrl };++ if (!canUseGatewayProtocolV2() || isGatewayMuxUnavailable(identity)) {+ return subscribeV1(gatewayUrl, channel, onEvent);+ }++ const mux = getGatewayMux(identity);+ if (!watchedMuxes.has(mux)) {+ watchedMuxes.add(mux);+ mux.on('unavailable', () => markGatewayMuxUnavailable(identity));+ }++ const subscription = mux.subscribe(channel, { executor: true });+ subscription.on('agent_event', onEvent);++ let closed = false;+ let release = () => subscription.unsubscribe();+ let stopWatching = () => {};+ const ready = new Promise<void>((resolve) => {+ subscription.on('resume_complete', () => resolve());+ // The mux leaves its subscriptions for their owner to move.+ stopWatching = mux.on('unavailable', () => {+ stopWatching();+ subscription.unsubscribe();+ subscribeV1(gatewayUrl, channel, onEvent).then(+ (fallback) => {+ if (closed) return fallback.close();+ release = fallback.close;+ void fallback.ready.then(resolve);+ },+ // No v1 either: the request goes ahead and the server reports it.+ () => resolve(),+ );+ });+ });++ return {+ close: () => {+ closed = true;+ stopWatching();+ release();+ },+ ready,+ };+};diff --git a/src/services/llmRelay/executor.test.ts b/src/services/llmRelay/executor.test.tsindex d235ed09fd8..a6ca5fe04ca 100644--- a/src/services/llmRelay/executor.test.ts+++ b/src/services/llmRelay/executor.test.ts@@ -302,6 +302,156 @@ describe('LlmRelayExecutor', () => {});});+describe('LlmRelayExecutor non-chat methods (one-shot relay)', () => {+ const run = async (data: LlmExecuteData, runtime: RelayRuntime) => {+ const server = createServer();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => runtime,+ fetch: server.fetch,+ });+ await executor.execute(data);+ return server;+ };++ const resultOf = (batches: LlmRelayBatch[]) =>+ JSON.parse(+ batches+ .flatMap((batch) => batch.chunks)+ .filter((chunk) => chunk.type === 'result_part')+ .map((chunk) => chunk.data)+ .join(''),+ );++ it('runs generateObject and uploads its value as JSON parts', async () => {+ const generateObject = vi.fn(async () => ({ title: 'Hello' }));+ const server = await run(callData({ method: 'generateObject' }), {+ chat: vi.fn(),+ generateObject,+ });++ expect(generateObject).toHaveBeenCalledWith(PAYLOAD, expect.anything());+ expect(resultOf(server.batches)).toEqual({ title: 'Hello' });+ expect(server.batches.at(-1)?.final).toEqual({ reason: 'done' });+ });++ // The server reads "no result parts" as `undefined` β what a provider returns+ // for absent structured output β and must not get `null` instead.+ it('uploads no result for an undefined value', async () => {+ const server = await run(callData({ method: 'generateObject' }), {+ chat: vi.fn(),+ generateObject: vi.fn(async () => undefined),+ });++ const parts = server.batches+ .flatMap((batch) => batch.chunks)+ .filter((chunk) => chunk.type === 'result_part');+ expect(parts).toEqual([]);+ expect(server.batches.at(-1)?.final).toEqual({ reason: 'done' });+ });++ // `models()` takes no signal and a local endpoint can accept the connection+ // and stall: a cancel must still settle the call instead of holding it.+ it('settles a cancelled model list even when the provider never answers', async () => {+ const server = createServer();+ const models = vi.fn(() => new Promise<never>(() => {}));+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => ({ chat: vi.fn(), models }),+ fetch: server.fetch,+ });++ const done = executor.execute(callData({ method: 'models' }));+ await waitFor(() => models.mock.calls.length === 1);+ executor.cancel({ callId: 'op-1:0:1', reason: 'interrupted' });+ await done;++ expect(server.batches.at(-1)?.final).toEqual({ reason: 'aborted' });+ expect(executor.isRunning('op-1:0:1')).toBe(false);+ });++ it('never starts the model list when cancelled while the runtime is created', async () => {+ const server = createServer();+ const models = vi.fn(() => new Promise<never>(() => {}));+ let resolveRuntime!: (runtime: RelayRuntime) => void;+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: () => new Promise((resolve) => (resolveRuntime = resolve)),+ fetch: server.fetch,+ });++ const done = executor.execute(callData({ method: 'models' }));+ await waitFor(() => !!resolveRuntime);+ executor.cancel({ callId: 'op-1:0:1', reason: 'interrupted' });+ resolveRuntime({ chat: vi.fn(), models });+ await done;++ expect(models).not.toHaveBeenCalled();+ expect(executor.isRunning('op-1:0:1')).toBe(false);+ });++ it('never starts a model download when cancelled while the runtime is created', async () => {+ const server = createServer();+ const pullModel = vi.fn(async () => new Response(''));+ let resolveRuntime!: (runtime: RelayRuntime) => void;+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: () => new Promise((resolve) => (resolveRuntime = resolve)),+ fetch: server.fetch,+ });++ const done = executor.execute(callData({ method: 'pullModel' }));+ await waitFor(() => !!resolveRuntime);+ executor.cancel({ callId: 'op-1:0:1', reason: 'interrupted' });+ resolveRuntime({ chat: vi.fn(), pullModel });+ await done;++ expect(pullModel).not.toHaveBeenCalled();+ });++ it('splits a large model list across batches under the size cap', async () => {+ const list = Array.from({ length: 3000 }, (_, i) => ({ id: `model-${i}`, displayName: 'x' }));+ const server = await run(callData({ method: 'models' }), {+ chat: vi.fn(),+ models: vi.fn(async () => list),+ });++ expect(resultOf(server.batches)).toEqual(list);+ for (const batch of server.batches)+ expect(JSON.stringify(batch).length).toBeLessThan(256 * 1024);+ });++ it('streams pullModel progress text', async () => {+ const progress = '{"status":"pulling","completed":1,"total":2}\n{"status":"success"}\n';+ const server = await run(callData({ method: 'pullModel' }), {+ chat: vi.fn(),+ pullModel: vi.fn(async () => new Response(progress)),+ });++ const text = server.batches+ .flatMap((batch) => batch.chunks)+ .filter((chunk) => chunk.type === 'progress')+ .map((chunk) => chunk.data)+ .join('');+ expect(text).toBe(progress);+ expect(server.batches.at(-1)?.final).toEqual({ reason: 'done' });+ });++ it('reports a failed method as the final error', async () => {+ const server = await run(callData({ method: 'generateObject' }), {+ chat: vi.fn(),+ generateObject: vi.fn(async () => {+ throw { error: { message: 'model not found' }, errorType: 'OllamaBizError' };+ }),+ });++ expect(server.batches.at(-1)?.final).toMatchObject({+ error: { errorType: 'OllamaBizError', provider: 'ollama' },+ reason: 'error',+ });+ });+});+describe('RelayBatchUploader', () => {it('sends an empty heartbeat batch while the model produces nothing', async () => {vi.useFakeTimers();diff --git a/src/services/llmRelay/executor.ts b/src/services/llmRelay/executor.tsindex 90f1ab462b5..10bac50347d 100644--- a/src/services/llmRelay/executor.ts+++ b/src/services/llmRelay/executor.ts@@ -22,8 +22,14 @@ const SETTLED_CALL_MEMORY = 200;export interface RelayRuntime {chat: (payload: any, options: { signal?: AbortSignal }) => Promise<Response>;+ generateObject?: (payload: any, options: { signal?: AbortSignal }) => Promise<unknown>;+ models?: () => Promise<unknown>;+ pullModel?: (params: any, options: { signal?: AbortSignal }) => Promise<Response | undefined>;}+/** A return value goes up as JSON text in parts of this size, well under the batch cap. */+const RESULT_PART_CHARS = 32 * 1024;+export interface LlmRelayExecutorDeps {clientId?: () => string;/** Build the model runtime from this client's own provider configuration. */@@ -72,6 +78,17 @@ const toRelayError = (error: unknown, provider: string) => {return { error: { message }, errorType: 'ProviderBizError', message, provider };};+/**+ * `promise`, or an abort error once `signal` aborts β for provider calls that+ * take no signal (`models`) and may never answer.+ */+const untilAborted = <T>(promise: Promise<T>, signal: AbortSignal) =>+ new Promise<T>((resolve, reject) => {+ if (signal.aborted) return reject(abortError());+ signal.addEventListener('abort', () => reject(abortError()), { once: true });+ promise.then(resolve, reject);+ });+const sleep = (ms: number, signal: AbortSignal) =>new Promise<void>((resolve, reject) => {if (signal.aborted) return reject(abortError());@@ -229,6 +246,9 @@ export class LlmRelayExecutor {provider: data.provider,runtimeProvider: data.runtimeProvider,});+ const method = data.method ?? 'chat';+ if (method !== 'chat')+ return await this.runMethod(method, runtime, payload, uploader, signal);response = await runtime.chat(payload, { signal });} catch (error) {if (signal.aborted) throw error;@@ -257,6 +277,51 @@ export class LlmRelayExecutor {return { reason: 'done' };}+ /**+ * A non-chat call (one-shot relay): `generateObject` / `models` upload their+ * return value as JSON parts, `pullModel` the provider's progress text.+ */+ private async runMethod(+ method: Exclude<NonNullable<LlmExecuteData['method']>, 'chat'>,+ runtime: RelayRuntime,+ payload: Record<string, unknown>,+ uploader: RelayBatchUploader,+ signal: AbortSignal,+ ): Promise<NonNullable<LlmRelayBatch['final']>> {+ // Cancelled while the runtime was created: never start a call that may not+ // see the abort (a download's listener misses an already-fired event).+ if (signal.aborted) throw abortError();++ if (method === 'pullModel') {+ const response = await runtime.pullModel?.(payload, { signal });+ if (!response) throw new Error('This provider cannot download models');+ if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`);+ if (response.body) {+ const decoder = new TextDecoder();+ const reader = response.body.getReader();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ uploader.push({ data: decoder.decode(value, { stream: true }), type: 'progress' });+ }+ }+ if (signal.aborted) throw abortError();+ return { reason: 'done' };+ }++ const run = method === 'models' ? runtime.models : runtime.generateObject;+ if (!run) throw new Error(`This provider does not support ${method}`);+ const result = await untilAborted(run.call(runtime, payload, { signal }), signal);+ if (signal.aborted) throw abortError();++ // No parts reads as `undefined` on the server, as the direct runtime returns it.+ const json = result === undefined ? '' : JSON.stringify(result);+ for (let i = 0; i < json.length; i += RESULT_PART_CHARS) {+ uploader.push({ data: json.slice(i, i + RESULT_PART_CHARS), type: 'result_part' });+ }+ return { reason: 'done' };+ }+private async fetchPayload(data: LlmExecuteData, signal: AbortSignal) {const doFetch = this.deps.fetch ?? fetch;const response = await doFetch(diff --git a/src/services/llmRelay/index.test.ts b/src/services/llmRelay/index.test.tsindex c7ad88f5e84..8c82968e556 100644--- a/src/services/llmRelay/index.test.ts+++ b/src/services/llmRelay/index.test.ts@@ -1,16 +1,27 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { buildLlmExecutorDeclaration } from './index';+import { buildLlmExecutorDeclaration, oneShotRelay } from './index';const state = vi.hoisted(() => ({aiInfra: {} as Record<string, unknown>,featureFlags: {} as Record<string, unknown>,+ serverConfig: {} as Record<string, unknown>,}));-vi.mock('@/store/aiInfra', () => ({ getAiInfraStoreState: () => state.aiInfra }));+vi.mock('@/store/aiInfra', () => ({+ aiProviderSelectors: {+ isProviderFetchOnClient: (provider: string) => () => provider === 'ollama',+ },+ getAiInfraStoreState: () => state.aiInfra,+}));vi.mock('@/store/serverConfig', () => ({- getServerConfigStoreState: () => ({ featureFlags: state.featureFlags }),+ getServerConfigStoreState: () => ({+ featureFlags: state.featureFlags,+ serverConfig: state.serverConfig,+ }),}));+vi.mock('@/store/user', () => ({ useUserStore: { getState: () => ({}) } }));+vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: { userId: () => 'user-1' } }));vi.mock('./clientId', () => ({ getLlmRelayClientId: () => 'tab-1' }));describe('buildLlmExecutorDeclaration', () => {@@ -37,3 +48,22 @@ describe('buildLlmExecutorDeclaration', () => {expect(buildLlmExecutorDeclaration()).toBeUndefined();});});++describe('oneShotRelay availability', () => {+ beforeEach(() => {+ state.featureFlags = { enableLlmRelay: true };+ state.serverConfig = { agentGatewayUrl: 'https://gw', llmRelayAvailable: true };+ });++ it('relays a device-only provider where the deployment can relay', () => {+ expect(oneShotRelay.needsRelay('ollama')).toBe(true);+ expect(oneShotRelay.needsRelay('openai')).toBe(false);+ });++ // A gateway URL without Redis: the server cannot relay and would call the+ // device-only provider itself, so the browser keeps its own fallback.+ it('keeps the browser fallback where the server cannot relay', () => {+ state.serverConfig = { agentGatewayUrl: 'https://gw', llmRelayAvailable: false };+ expect(oneShotRelay.needsRelay('ollama')).toBe(false);+ });+});diff --git a/src/services/llmRelay/index.ts b/src/services/llmRelay/index.tsindex 125484720e9..382dbffdc49 100644--- a/src/services/llmRelay/index.ts+++ b/src/services/llmRelay/index.ts@@ -2,14 +2,19 @@ import { CLIENT_LLM_WAIT_CAPABILITY, LLM_RELAY_CAPABILITY } from '@lobechat/agenimport type { ExecAgentLlmExecutor } from '@lobechat/types';import { initializeWithClientStore } from '@/services/chat/mecha/clientModelRuntime';-import { getAiInfraStoreState } from '@/store/aiInfra';+import { aiProviderSelectors, getAiInfraStoreState, useAiInfraStore } from '@/store/aiInfra';import { getServerConfigStoreState } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';+import { subscribeLlmRelayChannel } from './channelSubscription';import { getLlmRelayClientId } from './clientId';import { LlmRelayExecutor } from './executor';+import { OneShotRelay } from './oneShot';export { getLlmRelayClientId } from './clientId';export type { ExecuteRelayCallOptions } from './executor';+export type { OneShotRelayHandle } from './oneShot';/*** The page-wide relay executor. Runs on this client's own provider@@ -21,13 +26,79 @@ export const llmRelayExecutor = new LlmRelayExecutor({initializeWithClientStore({ payload, provider, runtimeProvider }),});-const isLlmRelayEnabled = () => {- const state =- (typeof window !== 'undefined' ? window.global_serverConfigStore?.getState() : undefined) ??- getServerConfigStoreState();- return !!state?.featureFlags?.enableLlmRelay;+const getConfigState = () =>+ (typeof window !== 'undefined' ? window.global_serverConfigStore?.getState() : undefined) ??+ getServerConfigStoreState();++const isLlmRelayEnabled = () => !!getConfigState()?.featureFlags?.enableLlmRelay;++/** How long a one-shot call waits for the provider runtime state to load. */+const PROVIDER_STATE_WAIT_MS = 5000;++const isProviderRuntimeStateKnown = () =>+ aiProviderSelectors.isInitAiProviderRuntimeState(getAiInfraStoreState());++/**+ * Nothing when the provider runtime state is loaded; else resolves once it is,+ * or after {@link PROVIDER_STATE_WAIT_MS}: whether a custom provider runs on+ * the device (private base URL, `fetchOnClient`) is only known from it.+ */+const waitForProviderRuntimeState = () => {+ if (isProviderRuntimeStateKnown()) return;++ return new Promise<void>((resolve) => {+ const done = () => {+ clearTimeout(timer);+ unsubscribe();+ resolve();+ };+ const timer = setTimeout(done, PROVIDER_STATE_WAIT_MS);+ const unsubscribe = useAiInfraStore.subscribe(() => {+ if (isProviderRuntimeStateKnown()) done();+ });+ });};+/**+ * The page-wide one-shot relay: LLM calls this tab asks the server for (preset+ * tasks, structured output, model lists) whose provider only this device can+ * reach are relayed back here instead of being called from the browser.+ * Active only within the `agent_llm_relay` rollout on a deployment that can+ * relay (Agent Gateway + Redis); elsewhere `oneShotRelay.run` just makes the+ * request.+ */+export const oneShotRelay = new OneShotRelay({+ // `llmRelayAvailable`: the server can relay (gateway + Redis); otherwise it+ // would call a device-only provider itself, so keep the browser path.+ isAvailable: () => {+ const serverConfig = getConfigState()?.serverConfig;+ return (+ isLlmRelayEnabled() && !!serverConfig?.agentGatewayUrl && !!serverConfig.llmRelayAvailable+ );+ },+ isDeviceProvider: (provider) =>+ aiProviderSelectors.isProviderFetchOnClient(provider)(getAiInfraStoreState()),+ onCancel: (data) => llmRelayExecutor.cancel(data),+ onExecute: (data) => void llmRelayExecutor.execute(data),+ subscribe: (channel, onEvent) => {+ const subscription = subscribeLlmRelayChannel(+ getConfigState()!.serverConfig!.agentGatewayUrl!,+ channel,+ onEvent,+ );+ return subscription.then((sub) => ({+ ...sub,+ close: () => {+ // The request is over: whatever it left running on this tab is moot.+ llmRelayExecutor.cancelOperation(channel);+ sub.close();+ },+ }));+ },+ userId: () => userProfileSelectors.userId(useUserStore.getState()),+ whenProvidersKnown: waitForProviderRuntimeState,+});+/*** `execAgent`'s `llmExecutor`: this client can run relayed LLM attempts for* the providers it has configured. The server still decides per providerdiff --git a/src/services/llmRelay/oneShot.test.ts b/src/services/llmRelay/oneShot.test.tsnew file mode 100644index 00000000000..58e19c67693--- /dev/null+++ b/src/services/llmRelay/oneShot.test.ts@@ -0,0 +1,237 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { describe, expect, it, vi } from 'vitest';++import type { OneShotRelayDeps } from './oneShot';+import { ONE_SHOT_SUBSCRIBE_TIMEOUT_MS, OneShotRelay } from './oneShot';++const createRelay = (overrides: Partial<OneShotRelayDeps> = {}) => {+ let emit!: (event: AgentStreamEvent) => void;+ let markReady!: () => void;+ const close = vi.fn();+ const deps: OneShotRelayDeps = {+ clientId: () => 'tab-1',+ isAvailable: () => true,+ isDeviceProvider: (provider) => provider === 'ollama',+ onCancel: vi.fn(),+ onExecute: vi.fn(),+ subscribe: vi.fn(async (_channel, onEvent) => {+ emit = onEvent;+ return { close, ready: new Promise<void>((resolve) => (markReady = resolve)) };+ }),+ userId: () => 'user-1',+ ...overrides,+ };+ return {+ close,+ deps,+ emit: (e: AgentStreamEvent) => emit(e),+ markReady: () => markReady(),+ relay: new OneShotRelay(deps),+ };+};++describe('OneShotRelay', () => {+ it('makes the request as-is for a provider the server reaches itself', async () => {+ const { deps, relay } = createRelay();+ const request = vi.fn(async () => 'ok');++ expect(await relay.run('openai', request)).toBe('ok');+ expect(request).toHaveBeenCalledWith();+ expect(deps.subscribe).not.toHaveBeenCalled();+ });++ it('makes the request as-is where the deployment cannot relay', async () => {+ const { deps, relay } = createRelay({ isAvailable: () => false });++ await relay.run('ollama', async () => 'ok');+ expect(deps.subscribe).not.toHaveBeenCalled();+ });++ // Callers drop the browser fetcher when `needsRelay` says so; with no user id+ // yet (session still loading) `run` cannot build a channel, so `needsRelay`+ // must say no and leave the legacy path in place.+ // A custom provider is device-only by its runtime state (a private base URL,+ // `fetchOnClient`), which a page loads after it starts: decided before that,+ // the call would go out without a channel and the server would find no tab.+ it('decides only once the provider runtime state is known', async () => {+ let known = false;+ let markKnown!: () => void;+ const { deps, markReady, relay } = createRelay({+ isDeviceProvider: () => known,+ whenProvidersKnown: () =>+ new Promise<void>((resolve) => {+ markKnown = () => {+ known = true;+ resolve();+ };+ }),+ });+ const request = vi.fn(async () => 'ok');++ const result = relay.run('my-local-proxy', request);+ await Promise.resolve();+ expect(deps.subscribe).not.toHaveBeenCalled();++ markKnown();+ await vi.waitFor(() => expect(deps.subscribe).toHaveBeenCalled());+ markReady();+ expect(await result).toBe('ok');+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ channel: expect.any(String) }));+ });++ it('stops waiting for the provider runtime state once the caller aborts', async () => {+ const { deps, relay } = createRelay({ whenProvidersKnown: () => new Promise(() => {}) });+ const controller = new AbortController();+ const request = vi.fn(async () => 'ok');++ const result = relay.run('ollama', request, { signal: controller.signal });+ controller.abort();++ expect(await result).toBe('ok');+ expect(request).toHaveBeenCalledWith();+ expect(deps.subscribe).not.toHaveBeenCalled();+ });++ it('does not claim the call while the user id is still unknown', async () => {+ const { deps, relay } = createRelay({ userId: () => undefined });+ const request = vi.fn(async () => 'ok');++ expect(relay.needsRelay('ollama')).toBe(false);+ expect(await relay.run('ollama', request)).toBe('ok');+ expect(request).toHaveBeenCalledWith();+ expect(deps.subscribe).not.toHaveBeenCalled();+ });++ it('subscribes its own channel first, sends it in the headers, executes what it delivers, then releases it', async () => {+ const { close, deps, emit, markReady, relay } = createRelay();+ const request = vi.fn(async (handle?: { channel: string; headers: Record<string, string> }) => {+ emit({ data: { callId: `${handle!.channel}:1` }, type: 'llm_execute' } as any);+ emit({+ data: { callId: `${handle!.channel}:1`, reason: 'timeout' },+ type: 'llm_cancel',+ } as any);+ return 'done';+ });++ const result = relay.run('ollama', request);+ await vi.waitFor(() => expect(deps.subscribe).toHaveBeenCalled());+ // Not sent before the gateway has the subscription.+ expect(request).not.toHaveBeenCalled();+ markReady();++ expect(await result).toBe('done');+ const [channel] = vi.mocked(deps.subscribe).mock.calls[0];+ expect(channel).toMatch(/^llmcall:user-1:[\w-]{8,64}$/);+ expect(request.mock.calls[0][0]).toEqual({+ channel,+ headers: { 'x-lobe-client-id': 'tab-1', 'x-lobe-llm-relay-channel': channel },+ });+ expect(deps.onExecute).toHaveBeenCalledWith({ callId: `${channel}:1` });+ expect(deps.onCancel).toHaveBeenCalledWith({ callId: `${channel}:1`, reason: 'timeout' });+ expect(close).toHaveBeenCalledTimes(1);+ });++ it('releases the channel when the request fails', async () => {+ const { close, markReady, relay } = createRelay();+ const result = relay.run('ollama', async () => {+ throw new Error('boom');+ });+ markReady();++ await expect(result).rejects.toThrow('boom');+ expect(close).toHaveBeenCalledTimes(1);+ });++ it('goes ahead once the subscription takes too long, so the server reports the failure', async () => {+ vi.useFakeTimers();+ try {+ const { relay } = createRelay();+ const request = vi.fn(async () => 'ok');+ const result = relay.run('ollama', request);++ await vi.advanceTimersByTimeAsync(ONE_SHOT_SUBSCRIBE_TIMEOUT_MS);+ expect(await result).toBe('ok');+ } finally {+ vi.useRealTimers();+ }+ });++ // The v1 path fetches a gateway token before it subscribes: a stalled token+ // request must not hold the caller's request up past the same timeout, and+ // a subscription that lands late is still released.+ it('bounds the subscription setup itself by the timeout and releases a late subscription', async () => {+ vi.useFakeTimers();+ try {+ const close = vi.fn();+ let finishSetup!: () => void;+ const { relay } = createRelay({+ subscribe: vi.fn(+ () =>+ new Promise((resolve) => {+ finishSetup = () => resolve({ close, ready: Promise.resolve() });+ }),+ ),+ });+ const request = vi.fn(async () => 'ok');+ const result = relay.run('ollama', request);++ await vi.advanceTimersByTimeAsync(ONE_SHOT_SUBSCRIBE_TIMEOUT_MS);+ expect(await result).toBe('ok');+ expect(request).toHaveBeenCalledWith(+ expect.objectContaining({ channel: expect.any(String) }),+ );++ finishSetup();+ await vi.advanceTimersByTimeAsync(0);+ expect(close).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('stops waiting for the subscription once the caller aborts', async () => {+ vi.useFakeTimers();+ try {+ const { relay } = createRelay({ subscribe: vi.fn(() => new Promise(() => {})) });+ const controller = new AbortController();+ const request = vi.fn(async () => 'ok');+ const result = relay.run('ollama', request, { signal: controller.signal });++ controller.abort();+ await vi.advanceTimersByTimeAsync(0);+ expect(request).toHaveBeenCalledTimes(1);+ expect(await result).toBe('ok');+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not wait for the subscription when the caller already aborted', async () => {+ vi.useFakeTimers();+ try {+ const { relay } = createRelay({ subscribe: vi.fn(() => new Promise(() => {})) });+ const controller = new AbortController();+ controller.abort();+ const request = vi.fn(async () => 'ok');++ const result = relay.run('ollama', request, { signal: controller.signal });+ await vi.advanceTimersByTimeAsync(0);+ expect(request).toHaveBeenCalledTimes(1);+ expect(await result).toBe('ok');+ } finally {+ vi.useRealTimers();+ }+ });++ it('still makes the request when the subscription setup fails', async () => {+ const { relay } = createRelay({+ subscribe: vi.fn(async () => {+ throw new Error('token request failed');+ }),+ });+ const request = vi.fn(async () => 'ok');++ expect(await relay.run('ollama', request)).toBe('ok');+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ channel: expect.any(String) }));+ });+});diff --git a/src/services/llmRelay/oneShot.ts b/src/services/llmRelay/oneShot.tsnew file mode 100644index 00000000000..ffd3a28837d--- /dev/null+++ b/src/services/llmRelay/oneShot.ts@@ -0,0 +1,174 @@+import type {+ AgentStreamEvent,+ LlmCancelData,+ LlmExecuteData,+} from '@lobechat/agent-gateway-client';+import {+ buildLlmRelayChannelId,+ LLM_RELAY_CHANNEL_HEADER,+ LLM_RELAY_CLIENT_ID_HEADER,+} from '@lobechat/agent-gateway-client';+import debug from 'debug';++import { getLlmRelayClientId } from './clientId';++const log = debug('lobe-client:llm-relay:one-shot');++/**+ * Client half of the one-shot relay (T-667): an LLM call this tab asks the+ * server for β a translation, a topic title, a provider check β whose provider+ * only this device can reach. The tab subscribes to a fresh gateway channel,+ * names it in the request headers, and executes the `llm_execute` the server+ * dispatches on it with its own provider configuration (the same executor as+ * relayed agent runs). The browser never calls the provider on its own.+ */++/** What a request must carry so the server relays its LLM calls back here. */+export interface OneShotRelayHandle {+ channel: string;+ headers: Record<string, string>;+}++/** A subscription to one channel; `ready` resolves once the gateway took it. */+export interface OneShotChannelSubscription {+ close: () => void;+ ready: Promise<void>;+}++export interface OneShotRelayDeps {+ clientId?: () => string;+ /** The deployment can relay: `agent_llm_relay` is on and an Agent Gateway is configured. */+ isAvailable: () => boolean;+ /** Whether calls to `provider` leave from this device (shared `fetchOnClient` rule). */+ isDeviceProvider: (provider: string) => boolean;+ /** Run a relayed call this channel delivered. */+ onCancel: (data: LlmCancelData) => void;+ onExecute: (data: LlmExecuteData) => void;+ /** Subscribe to `channel` on the gateway as its executor. */+ subscribe: (+ channel: string,+ onEvent: (event: AgentStreamEvent) => void,+ ) => Promise<OneShotChannelSubscription>;+ userId: () => string | undefined;+ /**+ * Resolves once the provider runtime state is loaded (bounded); nothing when+ * it already is. A custom provider is device-only by settings that arrive+ * after the page starts.+ */+ whenProvidersKnown?: () => Promise<void> | undefined;+}++/** How long a request waits for its channel subscription before going ahead anyway. */+export const ONE_SHOT_SUBSCRIBE_TIMEOUT_MS = 5000;++const randomNonce = (): string =>+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'+ ? crypto.randomUUID()+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;++type SubscribeOutcome = 'aborted' | 'failed' | 'ready' | 'timeout';++/**+ * Waits for `promise` until `ms` pass (no limit when omitted) or `signal`+ * aborts; says which happened.+ */+const withTimeout = (promise: Promise<void>, ms: number | undefined, signal?: AbortSignal) =>+ new Promise<SubscribeOutcome>((resolve) => {+ if (signal?.aborted) return resolve('aborted');+ const timer = ms === undefined ? undefined : setTimeout(() => resolve('timeout'), ms);+ signal?.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ resolve('aborted');+ },+ { once: true },+ );+ promise.then(+ () => {+ clearTimeout(timer);+ resolve('ready');+ },+ () => {+ clearTimeout(timer);+ resolve('failed');+ },+ );+ });++export class OneShotRelay {+ constructor(private readonly deps: OneShotRelayDeps) {}++ /**+ * Whether a call to `provider` is relayed back to this tab: the deployment+ * relays, the provider only runs from the device, and the user is known (a+ * channel is named after them). Callers drop their browser fetcher on this,+ * so it must match what `run` actually does.+ */+ needsRelay(provider: string | undefined): provider is string {+ return (+ !!provider &&+ this.deps.isAvailable() &&+ this.deps.isDeviceProvider(provider) &&+ !!this.deps.userId()+ );+ }++ /**+ * Run `request` with this tab standing by as the executor of its LLM calls+ * to `provider`: `request` gets the headers to send, and the channel is+ * released once it settles (`signal`: an aborted caller stops waiting for+ * the subscription). A provider the server reaches itself runs+ * `request` as-is, without a channel.+ */+ async run<T>(+ provider: string | undefined,+ request: (relay?: OneShotRelayHandle) => Promise<T>,+ { signal }: { signal?: AbortSignal } = {},+ ): Promise<T> {+ const providersLoading =+ provider && this.deps.isAvailable() ? this.deps.whenProvidersKnown?.() : undefined;+ if (providersLoading) {+ // Bounded by the dependency; an aborted caller stops waiting at once and+ // its request settles without a channel.+ await withTimeout(providersLoading, undefined, signal);+ if (signal?.aborted) return request();+ }+ if (!this.needsRelay(provider)) return request();++ const channel = buildLlmRelayChannelId(this.deps.userId()!, randomNonce());+ const subscribing = this.deps.subscribe(channel, (event) => {+ if (event.type === 'llm_execute') this.deps.onExecute(event.data as LlmExecuteData);+ else if (event.type === 'llm_cancel') this.deps.onCancel(event.data as LlmCancelData);+ });++ try {+ // The server dispatches as soon as the request lands: be subscribed+ // first, or the gateway finds nobody to deliver the call to. The setup+ // (a gateway token request on the v1 path) counts against the same+ // timeout; past it, or if it fails, the request goes ahead and the+ // server reports the relay failure.+ const outcome = await withTimeout(+ subscribing.then((subscription) => subscription.ready),+ ONE_SHOT_SUBSCRIBE_TIMEOUT_MS,+ // An aborted caller has nothing to wait for: its request settles at once.+ signal,+ );+ log('channel %s for %s: subscription %s', channel, provider, outcome);++ return await request({+ channel,+ headers: {+ [LLM_RELAY_CHANNEL_HEADER]: channel,+ [LLM_RELAY_CLIENT_ID_HEADER]: (this.deps.clientId ?? getLlmRelayClientId)(),+ },+ });+ } finally {+ // A subscription that lands after the request settled is released too.+ subscribing.then(+ (subscription) => subscription.close(),+ (error) => log('channel %s subscription failed: %O', channel, error),+ );+ }+ }+}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.tsindex 2cad317a9be..203c05fcf1e 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts@@ -382,6 +382,26 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {});});+ it('keeps one-shot relay channels out of gatewayFeed', () => {+ const { action, mux, state } = createTestAction();++ action.connectToGateway({+ gatewayUrl: GATEWAY_URL,+ operationId: 'op-1',+ token: 'tok',+ topicId: 'topic-1',+ });+ mux.emit('lifecycle', {+ at: 1_700_000_000_000,+ meta: { scope: 'llm_call' },+ operationId: 'llmcall:user-1:0b7c1d2e-aaaa',+ status: 'running',+ type: 'op_lifecycle',+ });++ expect(state.gatewayFeed).toEqual({});+ });+it('survives without an auth_expired round trip (token is minted per dial)', () => {const { action, muxClient, state } = createTestAction();diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 97e6466ef81..4200cbbb394 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -6,6 +6,7 @@ import {type ConnectionStatus,createOperationClient,type GatewayMuxClient,+ isLlmRelayChannelId,isSessionTerminalEvent,type MuxOpLifecycleMessage,type OperationClient,@@ -484,6 +485,9 @@ export class GatewayActionImpl {if (this.#feedAttachedMuxes.has(mux)) return;this.#feedAttachedMuxes.add(mux);mux.on('lifecycle', (lifecycle: MuxOpLifecycleMessage) => {+ // A one-shot relay channel (a single LLM call outside any run) is not a+ // run of this user's: nothing in the feed is about it.+ if (isLlmRelayChannelId(lifecycle.operationId)) return;this.#set((state) => ({gatewayFeed: {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.tsindex 7aa382ebc17..fb828ffa932 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts@@ -1,7 +1,7 @@import { GatewayMuxClient } from '@lobechat/agent-gateway-client';import { aiAgentService } from '@/services/aiAgent';-import { getLlmRelayClientId } from '@/services/llmRelay';+import { getLlmRelayClientId } from '@/services/llmRelay/clientId';import { shareChatService } from '@/services/shareChat';export interface GatewayMuxIdentity {