π€― 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): wrap up the local-model relay β keep partials and errors when no client is left (part 5) (#20339)
Arvin Xud0ab946b00ac
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.tsindex aa7da8740f5..1596d5a2b12 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts@@ -256,4 +256,27 @@ describe('ServerLLMTransport Β· LLM relay', () => {await transport.runAttempt(createInput(3));expect(update).toHaveBeenCalledWith('msg-1', expect.objectContaining({ content: 'Half' }));});++ it('keeps the partial of an earlier attempt when the re-dispatch finds no executor', async () => {+ const { ctx, update } = createCtx();+ relay.chat+ .mockImplementationOnce(+ answerWith('Half', createClientLlmExecutorLostError('ollama', 'idle')),+ )+ .mockImplementationOnce(async () => {+ // The tab that ran attempt 1 is gone: nobody claims the re-dispatch.+ throw createClientLlmExecutorUnavailableError('ollama', 'claim_timeout');+ });+ const transport = new ServerLLMTransport(ctx);++ await transport.runAttempt(createInput(1));+ expect(update).not.toHaveBeenCalled();++ const execution = await transport.runAttempt(createInput(2));+ expect(execution.ok).toBe(false);+ expect(update).toHaveBeenCalledWith('msg-1', {+ content: 'Half',+ metadata: { executionSite: 'client', interruptedMidStream: true },+ });+ });});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 3ebf66e44ab..b86e9ca06b5 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -276,6 +276,16 @@ export class ServerLLMTransport implements LLMTransport {ReturnType<ServerLLMTransport['createModelRuntime']>>();+ /**+ * Output of the latest relayed attempt that failed after producing some,+ * per assistant message. A re-dispatch that never gets claimed (the tab that+ * ran the attempt is gone) ends the step with nothing of its own to keep.+ */+ private readonly relayPartials = new Map<+ string,+ Pick<LLMAttemptExecution['output'], 'content' | 'thinkingContent'>+ >();+private relayStreamCount = 0;/** Keeps a redriven step's call ids apart from the execution it replaces. */@@ -429,22 +439,33 @@ export class ServerLLMTransport implements LLMTransport {* re-dispatch budget is spent, or the total deadline passed β keep what the* device had already produced on the message, marked as cut short, rather* than dropping it with the error (U4b). Retried attempts start over, so- * their partial output is discarded as usual.+ * their partial output is discarded as usual β unless the last re-dispatch+ * produced nothing, in which case the latest earlier partial is kept.*/private async keepRelayPartialOnTerminalError(input: LLMAttemptInput,execution: Extract<LLMAttemptExecution, { ok: false }>,) {- const { error, output } = execution;- if (!input.assistantMessageId || !isClientLlmRelayError(error)) return;- if (!output.content && !output.thinkingContent) return;+ const { error } = execution;+ const messageId = input.assistantMessageId;+ if (!messageId || !isClientLlmRelayError(error)) return;++ let output: Pick<LLMAttemptExecution['output'], 'content' | 'thinkingContent'> =+ execution.output;+ if (output.content || output.thinkingContent) {+ this.relayPartials.set(messageId, output);+ } else {+ const earlier = this.relayPartials.get(messageId);+ if (!earlier) return;+ output = earlier;+ }const classified = this.retryPolicy.classifyError(error);const budget = this.retryPolicy.resolveRetryBudget(input.provider, error);if (shouldRetryLLM(classified.kind, input.attempt, budget)) return;try {- await this.ctx.messageModel.update(input.assistantMessageId, {+ await this.ctx.messageModel.update(messageId, {content: output.content,metadata: { executionSite: 'client', interruptedMidStream: true } as any,...(output.thinkingContent && { reasoning: { content: output.thinkingContent } }),diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 9c3b54a2c2d..857b22652a8 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -1094,7 +1094,10 @@ export class CompletionLifecycle {if (reason === 'error') {await hookDispatcher.dispatch(operationId, 'onError', event, state?.host?.hooks);- const assistantMessageId = metadata?.assistantMessageId;+ const assistantMessageId =+ state?.error && !options?.skipErrorMessageWrite+ ? await this.resolveErrorMessageId(operationId, metadata, runOrigin)+ : undefined;if (assistantMessageId && state?.error && !options?.skipErrorMessageWrite) {// Preserve the semantic error type written by the runtime. Rebuilding// this as a generic AgentRuntimeError would lose UI routing data such@@ -1217,6 +1220,35 @@ export class CompletionLifecycle {}}+ /**+ * The assistant row an error belongs on. The client runtime names it in+ * `metadata.assistantMessageId`; a server `execAgent` turn leaves that unset,+ * so fall back to the run's own newest assistant row (`call_llm` stamps+ * `metadata.operationId` on it). Without this, a server run that fails with+ * no client online β a closed tab, a bot, a schedule β leaves an empty+ * bubble with no error card. Never the topic's latest row: that may belong+ * to an earlier turn or a concurrent run.+ */+ private async resolveErrorMessageId(+ operationId: string,+ metadata: { assistantMessageId?: string } | undefined,+ runOrigin: { topicId?: string; userId?: string },+ ): Promise<string | undefined> {+ if (metadata?.assistantMessageId) return metadata.assistantMessageId;+ if (!runOrigin.topicId || (runOrigin.userId && runOrigin.userId !== this.userId)) return;++ try {+ const row = await this.messageModel.findLatestAssistantByOperationId({+ operationId,+ topicId: runOrigin.topicId,+ });+ return row?.id;+ } catch (error) {+ log('[%s] Failed to resolve the run assistant row for its error: %O', operationId, error);+ return undefined;+ }+ }+private buildLifecycleEvent(operationId: string, state: any, reason: string) {const metadata = state?.metadata || {};const runOrigin = state?.origin ?? {};diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex aad4669ad0e..26a0bfdfcf7 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -688,6 +688,44 @@ describe('CompletionLifecycle.dispatchHooks β error persistence', () => {});});+ it("writes the error onto the run's own assistant row when a server run carries no assistantMessageId", async () => {+ // A server `execAgent` turn leaves `metadata.assistantMessageId` unset; with+ // no client online (a closed tab, a bot, a schedule) nothing else writes+ // the error, so the reply row would stay an empty bubble.+ const lifecycle = buildLifecycle();+ const updateMessage = vi.fn().mockResolvedValue({ success: true });+ const findLatestAssistantByOperationId = vi.fn().mockResolvedValue({ id: 'msg-run' });++ (lifecycle as any).messageModel = { findLatestAssistantByOperationId, update: updateMessage };+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});++ await lifecycle.dispatchHooks(+ 'op-1',+ {+ error: {+ error: { reason: 'claim_timeout', recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'lmstudio',+ },+ host: { hooks: [] },+ metadata: {},+ origin: { topicId: 'tpc-1' },+ status: 'error',+ },+ 'error',+ );++ expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({+ operationId: 'op-1',+ topicId: 'tpc-1',+ });+ expect(updateMessage).toHaveBeenCalledWith('msg-run', {+ error: expect.objectContaining({ type: 'ClientLlmExecutorUnavailable' }),+ });+ });+it('rethrows critical webhook failures after terminal persistence', async () => {const lifecycle = buildLifecycle();const persistCompletion = vidiff --git a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.tsindex 3c00b9c95ae..60cb2bfbbbd 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts@@ -37,6 +37,15 @@ describe('selectRuntimeType', () => {expect(selectRuntimeType({ isGatewayMode: true }, opts)).toBe('gateway');});+ it('keeps device-only model providers (Ollama / LM Studio) on gateway', () => {+ // The agent's model provider is deliberately not a routing input: a+ // provider only this device can reach still runs its loop on the server,+ // which relays each LLM attempt back to this client (`agent_llm_relay`).+ // Falling back to the client runtime here would reintroduce #19624.+ const localModelAgent = { isGatewayMode: true, model: 'qwen3', provider: 'lmstudio' };+ expect(selectRuntimeType(localModelAgent, opts)).toBe('gateway');+ });+it('routes local heterogeneousProvider to gateway on web', () => {expect(selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: true }, opts),diff --git a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.tsindex ce4fdb7fa7c..413a92a56ee 100644--- a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts+++ b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts@@ -109,6 +109,13 @@ interface SelectRuntimeTypeOptions {* not require re-deriving the routing rules.** Priority: `parentRuntime` > `hetero` (desktop only) > `gateway` > `client`.+ *+ * The agent's model provider is intentionally not an input. A provider only+ * this device can reach (local Ollama / LM Studio, a private base URL) still+ * runs on `gateway`: the server drives the loop and relays each LLM attempt+ * to the client that started the run (`agent_llm_relay`, see+ * `services/llmRelay`); tools, persistence and the loop stay on the server+ * rather than falling back to the client runtime.*/export const selectRuntimeType = (ctx: RuntimeSelectionContext,