Skip to content

🀯 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.

✨ feat(llm-relay): one-shot relay of a request's LLM calls to the requesting tab (#20453)

Arvin Xubecef7d2f887
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 91f843ff378..cbec817b53b 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -15,6 +15,7 @@ import { sandboxEnv } from '@/envs/sandbox';
import { toolsEnv } from '@/envs/tools';
import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { parseSystemAgent } from '@/server/globalConfig/parseSystemAgent';
+import { isLlmRelayDeploymentReady } from '@/server/modules/AgentRuntime/llmRelay/deployment';
import { type GlobalServerConfig } from '@/types/serverConfig';
import { cleanObject } from '@/utils/object';
@@ -157,6 +158,9 @@ export const getServerGlobalConfig = async () => {
// Expose Agent Gateway URL to client (used by hetero agents; also required for queue mode)
...(appEnv.AGENT_GATEWAY_URL ? { agentGatewayUrl: appEnv.AGENT_GATEWAY_URL } : undefined),
agentGatewayProtocol: resolveAgentGatewayProtocol(),
+ // Whether the server can relay an LLM call to a tab (gateway + Redis): only
+ // then does the browser drop its own provider fallback for the one-shot relay.
+ llmRelayAvailable: isLlmRelayDeploymentReady(),
image: cleanObject({
defaultImageNum: imageEnv.AI_IMAGE_DEFAULT_IMAGE_NUM,
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 565031ef696..e1470fdfdff 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -581,6 +581,33 @@ export class GatewayStreamNotifier implements IStreamEventManager {
}
}
+ /**
+ * Open a one-shot relay channel (`llmcall:<userId>:…`): the gateway session a
+ * single LLM call outside any run dispatches its `llm_execute` on. Only
+ * `userId` may subscribe to it; the tab that makes the call already has.
+ * Rejects when the gateway does not take it, so the call fails up front.
+ */
+ async openLlmRelayChannel(channel: string, userId: string): Promise<void> {
+ await this.httpPostAwait('/api/operations/init', {
+ meta: { scope: 'llm_call' },
+ operationId: channel,
+ userId,
+ });
+ }
+
+ /** The one-shot channel's calls are over: end its session. Best effort. */
+ async closeLlmRelayChannel(channel: string): Promise<void> {
+ try {
+ const res = await this.httpPostResponse('/api/operations/update-status', {
+ operationId: channel,
+ status: 'completed',
+ });
+ if (!res.ok) log('closeLlmRelayChannel %s: gateway returned %d', channel, res.status);
+ } catch (error) {
+ log('closeLlmRelayChannel failed for %s: %O', channel, error);
+ }
+ }
+
// ─── Read / subscribe methods: delegate directly to inner ───
async subscribeStreamEvents(
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index b59edff7b35..1bbe4ac6c61 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -1117,6 +1117,34 @@ describe('GatewayStreamNotifier', () => {
expect(callsTo('/api/operations/llm-close')).toHaveLength(0);
});
+ it('opens a one-shot relay channel for its user and ends it when the request is done', async () => {
+ const channel = 'llmcall:user-1:0b7c1d2e-aaaa';
+
+ await notifier.openLlmRelayChannel(channel, 'user-1');
+ await notifier.closeLlmRelayChannel(channel);
+
+ expect(JSON.parse(callsTo('/api/operations/init')[0][1].body)).toEqual({
+ meta: { scope: 'llm_call' },
+ operationId: channel,
+ userId: 'user-1',
+ });
+ expect(JSON.parse(callsTo('/api/operations/update-status')[0][1].body)).toEqual({
+ operationId: channel,
+ status: 'completed',
+ });
+ });
+
+ it('rejects opening a one-shot channel the gateway refuses, but never a failed close', async () => {
+ mockFetch.mockResolvedValue({ ok: false, status: 500, text: () => Promise.resolve('boom') });
+
+ await expect(
+ notifier.openLlmRelayChannel('llmcall:user-1:abcdefgh', 'user-1'),
+ ).rejects.toThrow('500');
+ await expect(
+ notifier.closeLlmRelayChannel('llmcall:user-1:abcdefgh'),
+ ).resolves.toBeUndefined();
+ });
+
it('stops probing the relay routes once a close returns 404', async () => {
mockFetch.mockImplementation((url: string) =>
Promise.resolve(
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
index e2ed2f8417c..a1e4526a292 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
@@ -2,12 +2,16 @@ import type {
LlmCancelData,
LlmExecuteData,
LlmRelayDeadlines,
+ LlmRelayMethod,
} from '@lobechat/agent-gateway-client';
import type {
ChatMethodOptions,
ChatStreamPayload,
+ GenerateObjectOptions,
+ GenerateObjectPayload,
ModelRuntime,
ProviderResponseDiagnostics,
+ PullModelParams,
} from '@lobechat/model-runtime';
import { createCallbacksTransformer } from '@lobechat/model-runtime';
import type { ModelUsage } from '@lobechat/types';
@@ -83,7 +87,10 @@ const createAbortError = () => {
*
* One instance per attempt: `callId` is the attempt's idempotency key.
*/
-export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleChatStreamError'> {
+export class RelayModelRuntime implements Pick<
+ ModelRuntime,
+ 'chat' | 'generateObject' | 'handleChatStreamError' | 'models' | 'pullModel'
+> {
readonly result: RelayAttemptResult = { usageEstimated: false };
private readonly deadlines: LlmRelayDeadlines;
@@ -98,6 +105,52 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
}
async chat(payload: ChatStreamPayload, options: ChatMethodOptions = {}): Promise<Response> {
+ const reader = await this.start('chat', payload, payload.model);
+
+ return new Response(
+ this.createStream(reader, payload, options).pipeThrough(
+ createCallbacksTransformer(options.callback),
+ ),
+ // Trace ids and the like, as every provider runtime sets them.
+ { headers: options.headers },
+ );
+ }
+
+ /**
+ * Structured output on the device (`runtime.generateObject`), returned as the
+ * value the device uploaded (see {@link collectResult}).
+ */
+ async generateObject(
+ payload: GenerateObjectPayload,
+ options: GenerateObjectOptions = {},
+ ): Promise<any> {
+ const reader = await this.start('generateObject', payload, payload.model);
+ return this.collectResult(reader, options.signal);
+ }
+
+ /** The provider's model list, as the device's runtime reads it. */
+ async models(): Promise<any> {
+ const reader = await this.start('models', {}, '');
+ return this.collectResult(reader);
+ }
+
+ /**
+ * Download a model on the device (Ollama). The response streams the
+ * provider's own progress lines; a failure ends it with a
+ * `{"status":"error"}` line, the shape a progress reader already handles.
+ */
+ async pullModel(params: PullModelParams, options: { signal?: AbortSignal } = {}) {
+ const reader = await this.start('pullModel', params, params.model);
+ return new Response(this.createProgressStream(reader, options.signal), {
+ headers: { 'content-type': 'application/x-ndjson' },
+ });
+ }
+
+ /**
+ * Store the request for the device and hand it the call. Throws an
+ * unavailable-executor error when nobody can pick it up.
+ */
+ private async start(method: LlmRelayMethod, payload: unknown, model: string) {
const { callId, provider, redis } = this.params;
const dispatchedAt = this.now();
const ttlMs = this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS;
@@ -116,7 +169,7 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
let delivered: number | undefined;
try {
- delivered = await this.dispatch(payload.model, dispatchedAt);
+ delivered = await this.dispatch(method, model, dispatchedAt);
} catch (error) {
log('[%s] llm_execute dispatch failed: %O', callId, error);
await this.cleanup();
@@ -131,19 +184,13 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
throw createClientLlmExecutorUnavailableError(provider, 'not_delivered');
}
- const reader = new RelayBatchReader(
+ return new RelayBatchReader(
redis.duplicate(),
llmRelayKeys.stream(callId),
this.deadlines,
dispatchedAt,
this.now,
);
-
- return new Response(
- this.createStream(reader, payload, options).pipeThrough(
- createCallbacksTransformer(options.callback),
- ),
- );
}
/**
@@ -158,7 +205,11 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
* Hand the call to the user's clients. Resolves to how many the gateway
* delivered it to when it can tell, else `undefined`.
*/
- private async dispatch(model: string, dispatchedAt: number): Promise<number | undefined> {
+ private async dispatch(
+ method: LlmRelayMethod,
+ model: string,
+ dispatchedAt: number,
+ ): Promise<number | undefined> {
const { params } = this;
const data: LlmExecuteData = {
assistantMessageId: params.assistantMessageId,
@@ -170,6 +221,8 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
exp: dispatchedAt + this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS,
userId: params.userId,
}),
+ // Absent for `chat`, so a client from before `method` existed still runs it.
+ ...(method !== 'chat' && { method }),
model,
operationId: params.operationId,
preferredClientId: params.preferredClientId,
@@ -306,6 +359,126 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
});
}
+ /**
+ * Read a call whose device uploads a return value (`generateObject`,
+ * `models`) and resolve to it. The device sends the value as JSON text split
+ * into `result_part` chunks, so a large model list never exceeds the batch
+ * cap. A provider failure on the device rejects with its normalized error,
+ * like the provider SDK would have thrown it.
+ */
+ private async collectResult(reader: RelayBatchReader, signal?: AbortSignal): Promise<unknown> {
+ const { provider } = this.params;
+ let resultJson = '';
+ let settled = false;
+ const settle = async (cancelReason?: LlmCancelData['reason']) => {
+ if (settled) return;
+ settled = true;
+ if (cancelReason) await this.cancel(cancelReason);
+ await this.cleanup(reader);
+ };
+
+ try {
+ for (;;) {
+ const next = await reader.next(signal);
+ if (next.kind === 'aborted') {
+ await settle('interrupted');
+ throw createAbortError();
+ }
+ if (next.kind === 'timeout') {
+ await settle('timeout');
+ throw this.toDeadlineError(next.which);
+ }
+
+ for (const chunk of next.batch.chunks) {
+ if (chunk.type === 'result_part' && typeof chunk.data === 'string')
+ resultJson += chunk.data;
+ }
+
+ const { final } = next.batch;
+ if (!final) continue;
+
+ await settle();
+ if (final.reason === 'done') return resultJson ? JSON.parse(resultJson) : undefined;
+ if (final.reason === 'error') {
+ throw final.error ?? createClientLlmExecutorLostError(provider, 'client_aborted');
+ }
+ throw createClientLlmExecutorLostError(provider, 'client_aborted');
+ }
+ } catch (error) {
+ await settle('error');
+ throw error;
+ }
+ }
+
+ private createProgressStream(
+ reader: RelayBatchReader,
+ signal?: AbortSignal,
+ ): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder();
+ let settled = false;
+ const settle = async (cancelReason?: LlmCancelData['reason']) => {
+ if (settled) return;
+ settled = true;
+ if (cancelReason) await this.cancel(cancelReason);
+ await this.cleanup(reader);
+ };
+ const errorLine = (error: unknown) => {
+ const message =
+ (error as { message?: unknown })?.message ??
+ (error as { error?: { message?: unknown } })?.error?.message ??
+ (error as { errorType?: unknown })?.errorType ??
+ 'The model download failed';
+ return encoder.encode(`${JSON.stringify({ error: String(message), status: 'error' })}\n`);
+ };
+
+ return new ReadableStream<Uint8Array>({
+ cancel: async () => {
+ await settle('interrupted');
+ },
+ pull: async (controller) => {
+ try {
+ for (;;) {
+ const next = await reader.next(signal);
+ if (next.kind === 'aborted') {
+ await settle('interrupted');
+ return controller.error(createAbortError());
+ }
+ if (next.kind === 'timeout') {
+ await settle('timeout');
+ controller.enqueue(errorLine(this.toDeadlineError(next.which)));
+ return controller.close();
+ }
+
+ const { batch } = next;
+ for (const chunk of batch.chunks) {
+ if (chunk.type === 'progress' && typeof chunk.data === 'string')
+ controller.enqueue(encoder.encode(chunk.data));
+ }
+
+ if (!batch.final) {
+ if (batch.chunks.length > 0) return;
+ continue;
+ }
+
+ await settle();
+ if (batch.final.reason !== 'done') {
+ controller.enqueue(
+ errorLine(
+ batch.final.error ??
+ createClientLlmExecutorLostError(this.params.provider, 'client_aborted'),
+ ),
+ );
+ }
+ return controller.close();
+ }
+ } catch (error) {
+ await settle('error');
+ controller.error(error);
+ }
+ },
+ });
+ }
+
private toDeadlineError(which: RelayDeadline) {
const { provider } = this.params;
switch (which) {
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
index 5b4e84b2a5c..43006d271b4 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
@@ -365,6 +365,142 @@ describe('RelayModelRuntime + llm-relay handlers', () => {
});
});
+describe('RelayModelRuntime non-chat methods', () => {
+ beforeEach(() => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ redis = new FakeRedis();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('runs generateObject on the device and resolves to its uploaded result', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+ const objectPayload = {
+ messages: [{ content: 'Title this', role: 'user' as const }],
+ model: 'llama3',
+ schema: { name: 'title', schema: { properties: {}, type: 'object' as const } },
+ };
+
+ const result = runtime.generateObject(objectPayload);
+ const execute = await waitForExecute(events);
+ expect(execute.method).toBe('generateObject');
+
+ const payloadRes = await llmRelayPayload(buildContext(CALL_ID, { lease: execute.leaseToken }));
+ expect(await payloadRes.json()).toEqual(objectPayload);
+
+ // The value arrives as JSON text in parts, possibly across batches.
+ await post(execute.leaseToken, {
+ chunks: [{ data: '{"title":', type: 'result_part' }],
+ clientId: 'tab-a',
+ seq: 1,
+ });
+ await post(execute.leaseToken, {
+ chunks: [{ data: '"Hello"}', type: 'result_part' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 2,
+ });
+
+ await expect(result).resolves.toEqual({ title: 'Hello' });
+ expect(redis.peek(llmRelayKeys.payload(CALL_ID))).toBeUndefined();
+ });
+
+ it('rejects generateObject with the provider error the device reported', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+
+ const result = runtime.generateObject({ messages: [], model: 'llama3' } as any);
+ const { leaseToken } = await waitForExecute(events);
+ const providerError = { errorType: 'OllamaServiceUnavailable', provider: 'ollama' };
+ await post(leaseToken, {
+ chunks: [],
+ clientId: 'tab-a',
+ final: { error: providerError, reason: 'error' },
+ seq: 1,
+ });
+
+ await expect(result).rejects.toEqual(providerError);
+ });
+
+ it('fails generateObject as ClientLlmExecutorUnavailable when nobody claims it', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager, {
+ claimMs: 50,
+ firstChunkMs: 2000,
+ idleMs: 2000,
+ totalMs: 5000,
+ });
+
+ await expect(runtime.models()).rejects.toMatchObject({
+ error: { reason: 'claim_timeout' },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ });
+ expect(events.find((e) => e.type === 'llm_execute')?.data.method).toBe('models');
+ expect(events.some((e) => e.type === 'llm_cancel')).toBe(true);
+ });
+
+ it('streams pullModel progress and ends a failed download with an error line', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+
+ const response = await runtime.pullModel({ model: 'llama3' });
+ const execute = await waitForExecute(events);
+ expect(execute).toMatchObject({ method: 'pullModel', model: 'llama3' });
+
+ await post(execute.leaseToken, {
+ chunks: [{ data: '{"status":"pulling","completed":1,"total":2}\n', type: 'progress' }],
+ clientId: 'tab-a',
+ seq: 1,
+ });
+ await post(execute.leaseToken, {
+ chunks: [],
+ clientId: 'tab-a',
+ final: { error: { message: 'disk full' }, reason: 'error' },
+ seq: 2,
+ });
+
+ const lines = (await response.text())
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ expect(lines).toEqual([
+ { completed: 1, status: 'pulling', total: 2 },
+ { error: 'disk full', status: 'error' },
+ ]);
+ });
+
+ // The chat route hands trace headers in `options.headers`; every provider
+ // runtime sets them on its Response, and the browser stores the trace id
+ // with the message from there.
+ it('sets the response headers the caller hands to chat (trace ids)', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+
+ const response = runtime.chat(payload, { headers: { 'x-lobe-chat-trace-id': 'trace-1' } });
+ const execute = await waitForExecute(events);
+ await post(execute.leaseToken, {
+ chunks: [],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 1,
+ });
+
+ expect((await response).headers.get('x-lobe-chat-trace-id')).toBe('trace-1');
+ });
+
+ it('keeps method off the chat dispatch, for executors that predate it', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+
+ void runtime.chat(payload).catch(() => {});
+ const execute = await waitForExecute(events);
+ expect(execute).not.toHaveProperty('method');
+ });
+});
+
describe('RelayModelRuntime over a gateway with relay routes', () => {
beforeEach(() => {
vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts
new file mode 100644
index 00000000000..1b49d5652d6
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { isLlmRelayDeploymentReady } from '../deployment';
+
+const env = vi.hoisted(() => ({
+ app: {} as Record<string, string | undefined>,
+ redis: {} as Record<string, string | undefined>,
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: env.app }));
+vi.mock('@/envs/redis', () => ({ redisEnv: env.redis }));
+
+// The browser only stands by for a one-shot relay where the server can relay:
+// a gateway it can push to and the Redis the relayed call runs through.
+// Anything less and the server calls the provider itself, which cannot reach
+// a model on the user's device β€” the browser must keep its own fallback then.
+describe('isLlmRelayDeploymentReady', () => {
+ beforeEach(() => {
+ vi.unstubAllEnvs();
+ env.app.AGENT_GATEWAY_URL = 'https://gw';
+ env.app.AGENT_GATEWAY_INTERNAL_URL = undefined;
+ env.app.AGENT_GATEWAY_SERVICE_TOKEN = 'token';
+ env.redis.REDIS_URL = 'redis://localhost:6379';
+ });
+
+ it('is ready with a gateway, its service token and Redis', () => {
+ expect(isLlmRelayDeploymentReady()).toBe(true);
+ });
+
+ it('is not ready without Redis', () => {
+ env.redis.REDIS_URL = undefined;
+ expect(isLlmRelayDeploymentReady()).toBe(false);
+ });
+
+ it('is not ready with Redis disabled', () => {
+ vi.stubEnv('DISABLE_REDIS', '1');
+ expect(isLlmRelayDeploymentReady()).toBe(false);
+ });
+
+ it('is not ready without a gateway service token', () => {
+ env.app.AGENT_GATEWAY_SERVICE_TOKEN = undefined;
+ expect(isLlmRelayDeploymentReady()).toBe(false);
+ });
+
+ it('is not ready without a gateway', () => {
+ env.app.AGENT_GATEWAY_URL = undefined;
+ expect(isLlmRelayDeploymentReady()).toBe(false);
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/oneShot.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/oneShot.test.ts
new file mode 100644
index 00000000000..f866bd5cd3b
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/oneShot.test.ts
@@ -0,0 +1,233 @@
+// @vitest-environment node
+import type { LlmExecuteData } from '@lobechat/agent-gateway-client';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { llmRelayChunks } from '@/server/router-hono/agent/handlers/llmRelay';
+
+import { initModelRuntimeForRequest } from '../oneShot';
+import { LLM_RELAY_LEASE_HEADER } from '../protocol';
+import {
+ readLlmRelayRequest,
+ runRouteWithLlmRelayRequest,
+ runWithLlmRelayRequest,
+} from '../requestScope';
+import { FakeRedis } from './fakeRedis';
+
+let redis: FakeRedis | null;
+let streamManager: any;
+
+const resolveProviderRelay = vi.hoisted(() => vi.fn());
+const initModelRuntimeFromDB = vi.hoisted(() => vi.fn(async () => ({ server: true })));
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => redis,
+}));
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createStreamEventManager: () => streamManager,
+}));
+vi.mock('../resolveLlmExecutionSite', () => ({ resolveProviderRelay }));
+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB }));
+
+const USER_ID = 'user-1';
+const CHANNEL = 'llmcall:user-1:0b7c1d2e-aaaa-bbbb-cccc-123456789abc';
+const REQUEST = { channel: CHANNEL, clientId: 'tab-a' };
+
+const createGatewayStreamManager = () => {
+ const executes: LlmExecuteData[] = [];
+ return {
+ closeLlmCall: vi.fn(async () => {}),
+ closeLlmRelayChannel: vi.fn(async () => {}),
+ executes,
+ openLlmRelayChannel: vi.fn(async () => {}),
+ publishStreamEvent: vi.fn(async () => 'id'),
+ sendLlmCancel: vi.fn(async () => {}),
+ sendLlmExecute: vi.fn(async (_operationId: string, data: LlmExecuteData) => {
+ executes.push(data);
+ return { delivered: 1, routed: true };
+ }),
+ };
+};
+
+const upload = (execute: LlmExecuteData, body: unknown) =>
+ llmRelayChunks({
+ json: (value: unknown, status = 200) => Response.json(value, { status }),
+ req: {
+ header: (name: string) => (name === LLM_RELAY_LEASE_HEADER ? execute.leaseToken : undefined),
+ param: (name: string) => (name === 'callId' ? execute.callId : undefined),
+ raw: new Request('http://localhost/chunks', { body: JSON.stringify(body), method: 'POST' }),
+ },
+ } as any);
+
+/** Play the device: answer the n-th dispatched call with its return value. */
+const answer = async (index: number, data: unknown) => {
+ await vi.waitFor(() => expect(streamManager.executes.length).toBeGreaterThan(index));
+ const execute = streamManager.executes[index];
+ await upload(execute, {
+ chunks: [{ data: JSON.stringify(data), type: 'result_part' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 1,
+ });
+ return execute as LlmExecuteData;
+};
+
+const generate = (runtime: Awaited<ReturnType<typeof initModelRuntimeForRequest>>) =>
+ runtime.generateObject({ messages: [{ content: 'hi', role: 'user' }], model: 'qwen3:1.7b' });
+
+describe('one-shot relay', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ redis = new FakeRedis();
+ streamManager = createGatewayStreamManager();
+ resolveProviderRelay.mockResolvedValue({ runtimeProvider: 'ollama' });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ describe('readLlmRelayRequest', () => {
+ it('reads the channel and client id headers', () => {
+ const headers = new Headers({
+ 'x-lobe-client-id': 'tab-a',
+ 'x-lobe-llm-relay-channel': CHANNEL,
+ });
+ expect(readLlmRelayRequest(headers)).toEqual(REQUEST);
+ });
+
+ it('ignores a request missing either header', () => {
+ expect(readLlmRelayRequest(new Headers({ 'x-lobe-client-id': 'tab-a' }))).toBeUndefined();
+ expect(
+ readLlmRelayRequest(new Headers({ 'x-lobe-llm-relay-channel': CHANNEL })),
+ ).toBeUndefined();
+ });
+ });
+
+ it('keeps a provider the server can reach on the server', async () => {
+ resolveProviderRelay.mockResolvedValue(undefined);
+
+ const runtime = await runWithLlmRelayRequest(REQUEST, USER_ID, () =>
+ initModelRuntimeForRequest({} as any, USER_ID, 'openai', { workspaceId: 'ws-1' }),
+ );
+
+ expect(runtime).toEqual({ server: true });
+ expect(initModelRuntimeFromDB).toHaveBeenCalledWith({}, USER_ID, 'openai', 'ws-1');
+ expect(streamManager.openLlmRelayChannel).not.toHaveBeenCalled();
+ });
+
+ it('fails at once with no_executor when no tab is attached to the request (bot, workflow)', async () => {
+ await expect(initModelRuntimeForRequest({} as any, USER_ID, 'ollama')).rejects.toMatchObject({
+ error: { context: 'no_client_request', reason: 'no_executor' },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ provider: 'ollama',
+ });
+ expect(streamManager.sendLlmExecute).not.toHaveBeenCalled();
+ });
+
+ it("never opens a channel the caller does not own (another user's or a run's operation)", async () => {
+ for (const channel of ['llmcall:user-2:0b7c1d2e-aaaa', 'op_123', 'llmcall:user-1:x']) {
+ await expect(
+ runWithLlmRelayRequest({ channel, clientId: 'tab-a' }, USER_ID, () =>
+ initModelRuntimeForRequest({} as any, USER_ID, 'ollama'),
+ ),
+ ).rejects.toMatchObject({ error: { reason: 'no_executor' } });
+ }
+ expect(streamManager.openLlmRelayChannel).not.toHaveBeenCalled();
+ });
+
+ it('relays every call of the request on its channel, then closes it', async () => {
+ const results = await runWithLlmRelayRequest(REQUEST, USER_ID, async () => {
+ const runtime = await initModelRuntimeForRequest({} as any, USER_ID, 'ollama');
+ const first = generate(runtime);
+ const firstExecute = await answer(0, { title: 'One' });
+ const second = generate(runtime);
+ const secondExecute = await answer(1, { title: 'Two' });
+ return {
+ executes: [firstExecute, secondExecute],
+ values: await Promise.all([first, second]),
+ };
+ });
+
+ expect(results.values).toEqual([{ title: 'One' }, { title: 'Two' }]);
+ expect(results.executes.map((e) => e.callId)).toEqual([`${CHANNEL}:1`, `${CHANNEL}:2`]);
+ expect(results.executes[0]).toMatchObject({
+ method: 'generateObject',
+ operationId: CHANNEL,
+ preferredClientId: 'tab-a',
+ provider: 'ollama',
+ runtimeProvider: 'ollama',
+ });
+ expect(streamManager.openLlmRelayChannel).toHaveBeenCalledTimes(1);
+ expect(streamManager.openLlmRelayChannel).toHaveBeenCalledWith(CHANNEL, USER_ID);
+ await vi.waitFor(() =>
+ expect(streamManager.closeLlmRelayChannel).toHaveBeenCalledWith(CHANNEL),
+ );
+ });
+
+ it('treats a call made after the request ended (deferred work) as having no tab', async () => {
+ const runtime = await runWithLlmRelayRequest(REQUEST, USER_ID, () =>
+ initModelRuntimeForRequest({} as any, USER_ID, 'ollama'),
+ );
+
+ await expect(generate(runtime)).rejects.toMatchObject({
+ error: { reason: 'no_executor' },
+ });
+ expect(streamManager.sendLlmExecute).not.toHaveBeenCalled();
+ });
+
+ // A deployment that cannot relay (no Agent Gateway, no Redis) keeps the
+ // legacy path: the browser sends no relay headers there, and the server
+ // calls the provider itself, as before the relay β€” tab or no tab.
+ it('keeps the server runtime on a deployment without a gateway or Redis', async () => {
+ streamManager = { publishStreamEvent: vi.fn() };
+ await expect(
+ runWithLlmRelayRequest(REQUEST, USER_ID, () =>
+ initModelRuntimeForRequest({} as any, USER_ID, 'ollama'),
+ ),
+ ).resolves.toEqual({ server: true });
+ // No tab attached (bot, workflow): still the server runtime, not no_executor.
+ await expect(initModelRuntimeForRequest({} as any, USER_ID, 'ollama')).resolves.toEqual({
+ server: true,
+ });
+
+ streamManager = createGatewayStreamManager();
+ redis = null;
+ await expect(initModelRuntimeForRequest({} as any, USER_ID, 'ollama')).resolves.toEqual({
+ server: true,
+ });
+ expect(initModelRuntimeFromDB).toHaveBeenCalledTimes(3);
+ expect(streamManager.sendLlmExecute).not.toHaveBeenCalled();
+ });
+
+ it('fails as relay_unsupported when the gateway does not open the channel', async () => {
+ streamManager.openLlmRelayChannel.mockRejectedValue(new Error('500'));
+
+ await expect(
+ runWithLlmRelayRequest(REQUEST, USER_ID, async () =>
+ generate(await initModelRuntimeForRequest({} as any, USER_ID, 'ollama')),
+ ),
+ ).rejects.toMatchObject({ error: { reason: 'relay_unsupported' } });
+ expect(streamManager.sendLlmExecute).not.toHaveBeenCalled();
+ });
+
+ it('keeps a streaming route channel open until its body is read', async () => {
+ const req = new Request('http://localhost/webapi/chat/ollama', {
+ headers: { 'x-lobe-client-id': 'tab-a', 'x-lobe-llm-relay-channel': CHANNEL },
+ method: 'POST',
+ });
+
+ const response = await runRouteWithLlmRelayRequest(req, USER_ID, async () => {
+ const runtime = await initModelRuntimeForRequest({} as any, USER_ID, 'ollama');
+ const value = generate(runtime);
+ await answer(0, 'done');
+ return new Response(JSON.stringify(await value), { status: 201 });
+ });
+
+ expect(response.status).toBe(201);
+ expect(streamManager.closeLlmRelayChannel).not.toHaveBeenCalled();
+ expect(await response.text()).toBe('"done"');
+ await vi.waitFor(() => expect(streamManager.closeLlmRelayChannel).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
index 5acea26bba2..013b40c272c 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
@@ -115,9 +115,32 @@ describe('resolveLlmExecutionSite', () => {
});
});
- it('keeps a provider without client requests on the server, whatever its endpoint', async () => {
- providerRow.current = { fetchOnClient: false, keyVaults: { baseURL: 'http://127.0.0.1:1234/v1' } };
+ it('keeps a provider without client requests on the server', async () => {
+ providerRow.current = {
+ fetchOnClient: false,
+ keyVaults: { apiKey: 'sk-local', baseURL: 'http://127.0.0.1:1234/v1' },
+ };
expect(await resolve('my-local-llm', executor(['my-local-llm']))).toEqual({ site: 'server' });
});
+
+ // The client store sends a provider with only a base URL from the device
+ // whatever `fetchOnClient` says; the server must relay it the same way, or the
+ // client prepares no executor and the call fails as `no_executor`.
+ it('relays a provider with only a base URL, like the client store does', async () => {
+ providerRow.current = {
+ fetchOnClient: false,
+ keyVaults: { baseURL: 'http://127.0.0.1:1234/v1' },
+ };
+
+ expect(await resolve('my-local-llm', executor(['my-local-llm']))).toMatchObject({
+ site: 'client',
+ });
+ });
+
+ it('keeps a provider whose card disables browser requests on the server', async () => {
+ providerRow.current = { fetchOnClient: true, keyVaults: { baseURL: 'http://127.0.0.1:1/v1' } };
+
+ expect(await resolve('cloudflare', executor(['cloudflare']))).toEqual({ site: 'server' });
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts b/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts
new file mode 100644
index 00000000000..e091e44d344
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts
@@ -0,0 +1,15 @@
+import { appEnv } from '@/envs/app';
+import { redisEnv } from '@/envs/redis';
+import { isRedisDisabledByEnv } from '@/libs/redis';
+
+/**
+ * Whether this deployment can relay an LLM call to a browser tab: it pushes to
+ * an Agent Gateway (URL + service token) and has the Redis relayed calls run
+ * through. Exposed to the browser (`llmRelayAvailable`) so a tab only gives up
+ * its own provider fallback where the server can actually relay.
+ */
+export const isLlmRelayDeploymentReady = (): boolean =>
+ !!(appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL) &&
+ !!appEnv.AGENT_GATEWAY_SERVICE_TOKEN &&
+ !!redisEnv.REDIS_URL &&
+ !isRedisDisabledByEnv();
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/oneShot.ts b/apps/server/src/modules/AgentRuntime/llmRelay/oneShot.ts
new file mode 100644
index 00000000000..b0372058c39
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/oneShot.ts
@@ -0,0 +1,167 @@
+import type { LlmRelayDeadlines } from '@lobechat/agent-gateway-client';
+import type {
+ ChatMethodOptions,
+ ChatStreamPayload,
+ GenerateObjectOptions,
+ GenerateObjectPayload,
+ ModelRuntime,
+ PullModelParams,
+} from '@lobechat/model-runtime';
+import debug from 'debug';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+
+import { createStreamEventManager } from '../factory';
+import { getAgentRuntimeRedisClient } from '../redis';
+import type { IStreamEventManager } from '../types';
+import { createClientLlmExecutorUnavailableError } from './errors';
+import { DEFAULT_LLM_RELAY_DEADLINES } from './protocol';
+import { RelayModelRuntime } from './RelayModelRuntime';
+import type { LlmRelayRequestScope } from './requestScope';
+import { getLlmRelayRequestScope } from './requestScope';
+import { resolveProviderRelay } from './resolveLlmExecutionSite';
+
+const log = debug('lobe-server:agent-runtime:llm-relay:one-shot');
+
+/**
+ * One-shot relay (T-667): an LLM call made outside any agent run β€” a topic
+ * title, a translation, a provider check β€” whose provider only the user's
+ * device can reach. The tab that asks for it subscribes to a fresh gateway
+ * channel (`llmcall:<userId>:<nonce>`) and names it in the request headers;
+ * the server opens that channel, dispatches the call's `llm_execute` on it
+ * through {@link RelayModelRuntime}, and returns the device's result to the
+ * caller like any provider result.
+ *
+ * The channel lives as long as the request: every relayed call the request
+ * makes uses it, and it is closed when the request ends. A call made without
+ * such a request β€” a bot webhook, a workflow, a cron, work deferred past the
+ * response β€” has no device to run on and fails at once (`no_executor`).
+ */
+
+/** The runtime methods a request-scoped caller uses, wherever the call runs. */
+export type RequestModelRuntime = Pick<
+ ModelRuntime,
+ 'chat' | 'generateObject' | 'models' | 'pullModel'
+>;
+
+/**
+ * One-shot calls run inside a request, not a 600 s step: keep the whole call
+ * well inside a route's `maxDuration`.
+ */
+const ONE_SHOT_DEADLINES: LlmRelayDeadlines = { ...DEFAULT_LLM_RELAY_DEADLINES, totalMs: 240_000 };
+
+interface OneShotRelayRuntimeParams {
+ deadlines: LlmRelayDeadlines;
+ provider: string;
+ redis: NonNullable<ReturnType<typeof getAgentRuntimeRedisClient>>;
+ runtimeProvider: string;
+ scope: LlmRelayRequestScope;
+ streamManager: IStreamEventManager;
+}
+
+/**
+ * The request's provider runtime when the provider runs on the device: each
+ * method is one relayed call on the request's channel.
+ */
+class OneShotRelayRuntime implements RequestModelRuntime {
+ constructor(private readonly params: OneShotRelayRuntimeParams) {}
+
+ async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {
+ return (await this.call()).chat(payload, options);
+ }
+
+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
+ return (await this.call()).generateObject(payload, options);
+ }
+
+ async models() {
+ return (await this.call()).models();
+ }
+
+ async pullModel(params: PullModelParams, options?: { signal?: AbortSignal }) {
+ return (await this.call()).pullModel(params, options);
+ }
+
+ private async call() {
+ const { deadlines, provider, redis, runtimeProvider, scope, streamManager } = this.params;
+ if (scope.ended) throw noClientRequestError(provider);
+
+ try {
+ await scope.open(streamManager);
+ } catch (error) {
+ log('failed to open relay channel %s: %O', scope.request.channel, error);
+ throw createClientLlmExecutorUnavailableError(provider, 'relay_unsupported');
+ }
+
+ return new RelayModelRuntime({
+ attempt: 1,
+ callId: scope.nextCallId(),
+ deadlines,
+ operationId: scope.request.channel,
+ preferredClientId: scope.request.clientId,
+ provider,
+ redis,
+ runtimeProvider,
+ stepIndex: 0,
+ streamManager,
+ userId: scope.userId,
+ });
+ }
+}
+
+const noClientRequestError = (provider: string) =>
+ createClientLlmExecutorUnavailableError(provider, 'no_executor', {
+ context: 'no_client_request',
+ message: `${provider} runs on the user's device, and no open LobeHub tab is attached to this request to run it.`,
+ });
+
+export interface InitModelRuntimeForRequestOptions {
+ /** Shorter deadlines for a latency-sensitive call (input completion). */
+ deadlines?: Partial<LlmRelayDeadlines>;
+ workspaceId?: string;
+}
+
+/**
+ * `initModelRuntimeFromDB` for a call made on behalf of a request: a provider
+ * only the user's device can reach (the shared `fetchOnClient` rule, with the
+ * `agent_llm_relay` rollout on) is relayed to the requesting tab; everything
+ * else runs on the server exactly as before.
+ *
+ * A deployment that cannot relay (no Agent Gateway or no Redis) keeps the
+ * legacy server runtime: its browser sends no relay headers either.
+ *
+ * Throws `ClientLlmExecutorUnavailable` up front when such a provider has no
+ * tab to run on (`no_executor`, e.g. a bot or a workflow).
+ */
+export const initModelRuntimeForRequest = async (
+ db: LobeChatDatabase,
+ userId: string,
+ provider: string,
+ { deadlines, workspaceId }: InitModelRuntimeForRequestOptions = {},
+): Promise<RequestModelRuntime> => {
+ const relay = await resolveProviderRelay({ db, provider, userId, workspaceId });
+ if (!relay) return initModelRuntimeFromDB(db, userId, provider, workspaceId);
+
+ const redis = getAgentRuntimeRedisClient();
+ const streamManager = createStreamEventManager();
+ if (!redis || !streamManager.sendLlmExecute || !streamManager.openLlmRelayChannel) {
+ log('deployment cannot relay %s, calling it from the server', provider);
+ return initModelRuntimeFromDB(db, userId, provider, workspaceId);
+ }
+
+ const scope = getLlmRelayRequestScope();
+ if (!scope || scope.ended || scope.userId !== userId) {
+ log('no client request to relay %s to', provider);
+ throw noClientRequestError(provider);
+ }
+
+ return new OneShotRelayRuntime({
+ deadlines: { ...ONE_SHOT_DEADLINES, ...deadlines },
+ provider,
+ redis,
+ runtimeProvider: relay.runtimeProvider,
+ scope,
+ streamManager,
+ });
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/requestScope.ts b/apps/server/src/modules/AgentRuntime/llmRelay/requestScope.ts
new file mode 100644
index 00000000000..f197c442dec
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/requestScope.ts
@@ -0,0 +1,171 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+import {
+ isOwnLlmRelayChannelId,
+ LLM_RELAY_CHANNEL_HEADER,
+ LLM_RELAY_CLIENT_ID_HEADER,
+} from '@lobechat/agent-gateway-client';
+import debug from 'debug';
+
+import type { IStreamEventManager } from '../types';
+
+const log = debug('lobe-server:agent-runtime:llm-relay:request');
+
+/**
+ * Request side of the one-shot relay (see `oneShot.ts`): which tab a request
+ * came from and the gateway channel it subscribed for the request's relayed
+ * LLM calls. Carried through the request in an `AsyncLocalStorage`, so a
+ * service deep in the call tree relays without every signature passing it on.
+ */
+
+/** What a request carries to have its LLM calls relayed back to its tab. */
+export interface LlmRelayRequest {
+ /** The one-shot channel the tab subscribed to. */
+ channel: string;
+ /** The tab's client id, the call's preferred executor. */
+ clientId: string;
+}
+
+const MAX_CLIENT_ID_LENGTH = 128;
+
+/** The relay request a set of request headers describes, if any. */
+export const readLlmRelayRequest = (headers: {
+ get: (name: string) => string | null;
+}): LlmRelayRequest | undefined => {
+ const channel = headers.get(LLM_RELAY_CHANNEL_HEADER)?.trim();
+ const clientId = headers.get(LLM_RELAY_CLIENT_ID_HEADER)?.trim();
+ if (!channel || !clientId || clientId.length > MAX_CLIENT_ID_LENGTH) return;
+
+ return { channel, clientId };
+};
+
+/**
+ * The relay channel of one request. Opened on the gateway by the first call
+ * that needs it, closed when the request ends; calls after that have no tab
+ * waiting for them.
+ */
+export class LlmRelayRequestScope {
+ ended = false;
+ private calls = 0;
+ private opened?: Promise<void>;
+ private streamManager?: IStreamEventManager;
+
+ constructor(
+ readonly request: LlmRelayRequest,
+ readonly userId: string,
+ ) {}
+
+ nextCallId() {
+ this.calls += 1;
+ return `${this.request.channel}:${this.calls}`;
+ }
+
+ open(streamManager: IStreamEventManager) {
+ if (!this.opened) {
+ this.streamManager = streamManager;
+ this.opened = streamManager.openLlmRelayChannel!(this.request.channel, this.userId);
+ }
+ return this.opened;
+ }
+
+ async end() {
+ if (this.ended) return;
+ this.ended = true;
+ if (!this.opened) return;
+
+ try {
+ await this.opened;
+ } catch {
+ return;
+ }
+ await this.streamManager?.closeLlmRelayChannel?.(this.request.channel);
+ }
+}
+
+const scopeStorage = new AsyncLocalStorage<LlmRelayRequestScope>();
+
+/** The relay scope of the request this code runs for, if it came from a tab that set one up. */
+export const getLlmRelayRequestScope = () => scopeStorage.getStore();
+
+const createScope = (request: LlmRelayRequest | undefined, userId: string | null | undefined) => {
+ if (!request || !userId) return;
+ // Only the caller's own channels: anything else could name a real run's
+ // operation or another user's channel, which the gateway would re-own.
+ if (!isOwnLlmRelayChannelId(request.channel, userId)) {
+ log('ignoring relay channel %s not owned by %s', request.channel, userId);
+ return;
+ }
+ return new LlmRelayRequestScope(request, userId);
+};
+
+/**
+ * Run `fn` as a request whose relayed LLM calls go back to the tab described
+ * by `request`. The channel closes once `fn` settles β€” the response is
+ * complete then (TRPC) β€” without holding the response up.
+ */
+export const runWithLlmRelayRequest = async <T>(
+ request: LlmRelayRequest | undefined,
+ userId: string | null | undefined,
+ fn: () => Promise<T>,
+): Promise<T> => {
+ const scope = createScope(request, userId);
+ if (!scope) return fn();
+
+ try {
+ return await scopeStorage.run(scope, fn);
+ } finally {
+ void scope.end();
+ }
+};
+
+/**
+ * {@link runWithLlmRelayRequest} for a route that streams its response: the
+ * channel stays open until the body is fully read or cancelled.
+ */
+export const runRouteWithLlmRelayRequest = async (
+ req: Request,
+ userId: string,
+ fn: () => Promise<Response>,
+): Promise<Response> => {
+ const scope = createScope(readLlmRelayRequest(req.headers), userId);
+ if (!scope) return fn();
+
+ let response: Response;
+ try {
+ response = await scopeStorage.run(scope, fn);
+ } catch (error) {
+ void scope.end();
+ throw error;
+ }
+ if (!response.body) {
+ void scope.end();
+ return response;
+ }
+
+ const reader = response.body.getReader();
+ const body = new ReadableStream<Uint8Array>({
+ cancel: async (reason) => {
+ void scope.end();
+ await reader.cancel(reason);
+ },
+ pull: async (controller) => {
+ try {
+ const { done, value } = await reader.read();
+ if (done) {
+ void scope.end();
+ return controller.close();
+ }
+ controller.enqueue(value);
+ } catch (error) {
+ void scope.end();
+ controller.error(error);
+ }
+ },
+ });
+
+ return new Response(body, {
+ headers: response.headers,
+ status: response.status,
+ statusText: response.statusText,
+ });
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
index dfbe7ce3974..63959efca67 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
@@ -1,8 +1,8 @@
import type { AgentState } from '@lobechat/agent-runtime';
-import { DEFAULT_LLM_CONFIG } from '@lobechat/business-config';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import debug from 'debug';
import { ModelProvider } from 'model-bank';
+import { isProviderFetchOnClient } from 'model-bank/modelProviders';
import { AiProviderModel } from '@/database/models/aiProvider';
import type { LobeChatDatabase } from '@/database/type';
@@ -31,17 +31,45 @@ export interface ResolveLlmExecutionSiteParams {
const SERVER: LlmExecutionSite = { site: 'server' };
+export interface ResolveProviderRelayParams {
+ db: LobeChatDatabase;
+ provider: string;
+ userId: string;
+ workspaceId?: string;
+}
+
/**
- * `fetchOnClient` as the client store reads it: the user's choice when they
- * made one, else this deployment's override from the server global config
- * (desktop, `OLLAMA_PROXY_URL`), else the provider default (Ollama / LM Studio
- * / Unsloth ship with `fetchOnClient: true`).
+ * Whether calls to `provider` must run on the user's device, i.e. be relayed:
+ * the relay is on for the user, the provider is not platform-owned, and the
+ * shared `fetchOnClient` rule β€” the one the client store applies, on the
+ * user's config with this deployment's override (desktop, `OLLAMA_PROXY_URL`)
+ * as the default β€” sends it to the device. `undefined` keeps it on the server.
*/
-const resolveFetchOnClient = (provider: string, stored: boolean | undefined) =>
- stored ??
- getServerFetchOnClientOverride(provider) ??
- (DEFAULT_LLM_CONFIG as Record<string, { fetchOnClient?: boolean } | undefined>)[provider]
- ?.fetchOnClient;
+export const resolveProviderRelay = async ({
+ db,
+ provider,
+ userId,
+ workspaceId,
+}: ResolveProviderRelayParams): Promise<{ runtimeProvider: string } | undefined> => {
+ if (provider === BRANDING_PROVIDER || provider === ModelProvider.LobeHub) return;
+
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
+ if (!featureFlags.enableLlmRelay) return;
+
+ const config = await new AiProviderModel(db, userId, workspaceId).getAiProviderById(
+ provider,
+ KeyVaultsGateKeeper.getUserKeyVaults,
+ );
+ const fetchOnClient = isProviderFetchOnClient(provider, {
+ fetchOnClient: config?.fetchOnClient ?? getServerFetchOnClientOverride(provider),
+ keyVaults: config?.keyVaults as { apiKey?: string; baseURL?: string } | undefined,
+ });
+
+ log('provider=%s fetchOnClient=%s', provider, fetchOnClient);
+ if (!fetchOnClient) return;
+
+ return { runtimeProvider: resolveRuntimeProvider(provider, config?.settings?.sdkType) };
+};
/**
* Where one LLM call of a run executes (T-540 Β§2.1). The server is the
@@ -64,20 +92,10 @@ export const resolveLlmExecutionSite = async ({
userId,
workspaceId,
}: ResolveLlmExecutionSiteParams): Promise<LlmExecutionSite> => {
- if (provider === BRANDING_PROVIDER || provider === ModelProvider.LobeHub) return SERVER;
if (state?.principal?.actor?.shareVisitor) return SERVER;
- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
- if (!featureFlags.enableLlmRelay) return SERVER;
-
- const config = await new AiProviderModel(db, userId, workspaceId).getAiProviderById(
- provider,
- KeyVaultsGateKeeper.getUserKeyVaults,
- );
- const fetchOnClient = resolveFetchOnClient(provider, config?.fetchOnClient) === true;
-
- log('provider=%s fetchOnClient=%s', provider, fetchOnClient);
- if (!fetchOnClient) return SERVER;
+ const relay = await resolveProviderRelay({ db, provider, userId, workspaceId });
+ if (!relay) return SERVER;
const executor = state?.host?.llmExecutor;
const canExecute =
@@ -88,7 +106,7 @@ export const resolveLlmExecutionSite = async ({
return {
preferredClientId: executor.clientId,
- runtimeProvider: resolveRuntimeProvider(provider, config?.settings?.sdkType),
+ runtimeProvider: relay.runtimeProvider,
site: 'client',
};
};
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 4b6a4f759ba..fa84d527eb7 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -196,6 +196,9 @@ export interface IStreamEventManager {
/** Optional: the relayed attempt is over; the gateway stops replaying it. */
closeLlmCall?: (operationId: string, callId: string) => Promise<void>;
+ /** Optional: end a one-shot relay channel's gateway session. */
+ closeLlmRelayChannel?: (channel: string) => Promise<void>;
+
/**
* Close connections
*/
@@ -218,6 +221,12 @@ export interface IStreamEventManager {
*/
getStreamHistory: (operationId: string, count?: number) => Promise<StreamEvent[]>;
+ /**
+ * Optional: open a one-shot relay channel on the gateway, owned by `userId`.
+ * Present only with a gateway, like {@link sendLlmExecute}.
+ */
+ openLlmRelayChannel?: (channel: string, userId: string) => Promise<void>;
+
/**
* Publish Agent runtime end event.
*
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index e4fe87b29eb..531dd18b36d 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -44,9 +44,15 @@ export type {
ToolResultPayload,
} from './mux/types';
export {
+ buildLlmRelayChannelId,
CLIENT_LLM_WAIT_CAPABILITY,
CLIENT_PROTOCOL_VERSION,
+ isLlmRelayChannelId,
+ isOwnLlmRelayChannelId,
LLM_RELAY_CAPABILITY,
+ LLM_RELAY_CHANNEL_HEADER,
+ LLM_RELAY_CHANNEL_PREFIX,
+ LLM_RELAY_CLIENT_ID_HEADER,
LLM_RELAY_LEASE_HEADER,
} from './protocol';
export { isSessionTerminalEvent } from './terminalEvent';
@@ -70,6 +76,7 @@ export type {
LlmRelayBatch,
LlmRelayBatchAck,
LlmRelayDeadlines,
+ LlmRelayMethod,
MessagePatchData,
MessagePatchUpsert,
SessionStatus,
diff --git a/packages/agent-gateway-client/src/protocol.ts b/packages/agent-gateway-client/src/protocol.ts
index e324cfe3ca5..4ff67445a49 100644
--- a/packages/agent-gateway-client/src/protocol.ts
+++ b/packages/agent-gateway-client/src/protocol.ts
@@ -28,3 +28,38 @@ export const CLIENT_LLM_WAIT_CAPABILITY = 'llm_client_wait@1';
/** Header carrying the per-call lease token on the relay endpoints. */
export const LLM_RELAY_LEASE_HEADER = 'x-llm-relay-lease';
+
+// ─── One-shot relay (an LLM call outside any agent run) ───
+
+/**
+ * Prefix of a one-shot relay channel id: `llmcall:<userId>:<nonce>`. The tab
+ * that makes the call generates the id, subscribes to it on the gateway, and
+ * hands it to the server in {@link LLM_RELAY_CHANNEL_HEADER}; the server opens
+ * the channel and dispatches the call's `llm_execute` on it. The user id in the
+ * id keeps a caller from making the server open a channel it does not own.
+ */
+export const LLM_RELAY_CHANNEL_PREFIX = 'llmcall:';
+
+/** Request header: the one-shot channel this tab subscribed to for the call. */
+export const LLM_RELAY_CHANNEL_HEADER = 'x-lobe-llm-relay-channel';
+
+/** Request header: this tab's client id (`getLlmRelayClientId`), the call's preferred executor. */
+export const LLM_RELAY_CLIENT_ID_HEADER = 'x-lobe-client-id';
+
+const CHANNEL_NONCE = /^[\w-]{8,64}$/;
+
+export const buildLlmRelayChannelId = (userId: string, nonce: string) =>
+ `${LLM_RELAY_CHANNEL_PREFIX}${userId}:${nonce}`;
+
+export const isLlmRelayChannelId = (operationId: string | undefined): boolean =>
+ !!operationId?.startsWith(LLM_RELAY_CHANNEL_PREFIX);
+
+/**
+ * Whether `channel` is a well-formed one-shot channel id of `userId`. The
+ * server opens only such channels: anything else could name a real run's
+ * operation or another user's channel.
+ */
+export const isOwnLlmRelayChannelId = (channel: string, userId: string): boolean => {
+ const prefix = buildLlmRelayChannelId(userId, '');
+ return channel.startsWith(prefix) && CHANNEL_NONCE.test(channel.slice(prefix.length));
+};
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index ce9742c6e1b..4c108267545 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -379,6 +379,14 @@ export interface LlmRelayDeadlines {
totalMs: number;
}
+/**
+ * Model-runtime method a relayed call runs on the device. `chat` streams the
+ * normalized protocol chunks; `generateObject` and `models` upload their
+ * return value as JSON text split into `result_part` chunks; `pullModel`
+ * uploads the provider's raw progress stream as `progress` chunks (text).
+ */
+export type LlmRelayMethod = 'chat' | 'generateObject' | 'models' | 'pullModel';
+
/**
* Server β†’ Client (`llm_execute`): run one LLM attempt locally and stream its
* normalized protocol chunks back. Carries no messages and no credentials: the
@@ -397,6 +405,8 @@ export interface LlmExecuteData {
* sent as the `x-llm-relay-lease` header. Expires with the attempt.
*/
leaseToken: string;
+ /** Runtime method to call; absent β‡’ `chat` (servers before one-shot relay). */
+ method?: LlmRelayMethod;
model: string;
operationId: string;
/**
diff --git a/packages/model-bank/src/modelProviders/index.test.ts b/packages/model-bank/src/modelProviders/index.test.ts
index f0f70332c5a..5213252fb57 100644
--- a/packages/model-bank/src/modelProviders/index.test.ts
+++ b/packages/model-bank/src/modelProviders/index.test.ts
@@ -5,6 +5,7 @@ import {
DEFAULT_MODEL_PROVIDER_LIST,
getProviderDisplayName,
isProviderDisableBrowserRequest,
+ isProviderFetchOnClient,
isProviderOAuthDeviceFlow,
} from './index';
@@ -63,3 +64,27 @@ describe('model provider predicates', () => {
expect(isProviderOAuthDeviceFlow()).toBe(false);
});
});
+
+describe('isProviderFetchOnClient', () => {
+ it('runs a local provider on the device unless fetchOnClient says otherwise', () => {
+ expect(isProviderFetchOnClient('lmstudio', undefined)).toBe(true);
+ expect(isProviderFetchOnClient('ollama', { keyVaults: {} })).toBe(true);
+ expect(isProviderFetchOnClient('lmstudio', { fetchOnClient: false })).toBe(false);
+ });
+
+ it('runs on the server without an endpoint or a key', () => {
+ expect(isProviderFetchOnClient('openai', { fetchOnClient: true, keyVaults: {} })).toBe(false);
+ });
+
+ it('runs on the device when only a base URL is set', () => {
+ expect(
+ isProviderFetchOnClient('openai', { keyVaults: { baseURL: 'http://localhost:8000/v1' } }),
+ ).toBe(true);
+ });
+
+ it('follows fetchOnClient with both a base URL and a key, default server', () => {
+ const keyVaults = { apiKey: 'sk', baseURL: 'http://localhost:8000/v1' };
+ expect(isProviderFetchOnClient('openai', { fetchOnClient: true, keyVaults })).toBe(true);
+ expect(isProviderFetchOnClient('openai', { keyVaults })).toBe(false);
+ });
+});
diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.ts
index 134c30c6d8b..f5dc08cb377 100644
--- a/packages/model-bank/src/modelProviders/index.ts
+++ b/packages/model-bank/src/modelProviders/index.ts
@@ -244,6 +244,46 @@ export const isProviderDisableBrowserRequest = (id: string) => {
return !!provider;
};
+/**
+ * Providers that run on the user's own machine: requests leave from the device
+ * unless `fetchOnClient` says otherwise (a desktop app or a deployment that
+ * proxies them sets it to `false`).
+ */
+const LOCAL_FETCH_ON_CLIENT_PROVIDERS = new Set(['lmstudio', 'ollama', 'unsloth']);
+
+export interface ProviderFetchOnClientConfig {
+ /** The user's choice, else the deployment's override for the provider. */
+ fetchOnClient?: boolean;
+ keyVaults?: { apiKey?: string; baseURL?: string };
+}
+
+/**
+ * Whether requests to `provider` must leave from the user's device rather than
+ * the server β€” the single rule the client and the server both apply, so the
+ * server never relays a call the client did not prepare for (or the reverse).
+ *
+ * 1. A provider that disables browser requests always runs on the server.
+ * 2. Local providers (Ollama / LM Studio / Unsloth) follow `fetchOnClient`, default the device.
+ * 3. Neither a base URL nor an API key: the server's own configuration.
+ * 4. Only a base URL: an endpoint the server may not reach, so the device.
+ * 5. Otherwise `fetchOnClient`, default the server.
+ */
+export const isProviderFetchOnClient = (
+ provider: string,
+ config: ProviderFetchOnClientConfig | undefined,
+): boolean => {
+ if (isProviderDisableBrowserRequest(provider)) return false;
+
+ if (LOCAL_FETCH_ON_CLIENT_PROVIDERS.has(provider)) return config?.fetchOnClient ?? true;
+
+ const hasEndpoint = !!config?.keyVaults?.baseURL;
+ const hasApiKey = !!config?.keyVaults?.apiKey;
+ if (!hasEndpoint && !hasApiKey) return false;
+ if (hasEndpoint && !hasApiKey) return true;
+
+ return config?.fetchOnClient ?? false;
+};
+
/**
* Human-readable provider name for a provider id (`meta` β†’ `Meta`). Unknown ids
* (custom providers, typos) fall back to the id itself so callers always get a
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index e408846b2e4..14c38921e83 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -242,6 +242,32 @@ describe('createLambdaContext', () => {
});
});
+ it('should carry the one-shot relay headers of the requesting tab', async () => {
+ const channel = 'llmcall:user-1:0b7c1d2e-aaaa';
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: { 'x-lobe-client-id': 'tab-a', 'x-lobe-llm-relay-channel': channel },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(context.llmRelay).toEqual({ channel, clientId: 'tab-a' });
+ });
+
+ // Procedures of one batch share the request headers but each opens its own
+ // relay scope: they would share the channel and its call ids. The browser
+ // sends relayed calls unbatched, so a batch never gets relayed.
+ it('should ignore the one-shot relay headers on a batched request', async () => {
+ const channel = 'llmcall:user-1:0b7c1d2e-aaaa';
+ const request = new NextRequest(
+ 'https://example.com/trpc/lambda/task.analyzeIntent,verify.generateGoalPlan?batch=1',
+ { headers: { 'x-lobe-client-id': 'tab-a', 'x-lobe-llm-relay-channel': channel } },
+ );
+
+ const context = await createLambdaContext(request);
+
+ expect(context.llmRelay).toBeUndefined();
+ });
+
it('should resolve clientIp through the overridable request IP module', async () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: { 'x-forwarded-for': '198.51.100.3, 10.0.0.1' },
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 454a08e7803..45f14175ed0 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -16,6 +16,10 @@ import { authEnv, LOBE_CHAT_OIDC_AUTH_HEADER } from '@/envs/auth';
import { extractTraceContext } from '@/libs/observability/traceparent';
import { assertOIDCUserActive, isOIDCUserInactiveError } from '@/libs/oidc-provider/access-control';
import { validateOIDCJWT } from '@/libs/oidc-provider/jwt';
+import {
+ type LlmRelayRequest,
+ readLlmRelayRequest,
+} from '@/server/modules/AgentRuntime/llmRelay/requestScope';
import { isApiKeyExpired, validateApiKeyFormat } from '@/utils/apiKey';
import { getRequestClientIP } from '@/utils/requestClientIP';
@@ -96,6 +100,12 @@ export interface AuthContext {
clientIp?: string | null;
clientMetadata?: ClientMetadata;
jwtPayload?: ClientSecretPayload | null;
+ /**
+ * The browser tab this request came from, when it subscribed a one-shot
+ * relay channel for the request's LLM calls (provider only reachable from
+ * the user's device). See `runWithLlmRelayRequest`.
+ */
+ llmRelay?: LlmRelayRequest;
marketAccessToken?: string;
oidcAuth?: OIDCAuth | null;
oidcClientId?: string;
@@ -128,6 +138,7 @@ export const createContextInner = async (params?: {
authFailure?: string;
clientMetadata?: ClientMetadata;
clientIp?: string | null;
+ llmRelay?: LlmRelayRequest;
marketAccessToken?: string;
oidcAuth?: OIDCAuth | null;
oidcClientId?: string;
@@ -149,6 +160,7 @@ export const createContextInner = async (params?: {
apiKeyScopes: params?.apiKeyScopes,
clientMetadata: params?.clientMetadata || { type: 'unknown' },
clientIp: params?.clientIp,
+ llmRelay: params?.llmRelay,
marketAccessToken: params?.marketAccessToken,
oidcAuth: params?.oidcAuth,
oidcClientId: params?.oidcClientId,
@@ -203,9 +215,15 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
log('marketAccessToken from cookie:', marketAccessToken ? '[HIDDEN]' : 'undefined');
const workspaceId = request.headers.get('X-Workspace-Id')?.trim() || undefined;
+ // One-shot relay headers name one channel for one procedure: procedures of a
+ // batch would share it (and its call ids). The browser sends relayed calls
+ // unbatched, so a batch is never relayed.
+ const isBatch = request.nextUrl.searchParams.get('batch') === '1';
+
const commonContext = {
clientMetadata,
clientIp,
+ llmRelay: isBatch ? undefined : readLlmRelayRequest(request.headers),
marketAccessToken,
userAgent,
workspaceId,
diff --git a/packages/trpc/src/lambda/index.ts b/packages/trpc/src/lambda/index.ts
index 103586f98f5..721fe1c109f 100644
--- a/packages/trpc/src/lambda/index.ts
+++ b/packages/trpc/src/lambda/index.ts
@@ -15,6 +15,7 @@ import { userAuth } from '../middleware/userAuth';
import { trpc } from './init';
import { apiKeyScopeGuard } from './middleware/apiKeyScope';
import { heteroOperationAuth } from './middleware/heteroOperationAuth';
+import { llmRelayRequest } from './middleware/llmRelayRequest';
import { oidcAuth } from './middleware/oidcAuth';
/**
@@ -38,7 +39,13 @@ export const publicProcedure = baseProcedure.use(apiKeyScopeGuard);
// procedure that asserts that the user is logged in
// `apiKeyScopeGuard` narrows API-key-authenticated calls to the key's scopes;
// session/OIDC auth and full-access keys pass through untouched.
-export const authedProcedure = baseProcedure.use(oidcAuth).use(userAuth).use(apiKeyScopeGuard);
+// `llmRelayRequest` relays the procedure's LLM calls to a device-only provider
+// back to the requesting tab (one-shot relay).
+export const authedProcedure = baseProcedure
+ .use(oidcAuth)
+ .use(userAuth)
+ .use(apiKeyScopeGuard)
+ .use(llmRelayRequest);
// procedure for hetero-agent ingest/finish endpoints β€” requires a `hetero-operation` JWT
export const heteroAuthedProcedure = baseProcedure.use(heteroOperationAuth).use(userAuth);
diff --git a/packages/trpc/src/lambda/middleware/llmRelayRequest.ts b/packages/trpc/src/lambda/middleware/llmRelayRequest.ts
new file mode 100644
index 00000000000..4cdc614df26
--- /dev/null
+++ b/packages/trpc/src/lambda/middleware/llmRelayRequest.ts
@@ -0,0 +1,12 @@
+import { runWithLlmRelayRequest } from '@/server/modules/AgentRuntime/llmRelay/requestScope';
+
+import { trpc } from '../init';
+
+/**
+ * Runs the procedure as a request whose LLM calls to a device-only provider
+ * are relayed back to the tab that sent it (`ctx.llmRelay`, from the one-shot
+ * relay headers). A no-op for requests without them.
+ */
+export const llmRelayRequest = trpc.middleware(async ({ ctx, next }) =>
+ runWithLlmRelayRequest(ctx.llmRelay, ctx.userId, () => next()),
+);
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 45bc815e77d..e1f5217cdc2 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -151,6 +151,11 @@ export interface GlobalServerConfig {
enableMultimodalUnderstanding?: boolean;
enableUploadFileToServer?: boolean;
image?: PartialDeep<UserImageConfig>;
+ /**
+ * Whether the server can relay an LLM call to a browser tab (Agent Gateway
+ * with its service token + Redis). The one-shot relay is used only then.
+ */
+ llmRelayAvailable?: boolean;
memory?: GlobalMemoryConfig;
multimodalUnderstanding?: MultimodalUnderstandingConfig;
oAuthSSOProviders?: string[];
diff --git a/src/store/aiInfra/slices/aiProvider/selectors.ts b/src/store/aiInfra/slices/aiProvider/selectors.ts
index 17d325628a1..7d299aec6de 100644
--- a/src/store/aiInfra/slices/aiProvider/selectors.ts
+++ b/src/store/aiInfra/slices/aiProvider/selectors.ts
@@ -1,4 +1,4 @@
-import { isProviderDisableBrowserRequest } from 'model-bank/modelProviders';
+import { isProviderFetchOnClient as isSharedProviderFetchOnClient } from 'model-bank/modelProviders';
import { type AIProviderStoreState } from '@/store/aiInfra/initialState';
import { type AiProviderRuntimeConfig } from '@/types/aiProvider';
@@ -49,8 +49,6 @@ const activeProviderConfig = (s: AIProviderStoreState) =>
const isAiProviderConfigLoading = (id: string) => (s: AIProviderStoreState) =>
!s.aiProviderDetailMap[id];
-const providerWhitelist = new Set(['ollama', 'lmstudio', 'unsloth']);
-
const activeProviderKeyVaults = (s: AIProviderStoreState) => activeProviderConfig(s)?.keyVaults;
const isActiveProviderEndpointNotEmpty = (s: AIProviderStoreState) => {
@@ -75,37 +73,13 @@ const isProviderConfigUpdating = (id: string) => (s: AIProviderStoreState) =>
s.aiProviderConfigUpdatingIds.includes(id);
/**
- * @description The conditions to enable client fetch
- * 1. If no baseUrl and apikey input, force on Server.
- * 2. If only contains baseUrl, force on Client
- * 3. Follow the user settings.
- * 4. On Server, by default.
+ * Whether requests to this provider leave from this device. The rule is shared
+ * with the server (`isProviderFetchOnClient` in model-bank), which relays a
+ * call back to this tab exactly when it applies.
*/
const isProviderFetchOnClient =
- (provider: GlobalLLMProviderKey | string) => (s: AIProviderStoreState) => {
- const config = providerConfigById(provider)(s);
-
- // If the provider already disable browser request in model config, force on Server.
- if (isProviderDisableBrowserRequest(provider)) return false;
-
- // If the provider in the whitelist, follow the user settings
- if (providerWhitelist.has(provider) && typeof config?.fetchOnClient !== 'undefined')
- return config?.fetchOnClient;
-
- // 1. If no baseUrl and apikey input, force on Server.
- const isProviderEndpointNotEmpty = !!config?.keyVaults.baseURL;
- const isProviderApiKeyNotEmpty = !!config?.keyVaults.apiKey;
- if (!isProviderEndpointNotEmpty && !isProviderApiKeyNotEmpty) return false;
-
- // 2. If only contains baseUrl, force on Client
- if (isProviderEndpointNotEmpty && !isProviderApiKeyNotEmpty) return true;
-
- // 3. Follow the user settings.
- if (typeof config?.fetchOnClient !== 'undefined') return config?.fetchOnClient;
-
- // 4. On Server, by default.
- return false;
- };
+ (provider: GlobalLLMProviderKey | string) => (s: AIProviderStoreState) =>
+ isSharedProviderFetchOnClient(provider, providerConfigById(provider)(s));
const providerKeyVaults = (provider: string | undefined) => (s: AIProviderStoreState) => {
if (!provider) return undefined;