π€― 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(agent-runtime): run relayed LLM attempts on the client β executor (behind agent_llm_relay) (#20336)
Arvin Xuf32cc386b9c2
diff --git a/apps/desktop/src/main/const/__tests__/protocol.test.ts b/apps/desktop/src/main/const/__tests__/protocol.test.tsnew file mode 100644index 00000000000..818f5379241--- /dev/null+++ b/apps/desktop/src/main/const/__tests__/protocol.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { isBackendPath } from '../protocol';++describe('isBackendPath', () => {+ // The renderer runs relayed local-model calls and uploads their output to+ // the remote server; served as a static asset instead, the claim gets a 404.+ it('proxies the LLM relay endpoints to the remote server', () => {+ expect(isBackendPath('/api/agent/llm-relay/op-1%3A0%3A1/payload')).toBe(true);+ expect(isBackendPath('/api/agent/llm-relay/op-1%3A0%3A1/chunks')).toBe(true);+ });++ it('keeps other /api/agent paths and lookalike prefixes local', () => {+ expect(isBackendPath('/api/agent/run')).toBe(false);+ expect(isBackendPath('/api/agent/llm-relayx')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/const/protocol.ts b/apps/desktop/src/main/const/protocol.tsindex 57c8741c900..1129fe02d40 100644--- a/apps/desktop/src/main/const/protocol.ts+++ b/apps/desktop/src/main/const/protocol.ts@@ -4,13 +4,21 @@ export const LOCAL_FILE_PROTOCOL_HOST = 'file';/*** Renderer pathnames that must be proxied to the remote LobeHub backend* instead of being served as static assets. Covers tRPC, webapi, NextAuth,- * and the marketplace REST + OIDC token/userinfo/handoff endpoints.+ * the marketplace REST + OIDC token/userinfo/handoff endpoints, and the LLM+ * relay upload channel (`/api/agent/llm-relay/:callId/{payload,chunks}`) the+ * desktop uses to run local-model calls for server-driven runs.** `/lobehub-oidc/*` is intentionally NOT here β those URLs are handed to* `shell.openExternal` as fully-qualified web URLs and never reach renderer* `fetch`.*/-export const BACKEND_PATH_PREFIXES = ['/trpc', '/webapi', '/api/auth', '/market'];+export const BACKEND_PATH_PREFIXES = [+ '/trpc',+ '/webapi',+ '/api/auth',+ '/api/agent/llm-relay',+ '/market',+];export const isBackendPath = (pathname: string) =>BACKEND_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.tsindex 387258b4a6c..50a71cc0604 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts@@ -1,6 +1,7 @@import { createHmac, timingSafeEqual } from 'node:crypto';import type { LlmRelayDeadlines } from '@lobechat/agent-gateway-client';+import { LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER } from '@lobechat/agent-gateway-client';/*** Shared constants and keys of the LLM relay: a server-driven agent loop hands@@ -16,9 +17,7 @@ import type { LlmRelayDeadlines } from '@lobechat/agent-gateway-client';* - `llm_relay:stream:{callId}` Redis Stream of uploaded batches (`seq`, `body`)*/-export const LLM_RELAY_CAPABILITY = 'llm_relay@1';--export const LLM_RELAY_LEASE_HEADER = 'x-llm-relay-lease';+export { LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER };/** Upper bound of the whole attempt; keeps it inside a 600s step invocation. */const MAX_TOTAL_MS = 540_000;diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex 9c6b64bef92..77d606d0724 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -129,6 +129,18 @@ describe('AgentStreamClient', () => {expect(JSON.parse(ws.sent[0])).toEqual({ token: 'test-token', type: 'auth' });});+ it('should send its client id with auth so the gateway can target it', async () => {+ const client = createClient({ clientId: 'tab-1' });+ client.connect();+ await vi.advanceTimersByTimeAsync(1);++ expect(JSON.parse(getLatestWs().sent[0])).toEqual({+ clientId: 'tab-1',+ token: 'test-token',+ type: 'auth',+ });+ });+it('should transition through connection states', async () => {const client = createClient();const statuses: ConnectionStatus[] = [];diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 0967ceb9866..be359564d74 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -79,6 +79,7 @@ export class AgentStreamClient extends TypedEmitter {private resumeMode = false;private resumeFlushTimer: ReturnType<typeof setTimeout> | null = null;+ private readonly clientId?: string;private readonly gatewayUrl: string;private readonly operationId: string;private readonly autoReconnect: boolean;@@ -88,6 +89,7 @@ export class AgentStreamClient extends TypedEmitter {constructor(options: AgentStreamClientOptions) {super();+ this.clientId = options.clientId;this.gatewayUrl = options.gatewayUrl;this.operationId = options.operationId;this.token = options.token;@@ -216,7 +218,11 @@ export class AgentStreamClient extends TypedEmitter {private handleOpen = (): void => {this.reconnectDelay = INITIAL_RECONNECT_DELAY;this.setStatus('authenticating');- this.sendMessage({ token: this.token, type: 'auth' });+ this.sendMessage({+ ...(this.clientId && { clientId: this.clientId }),+ token: this.token,+ type: 'auth',+ });};private handleMessage = (event: MessageEvent): void => {diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 77b954819a0..64c5636a15b 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -43,7 +43,7 @@ export type {ResumeCompleteInfo,ToolResultPayload,} from './mux/types';-export { CLIENT_PROTOCOL_VERSION } from './protocol';+export { CLIENT_PROTOCOL_VERSION, LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER } from './protocol';export type {AgentInterventionInteractionKind,AgentInterventionProvider,diff --git a/packages/agent-gateway-client/src/protocol.ts b/packages/agent-gateway-client/src/protocol.tsindex c1a91f840e9..7c7538cedc1 100644--- a/packages/agent-gateway-client/src/protocol.ts+++ b/packages/agent-gateway-client/src/protocol.ts@@ -10,3 +10,13 @@* this constant is exactly what tells the two apart.*/export const CLIENT_PROTOCOL_VERSION = 2 as const;++/**+ * LLM relay protocol a client declares in `execAgent`'s `llmExecutor` when it+ * can run relayed LLM attempts (`llm_execute`). The server relays only to a+ * client that declares a version it speaks.+ */+export const LLM_RELAY_CAPABILITY = 'llm_relay@1';++/** Header carrying the per-call lease token on the relay endpoints. */+export const LLM_RELAY_LEASE_HEADER = 'x-llm-relay-lease';diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex bf9e1a9dd65..0d702909a42 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -440,6 +440,11 @@ export interface LlmRelayBatchAck {// Client β Serverexport interface AuthMessage {+ /**+ * This page's client id. The gateway delivers `llm_execute` to the client+ * that started the run (`preferredClientId`); older gateways ignore it.+ */+ clientId?: string;token: string;type: 'auth';}@@ -606,6 +611,11 @@ export interface AgentStreamClientEvents {export interface AgentStreamClientOptions {/** Auto-reconnect with lastEventId resume (default: true) */autoReconnect?: boolean;+ /**+ * This page's client id, sent with `auth` so the gateway can route+ * client-targeted events (`llm_execute`) to it. Absent β not sent.+ */+ clientId?: string;/** Gateway WebSocket URL base (e.g. https://gateway.lobehub.com) */gatewayUrl: string;/**diff --git a/src/services/aiAgent.execAgentTask.test.ts b/src/services/aiAgent.execAgentTask.test.tsindex df9db0a6385..5cd8205d7f3 100644--- a/src/services/aiAgent.execAgentTask.test.ts+++ b/src/services/aiAgent.execAgentTask.test.ts@@ -2,7 +2,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { aiAgentService } from './aiAgent';-const mocks = vi.hoisted(() => ({ execAgent: vi.fn() }));+const mocks = vi.hoisted(() => ({ execAgent: vi.fn(), llmExecutor: vi.fn() }));++vi.mock('@/services/llmRelay', () => ({ buildLlmExecutorDeclaration: mocks.llmExecutor }));vi.mock('@/libs/trpc/client', () => ({lambdaClient: { aiAgent: { execAgent: { mutate: mocks.execAgent } } },@@ -26,4 +28,19 @@ describe('aiAgentService.execAgentTask', () => {{ signal },);});++ // Inside the `agent_llm_relay` rollout the tab offers to execute relayed LLM+ // calls; the server only relays to a run that carries this declaration.+ it('declares this tab as an LLM relay executor when the rollout includes it', async () => {+ const llmExecutor = { capabilities: ['llm_relay@1'], clientId: 'tab-1', providers: ['ollama'] };+ mocks.llmExecutor.mockReturnValueOnce(llmExecutor);+ mocks.execAgent.mockResolvedValueOnce({ success: true });++ await aiAgentService.execAgentTask({ agentId: 'agt-1', prompt: 'hi' });++ expect(mocks.execAgent).toHaveBeenCalledWith(+ expect.objectContaining({ llmExecutor }),+ undefined,+ );+ });});diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 525de64013b..e5ca22239d7 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -11,6 +11,7 @@ import type {import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';import { lambdaClient } from '@/libs/trpc/client';+import { buildLlmExecutorDeclaration } from '@/services/llmRelay';export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };@@ -281,9 +282,18 @@ class AiAgentService {// older bundle needs to render the run at all. A caller may still pin it// (a replay harness asserting v1 delivery).const clientProtocol = canUseGatewayProtocolV2() ? CLIENT_PROTOCOL_VERSION : undefined;+ // Inside the `agent_llm_relay` rollout this tab offers to run the LLM calls+ // of providers only this device can reach (a local Ollama, a private+ // endpoint); the server hands them over as `llm_execute`.+ const llmExecutor = buildLlmExecutorDeclaration();return await lambdaClient.aiAgent.execAgent.mutate(- { clientProtocol, ...params, streamFeatures: STREAM_FEATURES },+ {+ clientProtocol,+ ...(llmExecutor && { llmExecutor }),+ ...params,+ streamFeatures: STREAM_FEATURES,+ },options,);}diff --git a/src/services/llmRelay/batchUploader.ts b/src/services/llmRelay/batchUploader.tsnew file mode 100644index 00000000000..f4a0590870b--- /dev/null+++ b/src/services/llmRelay/batchUploader.ts@@ -0,0 +1,253 @@+import type { LlmRelayBatch, LlmRelayBatchAck } from '@lobechat/agent-gateway-client';+import { LLM_RELAY_LEASE_HEADER } from '@lobechat/agent-gateway-client';++import type { RelayProtocolChunk } from './protocolChunks';++/** Flush the pending chunks at most this long after the first one arrived. */+export const LLM_RELAY_FLUSH_INTERVAL_MS = 200;+/** Flush right away once this many bytes are pending. */+export const LLM_RELAY_FLUSH_BYTES = 64 * 1024;+/** Send an empty batch when nothing went out for this long (model cold start). */+export const LLM_RELAY_HEARTBEAT_MS = 10_000;++const MAX_SEND_ATTEMPTS = 3;+/** One upload request; a stalled one is retried, not waited on forever. */+export const LLM_RELAY_REQUEST_TIMEOUT_MS = 10_000;+const RETRY_BASE_DELAY_MS = 500;++/**+ * Why the server refused this client's upload. Every one of them means "stop+ * working on this call": another client owns it (`claimed`), it is over+ * (`closed`, `cancelled`), or this client may not write it (`unauthorized`,+ * `too_large`).+ */+export type RelayUploadRejection =+ 'cancelled' | 'claimed' | 'closed' | 'too_large' | 'unauthorized' | 'unreachable';++export class RelayUploadRejectedError extends Error {+ constructor(readonly reason: RelayUploadRejection) {+ super(`LLM relay upload rejected: ${reason}`);+ this.name = 'RelayUploadRejectedError';+ }+}++const rejectionOf = (status: number): RelayUploadRejection | undefined => {+ switch (status) {+ case 401:+ case 403: {+ return 'unauthorized';+ }+ case 409: {+ return 'claimed';+ }+ case 410: {+ return 'closed';+ }+ case 413: {+ return 'too_large';+ }+ }+};++export interface RelayBatchUploaderOptions {+ callId: string;+ clientId: string;+ fetch?: typeof fetch;+ leaseToken: string;+ /** Called once when the server refuses an upload; the call must stop. */+ onRejected: (reason: RelayUploadRejection) => void;+ /** Base of the relay endpoints, `''` for same-origin. */+ serverBaseUrl?: string;+}++/**+ * Client half of the relay's upload channel (T-540 Β§3.2): collects the+ * attempt's protocol chunks and posts them as numbered batches to+ * `POST /api/agent/llm-relay/:callId/chunks`.+ *+ * - batches go out every 200 ms or at 64 KB, one request at a time, so `seq`+ * reaches the server in order; a transient failure retries the same `seq`,+ * which the server dedupes+ * - an empty batch is sent after 10 s without output, so a model that is+ * still loading is not taken for a lost executor+ * - any refusal (`409` claimed elsewhere, `410` closed, `cancel: true` on the+ * ack, β¦) is reported once through `onRejected` and ends the upload+ */+export class RelayBatchUploader {+ private seq = 0;+ private pending: RelayProtocolChunk[] = [];+ private pendingBytes = 0;+ private flushTimer: ReturnType<typeof setTimeout> | undefined;+ private heartbeatTimer: ReturnType<typeof setInterval> | undefined;+ private lastSentAt = 0;+ private sending: Promise<void> = Promise.resolve();+ private rejected: RelayUploadRejection | undefined;+ private finished = false;+ /** Aborts the upload request in flight once the uploader is disposed. */+ private readonly inFlight = new AbortController();++ constructor(private readonly options: RelayBatchUploaderOptions) {}++ get rejection() {+ return this.rejected;+ }++ /**+ * Claim the call with an empty first batch. Resolves `true` when this client+ * now owns the call; `false` when the server gave it to someone else or it+ * is already over.+ */+ async claim(): Promise<boolean> {+ await this.enqueueSend([]);+ // Refused, or disposed while the claim was in flight.+ if (this.rejected || this.inFlight.signal.aborted) return false;++ this.heartbeatTimer = setInterval(() => {+ if (this.finished || this.rejected || this.pending.length > 0) return;+ if (Date.now() - this.lastSentAt >= LLM_RELAY_HEARTBEAT_MS) void this.enqueueSend([]);+ }, LLM_RELAY_HEARTBEAT_MS / 2);++ return true;+ }++ push(chunk: RelayProtocolChunk) {+ if (this.finished || this.rejected) return;++ this.pending.push(chunk);+ this.pendingBytes += JSON.stringify(chunk).length;++ // Also flush on arrival once the interval has passed: a background tab's+ // timers are throttled (down to once a minute), the model's chunks are not.+ if (+ this.pendingBytes >= LLM_RELAY_FLUSH_BYTES ||+ Date.now() - this.lastSentAt >= LLM_RELAY_FLUSH_INTERVAL_MS+ ) {+ this.flush();+ return;+ }+ this.flushTimer ??= setTimeout(() => this.flush(), LLM_RELAY_FLUSH_INTERVAL_MS);+ }++ /** Send everything still pending together with the attempt's final marker. */+ async finish(final: NonNullable<LlmRelayBatch['final']>): Promise<void> {+ if (this.finished) return this.sending;+ this.finished = true;+ this.stopTimers();++ if (!this.rejected) {+ const chunks = this.takePending();+ void this.enqueueSend(chunks, final);+ }+ await this.sending;+ }++ /** Stop without telling the server (it already knows, or refused us). */+ dispose() {+ this.finished = true;+ this.inFlight.abort();+ this.stopTimers();+ this.pending = [];+ this.pendingBytes = 0;+ }++ private flush() {+ if (this.flushTimer) {+ clearTimeout(this.flushTimer);+ this.flushTimer = undefined;+ }+ if (this.pending.length === 0 || this.rejected) return;+ void this.enqueueSend(this.takePending());+ }++ private takePending() {+ const chunks = this.pending;+ this.pending = [];+ this.pendingBytes = 0;+ if (this.flushTimer) {+ clearTimeout(this.flushTimer);+ this.flushTimer = undefined;+ }+ return chunks;+ }++ private stopTimers() {+ if (this.flushTimer) clearTimeout(this.flushTimer);+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);+ this.flushTimer = undefined;+ this.heartbeatTimer = undefined;+ }++ private enqueueSend(chunks: RelayProtocolChunk[], final?: LlmRelayBatch['final']) {+ this.seq += 1;+ const batch: LlmRelayBatch = {+ chunks,+ clientId: this.options.clientId,+ ...(final && { final }),+ seq: this.seq,+ };+ this.lastSentAt = Date.now();+ this.sending = this.sending.then(() => this.send(batch));+ return this.sending;+ }++ private async send(batch: LlmRelayBatch): Promise<void> {+ // Queued behind a request that `dispose()` aborted: never start it.+ if (this.rejected || this.inFlight.signal.aborted) return;++ const { callId, leaseToken, serverBaseUrl = '' } = this.options;+ const doFetch = this.options.fetch ?? fetch;+ const body = JSON.stringify(batch);++ for (let attempt = 1; attempt <= MAX_SEND_ATTEMPTS; attempt += 1) {+ if (this.inFlight.signal.aborted) return;+ const request = new AbortController();+ const abortRequest = () => request.abort();+ this.inFlight.signal.addEventListener('abort', abortRequest, { once: true });+ const timeout = setTimeout(abortRequest, LLM_RELAY_REQUEST_TIMEOUT_MS);+ try {+ const response = await doFetch(+ `${serverBaseUrl}/api/agent/llm-relay/${encodeURIComponent(callId)}/chunks`,+ {+ body,+ headers: { 'content-type': 'application/json', [LLM_RELAY_LEASE_HEADER]: leaseToken },+ method: 'POST',+ signal: request.signal,+ },+ );++ const rejection = rejectionOf(response.status);+ if (rejection) return this.reject(rejection);++ if (response.ok) {+ const ack = (await response.json().catch(() => ({}))) as Partial<LlmRelayBatchAck>;+ if (ack.cancel) this.reject('cancelled');+ return;+ }+ } catch {+ if (this.inFlight.signal.aborted) return;+ // Network failure or a stalled request: retry the same seq below;+ // the server dedupes it.+ } finally {+ clearTimeout(timeout);+ this.inFlight.signal.removeEventListener('abort', abortRequest);+ }++ if (attempt < MAX_SEND_ATTEMPTS) {+ await new Promise((resolve) =>+ setTimeout(resolve, RETRY_BASE_DELAY_MS * 2 ** (attempt - 1)),+ );+ }+ }++ // The server stays unreachable. Its idle deadline re-dispatches the+ // attempt; this client stops instead of streaming into the void.+ this.reject('unreachable');+ }++ private reject(reason: RelayUploadRejection) {+ if (this.rejected) return;+ this.rejected = reason;+ this.stopTimers();+ this.options.onRejected(reason);+ }+}diff --git a/src/services/llmRelay/clientId.ts b/src/services/llmRelay/clientId.tsnew file mode 100644index 00000000000..dbe30d1defd--- /dev/null+++ b/src/services/llmRelay/clientId.ts@@ -0,0 +1,20 @@+const randomClientId = (): string =>+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'+ ? crypto.randomUUID()+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;++let clientId: string | undefined;++/**+ * This page's id towards the Agent Gateway and the LLM relay.+ *+ * One value per page load, shared by the multiplexed socket (`?clientId=`),+ * the v1 socket's `auth` message and `execAgent`'s `llmExecutor.clientId`, so+ * the gateway can hand a run's `llm_execute` to the tab that started it. A+ * reload is a new client on purpose: the old page's in-flight attempts died+ * with it.+ */+export const getLlmRelayClientId = (): string => {+ clientId ??= randomClientId();+ return clientId;+};diff --git a/src/services/llmRelay/executor.test.ts b/src/services/llmRelay/executor.test.tsnew file mode 100644index 00000000000..d235ed09fd8--- /dev/null+++ b/src/services/llmRelay/executor.test.ts@@ -0,0 +1,480 @@+import type { LlmExecuteData, LlmRelayBatch } from '@lobechat/agent-gateway-client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ LLM_RELAY_FLUSH_BYTES,+ LLM_RELAY_HEARTBEAT_MS,+ LLM_RELAY_REQUEST_TIMEOUT_MS,+ RelayBatchUploader,+} from './batchUploader';+import type { RelayRuntime } from './executor';+import { LlmRelayExecutor, NON_PREFERRED_CLAIM_DELAY_MS } from './executor';++const PAYLOAD = { messages: [{ content: 'hi', role: 'user' }], model: 'qwen3', stream: true };++const callData = (overrides: Partial<LlmExecuteData> = {}): LlmExecuteData => ({+ assistantMessageId: 'msg-1',+ attempt: 1,+ callId: 'op-1:0:1',+ deadlines: { claimMs: 15_000, firstChunkMs: 120_000, idleMs: 60_000, totalMs: 540_000 },+ leaseToken: 'lease-1',+ model: 'qwen3',+ operationId: 'op-1',+ preferredClientId: 'tab-1',+ provider: 'ollama',+ runtimeProvider: 'ollama',+ stepIndex: 0,+ ...overrides,+});++/** Fake relay endpoints: records every batch, answers like the server would. */+const createServer = (+ answer: (batch: LlmRelayBatch) => { body?: unknown; status: number } = () => ({ status: 200 }),+) => {+ const batches: LlmRelayBatch[] = [];+ const payloadRequests: RequestInit[] = [];+ const fetchMock = vi.fn(async (url: string, init: RequestInit = {}) => {+ if (url.endsWith('/payload')) {+ payloadRequests.push(init);+ return new Response(JSON.stringify(PAYLOAD), { status: 200 });+ }+ const batch = JSON.parse(init.body as string) as LlmRelayBatch;+ batches.push(batch);+ const { body, status } = answer(batch);+ return new Response(JSON.stringify(body ?? { ackSeq: batch.seq }), { status });+ });+ return { batches, fetch: fetchMock as unknown as typeof fetch, payloadRequests };+};++/** A model whose SSE output the test pushes chunk by chunk. */+const createModel = () => {+ let controller!: ReadableStreamDefaultController<Uint8Array>;+ const encoder = new TextEncoder();+ const body = new ReadableStream<Uint8Array>({+ start(c) {+ controller = c;+ },+ });+ const calls: Array<{ payload: unknown; signal?: AbortSignal }> = [];+ const runtime: RelayRuntime = {+ chat: vi.fn(async (payload, { signal }) => {+ calls.push({ payload, signal });+ signal?.addEventListener('abort', () => controller.error(new Error('aborted')));+ return new Response(body);+ }),+ };+ return {+ calls,+ close: () => controller.close(),+ emit: (type: string, data: unknown) =>+ controller.enqueue(+ encoder.encode(`id: chat_1\nevent: ${type}\ndata: ${JSON.stringify(data)}\n\n`),+ ),+ runtime,+ };+};++const waitFor = async (predicate: () => boolean) => {+ await vi.waitFor(() => expect(predicate()).toBe(true), { timeout: 3000 });+};++afterEach(() => {+ vi.useRealTimers();+});++describe('LlmRelayExecutor', () => {+ it('claims the call, runs the model locally and uploads its chunks in order', async () => {+ const server = createServer();+ const model = createModel();+ const createRuntime = vi.fn(async () => model.runtime);+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime,+ fetch: server.fetch,+ });+ const output: unknown[] = [];++ const done = executor.execute(callData(), { onOutput: (chunk) => output.push(chunk) });++ await waitFor(() => model.calls.length === 1);+ // The empty claim batch goes out before the model is called.+ expect(server.batches[0]).toEqual({ chunks: [], clientId: 'tab-1', seq: 1 });+ expect(executor.ownsCall('op-1:0:1')).toBe(true);+ expect(new Headers(server.payloadRequests[0].headers).get('x-llm-relay-lease')).toBe('lease-1');+ expect(createRuntime).toHaveBeenCalledWith({+ payload: PAYLOAD,+ provider: 'ollama',+ runtimeProvider: 'ollama',+ });+ expect(model.calls[0].payload).toEqual(PAYLOAD);++ model.emit('text', 'Hello');+ model.emit('text', ' world');+ model.emit('usage', { totalTokens: 7 });+ model.close();+ await done;++ const uploaded = server.batches.flatMap((batch) => batch.chunks);+ expect(uploaded).toEqual([+ { data: 'Hello', id: 'chat_1', type: 'text' },+ { data: ' world', id: 'chat_1', type: 'text' },+ { data: { totalTokens: 7 }, id: 'chat_1', type: 'usage' },+ ]);+ expect(server.batches.map((batch) => batch.seq)).toEqual(+ server.batches.map((_, index) => index + 1),+ );+ expect(server.batches.at(-1)?.final).toEqual({ reason: 'done' });+ expect(output).toEqual(uploaded);+ });++ it('stops without calling the model when another client already claimed the call', async () => {+ const server = createServer(() => ({ body: { cancel: true }, status: 409 }));+ const createRuntime = vi.fn();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime,+ fetch: server.fetch,+ });++ await executor.execute(callData());++ expect(createRuntime).not.toHaveBeenCalled();+ expect(server.batches).toHaveLength(1);+ expect(executor.ownsCall('op-1:0:1')).toBe(false);+ });++ it('aborts the local model request on llm_cancel and reports the attempt aborted', async () => {+ const server = createServer();+ const model = createModel();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => model.runtime,+ fetch: server.fetch,+ });++ const done = executor.execute(callData());+ await waitFor(() => model.calls.length === 1);+ model.emit('text', 'partial');++ executor.cancel({ callId: 'op-1:0:1', reason: 'interrupted' });+ await done;++ expect(model.calls[0].signal?.aborted).toBe(true);+ expect(server.batches.at(-1)?.final).toEqual({ reason: 'aborted' });+ expect(executor.isRunning('op-1:0:1')).toBe(false);+ });++ it('drops the attempt silently when its run ends before llm_cancel arrives', async () => {+ const server = createServer();+ const model = createModel();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => model.runtime,+ fetch: server.fetch,+ });++ const done = executor.execute(callData());+ await waitFor(() => model.calls.length === 1);+ model.emit('text', 'partial');++ executor.cancelOperation('other-op');+ expect(executor.isRunning('op-1:0:1')).toBe(true);++ executor.cancelOperation('op-1');+ await done;++ expect(model.calls[0].signal?.aborted).toBe(true);+ // The server already settled the step: no `aborted` batch that could read+ // as a lost executor and trigger a re-dispatch.+ expect(server.batches.some((batch) => batch.final)).toBe(false);+ });++ it('stops as soon as an upload ack says the server no longer wants the attempt', async () => {+ const server = createServer((batch) =>+ batch.chunks.length > 0+ ? { body: { ackSeq: batch.seq, cancel: true }, status: 200 }+ : { status: 200 },+ );+ const model = createModel();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => model.runtime,+ fetch: server.fetch,+ });++ const done = executor.execute(callData());+ await waitFor(() => model.calls.length === 1);+ model.emit('text', 'one');+ await done;++ expect(model.calls[0].signal?.aborted).toBe(true);+ // Nothing is uploaded after the refusal, not even a final batch.+ expect(server.batches.some((batch) => batch.final)).toBe(false);+ });++ it('uploads the provider error as the final batch so the server classifies it', async () => {+ const server = createServer();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime: async () => ({+ chat: async () => {+ throw {+ error: new TypeError('Failed to fetch'),+ errorType: 'OllamaServiceUnavailable',+ provider: 'ollama',+ };+ },+ }),+ fetch: server.fetch,+ });++ await executor.execute(callData());++ expect(server.batches.at(-1)?.final).toEqual({+ error: {+ error: { message: 'Failed to fetch', name: 'TypeError' },+ errorType: 'OllamaServiceUnavailable',+ provider: 'ollama',+ },+ reason: 'error',+ });+ });++ it('runs a replayed llm_execute for the same call only once', async () => {+ const server = createServer();+ const model = createModel();+ const createRuntime = vi.fn(async () => model.runtime);+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime,+ fetch: server.fetch,+ });++ const first = executor.execute(callData());+ const replay = executor.execute(callData());+ await waitFor(() => model.calls.length === 1);+ model.close();+ await Promise.all([first, replay]);+ await executor.execute(callData());++ expect(createRuntime).toHaveBeenCalledTimes(1);+ });++ it('settles a call cancelled while its claim is stalled', async () => {+ const stalled = vi.fn(+ (_url: string, init: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init.signal?.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ ) as unknown as typeof fetch;+ const createRuntime = vi.fn();+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-1',+ createRuntime,+ fetch: stalled,+ });++ const done = executor.execute(callData());+ await vi.waitFor(() => expect(stalled).toHaveBeenCalled());+ executor.cancel({ callId: 'op-1:0:1', reason: 'interrupted' });+ await done;++ expect(createRuntime).not.toHaveBeenCalled();+ expect(executor.isRunning('op-1:0:1')).toBe(false);+ });++ it('lets the client that started the run claim first', async () => {+ vi.useFakeTimers();+ const server = createServer(() => ({ body: { cancel: true }, status: 409 }));+ const executor = new LlmRelayExecutor({+ clientId: () => 'tab-2',+ createRuntime: vi.fn(),+ fetch: server.fetch,+ });++ const done = executor.execute(callData({ preferredClientId: 'tab-1' }));+ await vi.advanceTimersByTimeAsync(NON_PREFERRED_CLAIM_DELAY_MS - 1);+ expect(server.batches).toHaveLength(0);++ await vi.advanceTimersByTimeAsync(1);+ await done;+ expect(server.batches).toHaveLength(1);+ });+});++describe('RelayBatchUploader', () => {+ it('sends an empty heartbeat batch while the model produces nothing', async () => {+ vi.useFakeTimers();+ const server = createServer();+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: server.fetch,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });++ await uploader.claim();+ expect(server.batches).toHaveLength(1);++ await vi.advanceTimersByTimeAsync(LLM_RELAY_HEARTBEAT_MS + LLM_RELAY_HEARTBEAT_MS / 2);+ expect(server.batches.length).toBeGreaterThanOrEqual(2);+ expect(server.batches[1]).toEqual({ chunks: [], clientId: 'tab-1', seq: 2 });+ uploader.dispose();+ });++ it('batches chunks every 200ms and flushes at once past 64KB', async () => {+ vi.useFakeTimers();+ const server = createServer();+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: server.fetch,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });+ await uploader.claim();++ uploader.push({ data: 'a', type: 'text' });+ uploader.push({ data: 'b', type: 'text' });+ await vi.advanceTimersByTimeAsync(199);+ expect(server.batches).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(server.batches[1].chunks).toHaveLength(2);++ uploader.push({ data: 'x'.repeat(LLM_RELAY_FLUSH_BYTES), type: 'text' });+ await vi.advanceTimersByTimeAsync(0);+ expect(server.batches).toHaveLength(3);+ uploader.dispose();+ });++ it('flushes on chunk arrival when its timer is throttled (background tab)', async () => {+ vi.useFakeTimers();+ const server = createServer();+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: server.fetch,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });+ await uploader.claim();++ uploader.push({ data: 'a', type: 'text' });+ // The page clock moves on but the throttled flush timer has not fired.+ vi.setSystemTime(Date.now() + 1000);+ uploader.push({ data: 'b', type: 'text' });+ await Promise.resolve();++ expect(server.batches).toHaveLength(2);+ expect(server.batches[1].chunks.map((c) => c.data)).toEqual(['a', 'b']);+ uploader.dispose();+ });++ it('gives up on a stalled upload instead of waiting on it forever', async () => {+ vi.useFakeTimers();+ const signals: AbortSignal[] = [];+ // A server that accepts the request and never answers.+ const stalled = vi.fn(+ (_url: string, init: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ signals.push(init.signal!);+ init.signal!.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ ) as unknown as typeof fetch;+ const onRejected = vi.fn();+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: stalled,+ leaseToken: 'l',+ onRejected,+ });++ const claimed = uploader.claim();+ await vi.advanceTimersByTimeAsync(LLM_RELAY_REQUEST_TIMEOUT_MS * 3 + 2000);++ expect(await claimed).toBe(false);+ expect(signals).toHaveLength(3);+ expect(onRejected).toHaveBeenCalledWith('unreachable');+ });++ it('aborts the stalled request in flight when disposed', async () => {+ let signal: AbortSignal | undefined;+ const stalled = vi.fn(+ (_url: string, init: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ signal = init.signal!;+ signal.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ ) as unknown as typeof fetch;+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: stalled,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });++ const claimed = uploader.claim();+ await vi.waitFor(() => expect(signal).toBeDefined());+ uploader.dispose();++ expect(signal?.aborted).toBe(true);+ expect(await claimed).toBe(false);+ });++ it('never starts the uploads queued behind a stalled request once disposed', async () => {+ const sent: number[] = [];+ const stalledOnBatch = vi.fn((_url: string, init: RequestInit) => {+ const batch = JSON.parse(init.body as string) as LlmRelayBatch;+ sent.push(batch.seq);+ if (batch.seq === 1) return Promise.resolve(new Response(JSON.stringify({ ackSeq: 1 })));+ return new Promise<Response>((_resolve, reject) => {+ init.signal!.addEventListener('abort', () => reject(new Error('aborted')));+ });+ }) as unknown as typeof fetch;+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: stalledOnBatch,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });++ expect(await uploader.claim()).toBe(true);+ uploader.push({ data: 'a'.repeat(LLM_RELAY_FLUSH_BYTES), type: 'text' });+ await vi.waitFor(() => expect(sent).toEqual([1, 2]));+ uploader.push({ data: 'b'.repeat(LLM_RELAY_FLUSH_BYTES), type: 'text' });+ uploader.dispose();+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(sent).toEqual([1, 2]);+ });++ it('retries a failed upload with the same seq', async () => {+ vi.useFakeTimers();+ let failures = 1;+ const batches: number[] = [];+ const flaky = vi.fn(async (_url: string, init: RequestInit) => {+ const batch = JSON.parse(init.body as string) as LlmRelayBatch;+ batches.push(batch.seq);+ if (failures-- > 0) throw new TypeError('network');+ return new Response(JSON.stringify({ ackSeq: batch.seq }));+ }) as unknown as typeof fetch;+ const uploader = new RelayBatchUploader({+ callId: 'c',+ clientId: 'tab-1',+ fetch: flaky,+ leaseToken: 'l',+ onRejected: vi.fn(),+ });++ const claimed = uploader.claim();+ await vi.advanceTimersByTimeAsync(1000);++ expect(await claimed).toBe(true);+ expect(batches).toEqual([1, 1]);+ uploader.dispose();+ });+});diff --git a/src/services/llmRelay/executor.ts b/src/services/llmRelay/executor.tsnew file mode 100644index 00000000000..90f1ab462b5--- /dev/null+++ b/src/services/llmRelay/executor.ts@@ -0,0 +1,282 @@+import type { LlmCancelData, LlmExecuteData, LlmRelayBatch } from '@lobechat/agent-gateway-client';+import { LLM_RELAY_LEASE_HEADER } from '@lobechat/agent-gateway-client';+import debug from 'debug';++import type { RelayUploadRejection } from './batchUploader';+import { RelayBatchUploader } from './batchUploader';+import { getLlmRelayClientId } from './clientId';+import type { RelayProtocolChunk } from './protocolChunks';+import { readProtocolChunks } from './protocolChunks';++const log = debug('lobe-client:llm-relay');++/**+ * A client that did not start the run gives the starter this long to claim the+ * call first. Only matters where the gateway broadcasts `llm_execute` (older+ * gateways, the self-hosted Go gateway); the claim deadline is 15 s.+ */+export const NON_PREFERRED_CLAIM_DELAY_MS = 3000;++/** Call ids remembered after they settle, to drop replays and late echoes. */+const SETTLED_CALL_MEMORY = 200;++export interface RelayRuntime {+ chat: (payload: any, options: { signal?: AbortSignal }) => Promise<Response>;+}++export interface LlmRelayExecutorDeps {+ clientId?: () => string;+ /** Build the model runtime from this client's own provider configuration. */+ createRuntime: (options: {+ payload: Record<string, unknown>;+ provider: string;+ runtimeProvider: string;+ }) => Promise<RelayRuntime>;+ fetch?: typeof fetch;+ serverBaseUrl?: string;+}++export interface ExecuteRelayCallOptions {+ /**+ * Each protocol chunk this client produces for the call, as soon as it is+ * produced β for rendering the reply locally before the server's echo.+ * Only called once this client owns the call.+ */+ onOutput?: (chunk: RelayProtocolChunk) => void;+}++type StopReason = LlmCancelData['reason'] | 'deadline' | 'operation_ended' | RelayUploadRejection;++interface ActiveCall {+ controller: AbortController;+ operationId: string;+ owned: boolean;+ stop: (reason: StopReason) => void;+}++const abortError = () => Object.assign(new Error('aborted'), { name: 'AbortError' });++/** JSON-safe error for the final batch; the server keys its retry policy off `errorType`. */+const toRelayError = (error: unknown, provider: string) => {+ if (error && typeof error === 'object' && 'errorType' in error) {+ const { error: inner, ...rest } = error as Record<string, unknown>;+ const detail =+ inner instanceof Error ? { message: inner.message, name: inner.name } : (inner ?? undefined);+ // Not a clone: a JSON round trip drops what the upload cannot carry+ // (functions, undefined), where structuredClone would throw.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ return JSON.parse(JSON.stringify({ provider, ...rest, error: detail }));+ }++ const message = error instanceof Error ? error.message : String(error);+ return { error: { message }, errorType: 'ProviderBizError', message, provider };+};++const sleep = (ms: number, signal: AbortSignal) =>+ new Promise<void>((resolve, reject) => {+ if (signal.aborted) return reject(abortError());+ const timer = setTimeout(resolve, ms);+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ reject(abortError());+ },+ { once: true },+ );+ });++/**+ * Client executor of the LLM relay (T-540 Β§3, PR 4): when the server hands+ * this client one LLM attempt (`llm_execute`) for a provider only this device+ * can reach, run it with the client's own provider configuration and stream+ * the normalized protocol chunks back in batches.+ *+ * 1. claim the call with an empty batch (the first claimant wins, others `409`)+ * 2. fetch the request body (`GET β¦/payload`) β it never rides the socket+ * 3. `ModelRuntime.chat()` locally, upload every protocol chunk, and hand it+ * to `onOutput` for local rendering+ * 4. end with a `final` batch: `done`, `error` (the provider's own error, so+ * the server's retry policy classifies it) or `aborted`+ *+ * `llm_cancel`, a `cancel` ack, a `409`/`410`, or the total deadline stop the+ * local model request immediately.+ */+export class LlmRelayExecutor {+ private readonly active = new Map<string, ActiveCall>();+ /** Calls this client claimed, kept after they settle for echo dedupe. */+ private readonly owned = new Set<string>();+ private readonly settled = new Set<string>();++ constructor(private readonly deps: LlmRelayExecutorDeps) {}++ /** Whether this client executed (and rendered) the call β its server echo is redundant. */+ ownsCall(callId: string | undefined): boolean {+ return !!callId && this.owned.has(callId);+ }++ isRunning(callId: string) {+ return this.active.has(callId);+ }++ cancel({ callId, reason }: Pick<LlmCancelData, 'callId' | 'reason'>) {+ this.active.get(callId)?.stop(reason);+ }++ /**+ * The run ended (stopped, failed, finished): drop its in-flight attempts.+ * Its `llm_cancel` can trail the terminal event, which closes the session+ * that would deliver it. Nothing more is uploaded β the server has already+ * settled the step, and a late `aborted` batch must not look like a lost+ * executor.+ */+ cancelOperation(operationId: string) {+ for (const call of this.active.values()) {+ if (call.operationId === operationId) call.stop('operation_ended');+ }+ }++ async execute(data: LlmExecuteData, options: ExecuteRelayCallOptions = {}): Promise<void> {+ const { callId } = data;+ // Replays (gateway resume, a re-subscribe) re-deliver the same call id.+ if (this.active.has(callId) || this.settled.has(callId)) return;++ const clientId = (this.deps.clientId ?? getLlmRelayClientId)();+ const controller = new AbortController();+ let stopReason: StopReason | undefined;++ const call: ActiveCall = {+ controller,+ operationId: data.operationId,+ owned: false,+ stop: (reason) => {+ if (controller.signal.aborted) return;+ stopReason = reason;+ controller.abort();+ // A claim still in flight is abandoned; an owned call keeps its+ // uploader to send the final `aborted` batch.+ if (!call.owned) uploader.dispose();+ },+ };+ this.active.set(callId, call);++ const uploader = new RelayBatchUploader({+ callId,+ clientId,+ fetch: this.deps.fetch,+ leaseToken: data.leaseToken,+ onRejected: (reason) => call.stop(reason),+ serverBaseUrl: this.deps.serverBaseUrl,+ });++ // Stop a little before the server's own total deadline would.+ const deadline = setTimeout(+ () => call.stop('deadline'),+ Math.max(data.deadlines.totalMs - 5000, 1000),+ );++ try {+ if (data.preferredClientId && data.preferredClientId !== clientId) {+ await sleep(NON_PREFERRED_CLAIM_DELAY_MS, controller.signal);+ }++ if (!(await uploader.claim())) {+ log('[%s] not claimed: %s', callId, uploader.rejection);+ return;+ }+ call.owned = true;+ this.owned.add(callId);+ log('[%s] claimed by %s', callId, clientId);++ const final = await this.run(data, uploader, controller.signal, options);+ if (!uploader.rejection) await uploader.finish(final);+ } catch (error) {+ if (!controller.signal.aborted) {+ log('[%s] relay attempt failed before streaming: %O', callId, error);+ await uploader.finish({ error: toRelayError(error, data.provider), reason: 'error' });+ }+ } finally {+ clearTimeout(deadline);+ if (+ controller.signal.aborted &&+ call.owned &&+ !uploader.rejection &&+ stopReason !== 'operation_ended'+ ) {+ // Stopped by `llm_cancel` or the local deadline: tell the server the+ // attempt ended here, so it does not wait for the idle deadline.+ await uploader.finish({ reason: 'aborted' });+ }+ uploader.dispose();+ this.active.delete(callId);+ this.remember(callId);+ log('[%s] settled (stop=%s)', callId, stopReason ?? 'none');+ }+ }++ private async run(+ data: LlmExecuteData,+ uploader: RelayBatchUploader,+ signal: AbortSignal,+ { onOutput }: ExecuteRelayCallOptions,+ ): Promise<NonNullable<LlmRelayBatch['final']>> {+ const payload = await this.fetchPayload(data, signal);++ let response: Response;+ try {+ const runtime = await this.deps.createRuntime({+ payload,+ provider: data.provider,+ runtimeProvider: data.runtimeProvider,+ });+ response = await runtime.chat(payload, { signal });+ } catch (error) {+ if (signal.aborted) throw error;+ return { error: toRelayError(error, data.provider), reason: 'error' };+ }++ if (!response.body) {+ return {+ error: toRelayError(new Error('The model returned an empty response'), data.provider),+ reason: 'error',+ };+ }++ try {+ for await (const chunk of readProtocolChunks(response.body)) {+ if (signal.aborted) break;+ uploader.push(chunk);+ onOutput?.(chunk);+ }+ } catch (error) {+ if (signal.aborted) throw error;+ return { error: toRelayError(error, data.provider), reason: 'error' };+ }++ if (signal.aborted) throw abortError();+ return { reason: 'done' };+ }++ private async fetchPayload(data: LlmExecuteData, signal: AbortSignal) {+ const doFetch = this.deps.fetch ?? fetch;+ const response = await doFetch(+ `${this.deps.serverBaseUrl ?? ''}/api/agent/llm-relay/${encodeURIComponent(data.callId)}/payload`,+ { headers: { [LLM_RELAY_LEASE_HEADER]: data.leaseToken }, signal },+ );+ if (!response.ok) {+ throw new Error(`Failed to load the relayed request (HTTP ${response.status})`);+ }+ return (await response.json()) as Record<string, unknown>;+ }++ private remember(callId: string) {+ this.settled.add(callId);+ if (this.settled.size > SETTLED_CALL_MEMORY) {+ const oldest = this.settled.values().next().value;+ if (oldest) {+ this.settled.delete(oldest);+ this.owned.delete(oldest);+ }+ }+ }+}diff --git a/src/services/llmRelay/index.test.ts b/src/services/llmRelay/index.test.tsnew file mode 100644index 00000000000..f26b6eaa991--- /dev/null+++ b/src/services/llmRelay/index.test.ts@@ -0,0 +1,39 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildLlmExecutorDeclaration } from './index';++const state = vi.hoisted(() => ({+ aiInfra: {} as Record<string, unknown>,+ featureFlags: {} as Record<string, unknown>,+}));++vi.mock('@/store/aiInfra', () => ({ getAiInfraStoreState: () => state.aiInfra }));+vi.mock('@/store/serverConfig', () => ({+ getServerConfigStoreState: () => ({ featureFlags: state.featureFlags }),+}));+vi.mock('./clientId', () => ({ getLlmRelayClientId: () => 'tab-1' }));++describe('buildLlmExecutorDeclaration', () => {+ beforeEach(() => {+ state.featureFlags = { enableLlmRelay: true };+ // A chat page loads the runtime state only; the settings-page provider+ // list stays empty there.+ state.aiInfra = {+ aiProviderList: [],+ enabledAiProviders: [{ id: 'lmstudio' }, { id: 'ollama' }],+ };+ });++ it('declares the providers of the runtime state a chat page has loaded', () => {+ expect(buildLlmExecutorDeclaration()).toEqual({+ capabilities: ['llm_relay@1'],+ clientId: 'tab-1',+ providers: ['lmstudio', 'ollama'],+ });+ });++ it('declares nothing outside the agent_llm_relay rollout', () => {+ state.featureFlags = { enableLlmRelay: false };+ expect(buildLlmExecutorDeclaration()).toBeUndefined();+ });+});diff --git a/src/services/llmRelay/index.ts b/src/services/llmRelay/index.tsnew file mode 100644index 00000000000..d017740d082--- /dev/null+++ b/src/services/llmRelay/index.ts@@ -0,0 +1,51 @@+import { LLM_RELAY_CAPABILITY } from '@lobechat/agent-gateway-client';+import type { ExecAgentLlmExecutor } from '@lobechat/types';++import { initializeWithClientStore } from '@/services/chat/mecha/clientModelRuntime';+import { getAiInfraStoreState } from '@/store/aiInfra';+import { getServerConfigStoreState } from '@/store/serverConfig';++import { getLlmRelayClientId } from './clientId';+import { LlmRelayExecutor } from './executor';++export { getLlmRelayClientId } from './clientId';+export type { ExecuteRelayCallOptions } from './executor';++/**+ * The page-wide relay executor. Runs on this client's own provider+ * configuration (key vaults, base URL), exactly like the client-side fetch+ * path of `chatService`.+ */+export const llmRelayExecutor = new LlmRelayExecutor({+ createRuntime: ({ payload, provider, runtimeProvider }) =>+ initializeWithClientStore({ payload, provider, runtimeProvider }),+});++const isLlmRelayEnabled = () => {+ const state =+ (typeof window !== 'undefined' ? window.global_serverConfigStore?.getState() : undefined) ??+ getServerConfigStoreState();+ return !!state?.featureFlags?.enableLlmRelay;+};++/**+ * `execAgent`'s `llmExecutor`: this client can run relayed LLM attempts for+ * the providers it has configured. The server still decides per provider+ * whether a call needs the device at all (`fetchOnClient`, a private base+ * URL). Absent outside the `agent_llm_relay` rollout.+ */+export const buildLlmExecutorDeclaration = (): ExecAgentLlmExecutor | undefined => {+ if (!isLlmRelayEnabled()) return;++ // The runtime state every chat surface loads (the full `aiProviderList` is+ // only fetched by the provider settings page).+ const providers = (getAiInfraStoreState().enabledAiProviders ?? [])+ .map((provider) => provider.id)+ .slice(0, 256);++ return {+ capabilities: [LLM_RELAY_CAPABILITY],+ clientId: getLlmRelayClientId(),+ providers,+ };+};diff --git a/src/services/llmRelay/protocolChunks.test.ts b/src/services/llmRelay/protocolChunks.test.tsnew file mode 100644index 00000000000..de49ec9e6dd--- /dev/null+++ b/src/services/llmRelay/protocolChunks.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';++import { readProtocolChunks } from './protocolChunks';++const streamOf = (...parts: string[]) => {+ const encoder = new TextEncoder();+ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const part of parts) controller.enqueue(encoder.encode(part));+ controller.close();+ },+ });+};++const collect = async (body: ReadableStream<Uint8Array>) => {+ const chunks = [];+ for await (const chunk of readProtocolChunks(body)) chunks.push(chunk);+ return chunks;+};++describe('readProtocolChunks', () => {+ it('parses SSE protocol events back into chunks', async () => {+ const chunks = await collect(+ streamOf(+ 'id: chat_1\nevent: text\ndata: "Hel"\n\n',+ 'id: chat_1\nevent: text\ndata: "lo"\n\n',+ 'id: chat_1\nevent: usage\ndata: {"totalTokens":3}\n\n',+ ),+ );++ expect(chunks).toEqual([+ { data: 'Hel', id: 'chat_1', type: 'text' },+ { data: 'lo', id: 'chat_1', type: 'text' },+ { data: { totalTokens: 3 }, id: 'chat_1', type: 'usage' },+ ]);+ });++ it('reassembles events split across network reads', async () => {+ const chunks = await collect(+ streamOf('event: reas', 'oning\ndata: "thi', 'nk"\n', '\nevent: text\ndata: "ok"\n\n'),+ );++ expect(chunks).toEqual([+ { data: 'think', type: 'reasoning' },+ { data: 'ok', type: 'text' },+ ]);+ });++ it('keeps a trailing event without the closing blank line and CRLF framing', async () => {+ const chunks = await collect(+ streamOf('event: text\r\ndata: "a"\r\n\r\nevent: stop\r\ndata: "stop"'),+ );++ expect(chunks).toEqual([+ { data: 'a', type: 'text' },+ { data: 'stop', type: 'stop' },+ ]);+ });++ it('finds the event boundary when a CRLF pair straddles two reads', async () => {+ const chunks = await collect(+ streamOf('event: text\r\ndata: "a"\r\n\r', '\nevent: text\r\ndata: "b"\r\n\r\n'),+ );++ expect(chunks).toEqual([+ { data: 'a', type: 'text' },+ { data: 'b', type: 'text' },+ ]);+ });+});diff --git a/src/services/llmRelay/protocolChunks.ts b/src/services/llmRelay/protocolChunks.tsnew file mode 100644index 00000000000..50b24df429d--- /dev/null+++ b/src/services/llmRelay/protocolChunks.ts@@ -0,0 +1,67 @@+/** One normalized model-runtime protocol chunk, as the relay uploads it. */+export interface RelayProtocolChunk {+ data: unknown;+ id?: string;+ type: string;+}++const parseEvent = (block: string): RelayProtocolChunk | undefined => {+ let id: string | undefined;+ let type: string | undefined;+ const dataLines: string[] = [];++ for (const line of block.split('\n')) {+ if (line.startsWith('id:')) id = line.slice(3).trim();+ else if (line.startsWith('event:')) type = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }++ if (!type) return;++ const raw = dataLines.join('\n');+ let data: unknown = raw;+ try {+ data = raw ? JSON.parse(raw) : null;+ } catch {+ // Not JSON: keep the raw text, the server replays it as-is.+ }++ return { data, ...(id && { id }), type };+};++/**+ * Turn a `ModelRuntime.chat()` response β the SSE-encoded protocol stream+ * (`id:` / `event:` / `data:` blocks) β back into protocol chunks, the shape+ * the server's relay runtime re-encodes and feeds into its own pipeline.+ */+export async function* readProtocolChunks(+ body: ReadableStream<Uint8Array>,+): AsyncGenerator<RelayProtocolChunk> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ // Normalize the whole buffer: a `\r\n` pair can straddle two reads.+ buffer = (buffer + decoder.decode(value, { stream: true })).replaceAll('\r\n', '\n');++ let boundary = buffer.indexOf('\n\n');+ while (boundary !== -1) {+ const chunk = parseEvent(buffer.slice(0, boundary));+ buffer = buffer.slice(boundary + 2);+ if (chunk) yield chunk;+ boundary = buffer.indexOf('\n\n');+ }+ }++ buffer += decoder.decode();+ const tail = parseEvent(buffer.trim());+ if (tail) yield tail;+ } finally {+ reader.releaseLock();+ }+}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 e937596e019..1e4e3f0bc4d 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@@ -256,6 +256,7 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {});expect(action.createClient).toHaveBeenCalledWith({+ clientId: expect.any(String),gatewayUrl: GATEWAY_URL,operationId: 'op-1',resumeOnConnect: undefined,@@ -412,6 +413,7 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {expect(action.createClient).toHaveBeenCalledTimes(2);expect(action.createClient).toHaveBeenNthCalledWith(1, {+ clientId: expect.any(String),gatewayUrl: GATEWAY_URL,operationId: 'op-1',// The run kept executing on the server while the mux was failing, so a@@ -435,6 +437,7 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {// Replaying from the start would re-apply chunks and re-run// `tool_execute` events this tab already executed.expect(action.createClient).toHaveBeenCalledWith({+ clientId: expect.any(String),gatewayUrl: GATEWAY_URL,lastEventId: '42',operationId: 'op-1',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex a2f3ec4eed8..7697171fb34 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -854,6 +854,9 @@ describe('GatewayActionImpl', () => {expect(aiAgentService.execAgentTask).toHaveBeenCalledOnce();expect(action.createClient).toHaveBeenLastCalledWith({+ // The page-scoped relay client id, so the gateway can route+ // `llm_execute` to the tab that started the run.+ clientId: expect.any(String),gatewayUrl: expectedUrl,operationId: 'server-op-1',resumeOnConnect: undefined,@@ -871,6 +874,9 @@ describe('GatewayActionImpl', () => {expect(aiAgentService.refreshGatewayToken).toHaveBeenCalledWith('topic-1');expect(action.createClient).toHaveBeenLastCalledWith({+ // The page-scoped relay client id, so the gateway can route+ // `llm_execute` to the tab that started the run.+ clientId: expect.any(String),gatewayUrl: expectedUrl,operationId: 'server-op-1',resumeOnConnect: true,diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex a223abd70cd..7db40824735 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -43,6 +43,7 @@ import {type ResumeToolResultParam,} from '@/services/aiAgent';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';+import { getLlmRelayClientId } from '@/services/llmRelay';import { messageService } from '@/services/message';import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';@@ -509,6 +510,7 @@ export class GatewayActionImpl {const client: GatewayConnection['client'] =muxClient ??this.createClient({+ ...(!agentShareId && { clientId: getLlmRelayClientId() }),gatewayUrl,...(lastEventId && { lastEventId }),operationId,diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.tsnew file mode 100644index 00000000000..0d3d57da3aa--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts@@ -0,0 +1,270 @@+import type { AgentStreamEvent, LlmExecuteData } from '@lobechat/agent-gateway-client';+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';+import type { ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { createGatewayEventHandler } from './gatewayEventHandler';++const relay = vi.hoisted(() => {+ const owned = new Set<string>();+ return {+ cancel: vi.fn(),+ cancelOperation: vi.fn(),+ execute: vi.fn(),+ owned,+ ownsCall: (callId?: string) => !!callId && owned.has(callId),+ };+});++vi.mock('@/services/llmRelay', () => ({+ llmRelayExecutor: {+ cancel: relay.cancel,+ cancelOperation: relay.cancelOperation,+ execute: relay.execute,+ ownsCall: relay.ownsCall,+ },+}));++vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: vi.fn(() => ({})),+ registerBuiltinToolExecutors: vi.fn(),+}));++const context = { agentId: 'agent-1', topicId: 'topic-1' } as ConversationContext;++const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>+ ({ data, id: 'e', operationId: 'op-1', stepIndex: 0, timestamp: 0, type }) as AgentStreamEvent;++const execute = (overrides: Partial<LlmExecuteData> = {}): LlmExecuteData => ({+ assistantMessageId: 'msg-1',+ attempt: 1,+ callId: 'op-1:0:1',+ deadlines: { claimMs: 15_000, firstChunkMs: 120_000, idleMs: 60_000, totalMs: 540_000 },+ leaseToken: 'lease',+ model: 'qwen3',+ operationId: 'op-1',+ provider: 'ollama',+ runtimeProvider: 'ollama',+ stepIndex: 0,+ ...overrides,+});++const createStore = () => {+ const dbMessagesMap: Record<string, UIChatMessage[]> = {+ [messageMapKey(context)]: [{ content: '', id: 'msg-1', role: 'assistant' } as UIChatMessage],+ };+ return {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ dbMessagesMap,+ internal_dispatchMessage: vi.fn(),+ internal_toggleToolCallingStreaming: vi.fn(),+ operations: {},+ operationsByContext: {},+ replaceMessages: vi.fn(),+ startOperation: vi.fn(() => ({ abortController: new AbortController(), operationId: 'r-op' })),+ updateOperationMetadata: vi.fn(),+ } as unknown as ChatStore;+};++const flush = async () => {+ for (let i = 0; i < 50; i += 1) await Promise.resolve();+};++const contentUpdates = (store: ChatStore) =>+ vi+ .mocked(store.internal_dispatchMessage)+ .mock.calls.map(([action]) => action as any)+ .filter((action) => action.type === 'updateMessage' && 'content' in action.value)+ .map((action) => [action.id, action.value.content]);++describe('createGatewayEventHandler β LLM relay', () => {+ beforeEach(() => {+ relay.execute.mockReset();+ relay.cancel.mockReset();+ relay.cancelOperation.mockReset();+ relay.owned.clear();+ vi.spyOn(agentSignalBridge, 'emitClientAgentSignalSourceEvent').mockResolvedValue(undefined);+ });++ it('runs llm_execute locally, renders its output and skips the server echo', async () => {+ let emit!: (chunk: { data: unknown; type: string }) => void;+ relay.execute.mockImplementation((data: LlmExecuteData, options) => {+ relay.owned.add(data.callId);+ emit = options.onOutput;+ return Promise.resolve();+ });+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('llm_execute', execute()));+ expect(relay.execute).toHaveBeenCalledWith(execute(), { onOutput: expect.any(Function) });++ emit({ data: 'Hello', type: 'text' });+ emit({ data: ' world', type: 'text' });+ await flush();+ // The server re-publishes the same output tagged with the call id.+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'Hello world',+ relayCallId: 'op-1:0:1',+ }),+ );+ await flush();++ expect(contentUpdates(store)).toEqual([+ ['msg-1', 'Hello'],+ ['msg-1', 'Hello world'],+ ]);+ });++ it('applies the echo when another client ran the call', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'From tab 2',+ relayCallId: 'op-1:0:1',+ }),+ );+ await flush();++ expect(contentUpdates(store)).toEqual([['msg-1', 'From tab 2']]);+ });++ it('starts a re-dispatched attempt over instead of appending to the lost one', async () => {+ const emitters: Array<(chunk: { data: unknown; type: string }) => void> = [];+ relay.execute.mockImplementation((data: LlmExecuteData, options) => {+ relay.owned.add(data.callId);+ emitters.push(options.onOutput);+ return Promise.resolve();+ });+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('llm_execute', execute()));+ emitters[0]({ data: 'half', type: 'text' });+ handler(makeEvent('llm_execute', execute({ attempt: 2, callId: 'op-1:0:2' })));+ emitters[1]({ data: 'fresh', type: 'text' });+ await flush();++ expect(contentUpdates(store)).toEqual([+ ['msg-1', 'half'],+ ['msg-1', 'fresh'],+ ]);+ });++ it('keeps output rendered ahead of stream_start for the same message', async () => {+ let emit!: (chunk: { data: unknown; type: string }) => void;+ relay.execute.mockImplementation((data: LlmExecuteData, options) => {+ relay.owned.add(data.callId);+ emit = options.onOutput;+ return Promise.resolve();+ });+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('llm_execute', execute()));+ emit({ data: 'early', type: 'text' });+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-1' } }));+ // A server-side chunk for the same message (tool call text, etc.) appends.+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: '!' }));+ await flush();++ expect(contentUpdates(store).at(-1)).toEqual(['msg-1', 'early!']);+ });++ it('puts output that raced ahead of a later step onto its message shell', async () => {+ let emit!: (chunk: { data: unknown; type: string }) => void;+ relay.execute.mockImplementation((data: LlmExecuteData, options) => {+ relay.owned.add(data.callId);+ emit = options.onOutput;+ return Promise.resolve();+ });+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ // Step 2's assistant row is not in the store when its relayed output lands.+ handler(makeEvent('llm_execute', execute({ assistantMessageId: 'msg-2', stepIndex: 2 })));+ emit({ data: 'early', type: 'text' });+ emit({ data: 'hmm', type: 'reasoning' });+ handler(+ makeEvent('stream_start', { assistantMessage: { id: 'msg-2', role: 'assistant' } } as any),+ );+ await flush();++ const actions = vi.mocked(store.internal_dispatchMessage).mock.calls.map(([a]) => a as any);+ const created = actions.findIndex((a) => a.type === 'createMessage' && a.id === 'msg-2');+ const after = actions.slice(created + 1).filter((a) => a.id === 'msg-2');+ expect(created).toBeGreaterThanOrEqual(0);+ expect(after).toContainEqual(+ expect.objectContaining({ type: 'updateMessage', value: { content: 'early' } }),+ );+ expect(after).toContainEqual(+ expect.objectContaining({+ type: 'updateMessage',+ value: { reasoning: { content: 'hmm' } },+ }),+ );+ });++ it('forwards llm_cancel to the executor and ignores relays on share visitors', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });+ handler(makeEvent('llm_cancel', { callId: 'op-1:0:1', reason: 'interrupted' }));+ expect(relay.cancel).toHaveBeenCalledWith({ callId: 'op-1:0:1', reason: 'interrupted' });++ const visitor = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context: { ...context, agentShareId: 'share-1' } as ConversationContext,+ operationId: 'op-1',+ });+ visitor(makeEvent('llm_execute', execute()));+ expect(relay.execute).not.toHaveBeenCalled();+ });++ // The terminal event closes the session that would carry a trailing+ // `llm_cancel`, so the run's end itself stops the local attempt.+ it("stops the run's relayed attempts when the run ends", () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));++ expect(relay.cancelOperation).toHaveBeenCalledWith('op-1');+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex ac83b08df9b..f1e31f15e36 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -2,6 +2,8 @@ import type {AgentInterventionRequestData,AgentInterventionResponseData,AgentStreamEvent,+ LlmCancelData,+ LlmExecuteData,MessagePatchData,StepCompleteData,StreamChunkData,@@ -18,6 +20,8 @@ import type { BuiltinToolResult, ConversationContext, UIChatMessage } from '@lobimport { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { readConversationMessages } from '@/helpers/conversationMessageRead';+import { llmRelayExecutor } from '@/services/llmRelay';+import type { RelayProtocolChunk } from '@/services/llmRelay/protocolChunks';import { messageService } from '@/services/message';import { didToolMutateWorkView, workService } from '@/services/work';import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';@@ -399,6 +403,12 @@ export const createGatewayEventHandler = (reasoningOperationId = undefined;};+ // Reply of the relayed LLM attempt this tab is executing (`llm_execute`),+ // rendered from the local model output instead of the server's echo. Reset+ // per call id: a re-dispatched attempt starts its reply over.+ let relayRender:+ { callId: string; content: string; messageId: string; reasoning: string } | undefined;+// Sequential processing queue β ensures stream_chunk waits for stream_start's fetchlet processingChain: Promise<void> = Promise.resolve();@@ -548,6 +558,55 @@ export const createGatewayEventHandler = (toolStateBootstrapPromiseByCallId.set(data.toolCallId, trackedBootstrapPromise);};+ /**+ * Optimistic render of a relayed attempt this tab executes: the local model's+ * text and reasoning land on the step's assistant message as they are+ * produced, and the server's echo of the same output (`relayCallId`) is+ * skipped. Tool calls, `stream_end` and the step's message patch still come+ * from the server, so its final state overrides what was rendered here.+ */+ const applyLocalRelayOutput = (call: LlmExecuteData, chunk: RelayProtocolChunk) => {+ const messageId = call.assistantMessageId;+ if (!messageId || terminalState) return;+ if (chunk.type !== 'text' && chunk.type !== 'reasoning') return;+ if (typeof chunk.data !== 'string' || !chunk.data) return;++ if (relayRender?.callId !== call.callId) {+ relayRender = { callId: call.callId, content: '', messageId, reasoning: '' };+ }+ const isCurrent = messageId === currentAssistantMessageId;+ hasStreamedContent = true;++ if (chunk.type === 'text') {+ relayRender.content += chunk.data;+ if (isCurrent) {+ endReasoningIfNeeded();+ accumulatedContent = relayRender.content;+ }+ // The whole reply so far, not the delta: a chunk that raced ahead of+ // `stream_start` (the message shell not in the store yet) is not lost.+ get().internal_dispatchMessage(+ { id: messageId, type: 'updateMessage', value: { content: relayRender.content } },+ dispatchContext,+ );+ return;+ }++ relayRender.reasoning += chunk.data;+ if (isCurrent) {+ startReasoningIfNeeded();+ accumulatedReasoning = relayRender.reasoning;+ }+ get().internal_dispatchMessage(+ {+ id: messageId,+ type: 'updateMessage',+ value: { reasoning: { content: relayRender.reasoning } },+ },+ dispatchContext,+ );+ };+return (event: AgentStreamEvent) => {if (terminalState) return;@@ -565,6 +624,8 @@ export const createGatewayEventHandler = (if (event.type === 'agent_runtime_end' || event.type === 'error') {terminalState = event.type === 'error' ? 'error' : 'completed';+ // A relayed attempt this tab still runs for the run is moot now.+ llmRelayExecutor.cancelOperation(event.operationId || gatewayOperationId);}switch (event.type) {@@ -629,9 +690,37 @@ export const createGatewayEventHandler = (// current id.endReasoningIfNeeded();- // Reset accumulators for the new stream- accumulatedContent = '';- accumulatedReasoning = '';+ // Reset accumulators for the new stream β unless this tab already+ // rendered the step's relayed reply locally ahead of `stream_start`.+ const localRelay =+ relayRender && relayRender.messageId === currentAssistantMessageId+ ? relayRender+ : undefined;+ accumulatedContent = localRelay?.content ?? '';+ accumulatedReasoning = localRelay?.reasoning ?? '';+ // Output that raced ahead of the shell inserted above was dispatched+ // to a missing id (a no-op), and the server echo of it is skipped:+ // put it on the message now.+ if (localRelay?.content) {+ get().internal_dispatchMessage(+ {+ id: localRelay.messageId,+ type: 'updateMessage',+ value: { content: localRelay.content },+ },+ dispatchContext,+ );+ }+ if (localRelay?.reasoning) {+ get().internal_dispatchMessage(+ {+ id: localRelay.messageId,+ type: 'updateMessage',+ value: { reasoning: { content: localRelay.reasoning } },+ },+ dispatchContext,+ );+ }get().updateOperationMetadata(operationId, { visibleLoadingDone: false });// Native gateway streams carry `assistantMessage.id` directly on@@ -692,6 +781,14 @@ export const createGatewayEventHandler = (const data = event.data as StreamChunkData | undefined;if (!data) return;+ // Echo of a relayed attempt this tab ran: already rendered locally.+ if (+ (data.chunkType === 'text' || data.chunkType === 'reasoning') &&+ llmRelayExecutor.ownsCall(data.relayCallId)+ ) {+ return;+ }+if (data.chunkType === 'text' && data.content) {// `lh hetero exec` coalesces main-agent text into full-text// `replace` snapshots; native gateway runs stream plain deltas.@@ -1042,6 +1139,27 @@ export const createGatewayEventHandler = (break;}+ case 'llm_execute': {+ // The server hands this tab one LLM attempt for a provider only this+ // device can reach. Started right away, not queued: the queue may be+ // waiting on a DB read, and the claim deadline is 15 s. Its output is+ // rendered through the queue so it keeps its order with stream_start.+ const data = event.data as LlmExecuteData | undefined;+ if (!data?.callId || context.agentShareId) break;+ void llmRelayExecutor.execute(data, {+ onOutput: (chunk) => {+ enqueue(() => applyLocalRelayOutput(data, chunk));+ },+ });+ break;+ }++ case 'llm_cancel': {+ const data = event.data as LlmCancelData | undefined;+ if (data?.callId) llmRelayExecutor.cancel(data);+ break;+ }+case 'tool_end': {const data = event.data as ToolEndData | undefined;const completedToolCallId =diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.tsindex b62ab6da1f0..7aa382ebc17 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts@@ -1,6 +1,7 @@import { GatewayMuxClient } from '@lobechat/agent-gateway-client';import { aiAgentService } from '@/services/aiAgent';+import { getLlmRelayClientId } from '@/services/llmRelay';import { shareChatService } from '@/services/shareChat';export interface GatewayMuxIdentity {@@ -56,6 +57,9 @@ export const getGatewayMux = (identity: GatewayMuxIdentity): GatewayMuxClient =>let mux = registry.get(key);if (!mux) {mux = new GatewayMuxClient({+ // The owner socket uses the id this tab declares as its LLM executor,+ // so the hub can hand `llm_execute` to the tab that started the run.+ ...(!identity.agentShareId && { clientId: getLlmRelayClientId() }),gatewayUrl: identity.gatewayUrl,getToken: buildGetToken(identity),keepAlive: true,