🤯 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): park local-model runs in waiting_for_client when no client can run them (#20346)
Arvin Xu308bc1bd37f4
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.tsindex bc9f05491ae..e2ed2f8417c 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts@@ -114,14 +114,23 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha.set(llmRelayKeys.open(callId), this.params.userId, 'PX', ttlMs).exec();+ let delivered: number | undefined;try {- await this.dispatch(payload.model, dispatchedAt);+ delivered = await this.dispatch(payload.model, dispatchedAt);} catch (error) {log('[%s] llm_execute dispatch failed: %O', callId, error);await this.cleanup();throw createClientLlmExecutorUnavailableError(provider, 'relay_unsupported');}+ // The gateway reached no client at all: nobody can claim the call, so+ // waiting out `claimMs` would only delay the run's `waiting_for_client`.+ if (delivered === 0) {+ log('[%s] llm_execute reached no client', callId);+ await this.cleanup();+ throw createClientLlmExecutorUnavailableError(provider, 'not_delivered');+ }+const reader = new RelayBatchReader(redis.duplicate(),llmRelayKeys.stream(callId),@@ -145,7 +154,11 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleChalog('[%s] relayed attempt failed: %O', this.params.callId, error);}- private async dispatch(model: string, dispatchedAt: number) {+ /**+ * 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> {const { params } = this;const data: LlmExecuteData = {assistantMessageId: params.assistantMessageId,@@ -174,7 +187,8 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCharouted,delivered,);- return;+ // A broadcast fallback (`routed: false`) cannot tell who got it.+ return routed ? delivered : undefined;}await streamManager.publishStreamEvent(params.operationId, {diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.tsindex a920a8c1408..5b4e84b2a5c 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts@@ -464,6 +464,44 @@ describe('RelayModelRuntime over a gateway with relay routes', () => {});expect(redis.peek(llmRelayKeys.payload(CALL_ID))).toBeUndefined();});++ it('fails as not_delivered at once when the gateway reached no client, without waiting out the claim', async () => {+ const { manager } = createGatewayManager();+ manager.sendLlmExecute.mockResolvedValueOnce({ delivered: 0, routed: true });+ // A claim window far longer than the test: only the fast path can settle it.+ const runtime = createRuntime(manager, {+ claimMs: 60_000,+ firstChunkMs: 60_000,+ idleMs: 60_000,+ totalMs: 120_000,+ });++ const startedAt = Date.now();+ await expect(runtime.chat(payload, {})).rejects.toMatchObject({+ error: { reason: 'not_delivered', recoverable: true },+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ });+ expect(Date.now() - startedAt).toBeLessThan(1000);+ expect(redis.peek(llmRelayKeys.payload(CALL_ID))).toBeUndefined();+ expect(manager.closeLlmCall).toHaveBeenCalledWith('op_1', CALL_ID);+ });++ it('still waits for a claim when the gateway could not count recipients', async () => {+ const { manager } = createGatewayManager();+ // A broadcast fallback (self-hosted gateway) cannot tell who got the call.+ manager.sendLlmExecute.mockResolvedValueOnce({ delivered: undefined, routed: false } as any);++ const response = await createRuntime(manager, {+ claimMs: 200,+ firstChunkMs: 2000,+ idleMs: 2000,+ totalMs: 5000,+ }).chat(payload, {});++ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({+ error: { reason: 'claim_timeout' },+ });+ });});describe('llm-relay upload handler', () => {diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.ts b/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.tsnew file mode 100644index 00000000000..0e74baf2056--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.ts@@ -0,0 +1,122 @@+import type { AgentRunClientLlmWait, AgentRuntimeContext } from '@lobechat/agent-runtime';+import type { ChatMessageError } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';++import type { ClientLlmUnavailableReason } from './errors';++/**+ * `waiting_for_client` (U4c, T-540 D3 = a): a run whose next LLM call can only+ * run on the user's device, with no client there to take it — a schedule, a+ * bot, a CLI run, every tab closed. Instead of failing, the run parks on that+ * step, keeps what it already produced, and tells the user why. A client that+ * can run the provider continues it from the same step; past the wait window+ * it ends with an actionable error.+ */++/**+ * How long a parked run waits for a client. Well inside the gateway's 30 min+ * inactivity watchdog, so the parked stream is never reaped as dead first.+ * `AGENT_LLM_RELAY_CLIENT_WAIT_MS` overrides it (self-hosting, tests).+ */+export const DEFAULT_LLM_RELAY_CLIENT_WAIT_MS = 10 * 60_000;++const MAX_LLM_RELAY_CLIENT_WAIT_MS = 25 * 60_000;++/**+ * Below this much remaining wait a run does not (re-)park: its expiry would be+ * due before the parking step commits.+ */+export const MIN_CLIENT_LLM_WAIT_REMAINING_MS = 5000;++/** Backoff for putting a claimed wait's row back after a failed resume. */+export const CLIENT_WAIT_REVERT_RETRY_DELAYS_MS = [0, 200, 1000] as const;++export const resolveClientLlmWaitMs = (env: Record<string, string | undefined> = process.env) => {+ const configured = Number(env.AGENT_LLM_RELAY_CLIENT_WAIT_MS);+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_LLM_RELAY_CLIENT_WAIT_MS;+ return Math.min(configured, MAX_LLM_RELAY_CLIENT_WAIT_MS);+};++export const buildClientLlmWait = (params: {+ assistantMessage?: { id: string; parentId?: string | null } | null;+ context?: AgentRuntimeContext;+ /** Deadline of the wait this park continues; the new one never runs past it. */+ notAfter?: string;+ now?: number;+ provider: string;+ reason: ClientLlmUnavailableReason;+ waitMs?: number;+}): AgentRunClientLlmWait => {+ const now = params.now ?? Date.now();+ const context = params.context;+ const windowEnd = now + (params.waitMs ?? resolveClientLlmWaitMs());+ const notAfter = params.notAfter ? Date.parse(params.notAfter) : Number.NaN;+ const expiresAt = Number.isFinite(notAfter) ? Math.min(windowEnd, notAfter) : windowEnd;+ return {+ assistantMessageId: params.assistantMessage?.id,+ ...(context && {+ context: {+ initialContext: context.initialContext,+ metadata: context.metadata,+ payload: context.payload,+ phase: context.phase,+ },+ }),+ expiresAt: new Date(expiresAt).toISOString(),+ parentMessageId: params.assistantMessage?.parentId ?? undefined,+ parkedAt: new Date(now).toISOString(),+ provider: params.provider,+ reason: params.reason,+ };+};++/**+ * What the parked call's assistant row shows while the run waits: the same+ * error type as a failed relay, flagged `waitingForClient` so the UI renders+ * the waiting card (and its "continue here") instead of a final error.+ */+export const buildClientLlmWaitMessageError = (wait: AgentRunClientLlmWait): ChatMessageError => ({+ body: {+ expiresAt: wait.expiresAt,+ provider: wait.provider,+ reason: wait.reason,+ recoverable: true,+ waitingForClient: true,+ },+ message: `Waiting for a LobeHub client that can reach ${wait.provider}`,+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+});++/**+ * Step context that replays the parked call: the parked step's own context, so+ * the agent rebuilds the same LLM request. The resumed state also seeds+ * `pendingAssistantMessageId`, so the call fills the assistant row it already+ * created; `user_input` carries that id in its payload instead.+ */+export const buildClientLlmWaitResumeContext = (+ wait: AgentRunClientLlmWait | undefined,+): AgentRuntimeContext => {+ const context = wait?.context;+ if (context && context.phase !== 'user_input') return { ...context };++ const payload = context?.payload && typeof context.payload === 'object' ? context.payload : {};+ return {+ ...context,+ payload: {+ ...payload,+ ...(wait?.assistantMessageId && { assistantMessageId: wait.assistantMessageId }),+ ...(wait?.parentMessageId && { parentMessageId: wait.parentMessageId }),+ },+ phase: 'user_input',+ } as AgentRuntimeContext;+};++/**+ * Whether `state` is the terminal error an expiry of the park at `parkedAt`+ * wrote, so a redelivered expiry can finish that run's lifecycle again.+ */+export const isClientLlmWaitExpiryOf = (state: { error?: unknown }, parkedAt: string): boolean => {+ const body = (state.error as { body?: { reason?: unknown; waitedSince?: unknown } } | undefined)+ ?.body;+ return body?.reason === 'wait_timeout' && body.waitedSince === parkedAt;+};diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts b/apps/server/src/modules/AgentRuntime/llmRelay/errors.tsindex eb9672a6201..e168be526ab 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts@@ -1,5 +1,5 @@import { AgentRuntimeError } from '@lobechat/model-runtime';-import { AgentRuntimeErrorType } from '@lobechat/types';+import { AgentRuntimeErrorType, CLIENT_LLM_WAITABLE_REASONS } from '@lobechat/types';/*** Errors of a relayed LLM attempt, shaped like every other provider error@@ -13,8 +13,19 @@ export type ClientLlmUnavailableReason =| 'no_executor'/** An executor was asked, but no batch arrived within `claimMs`. */| 'claim_timeout'+ /** The gateway delivered `llm_execute` to no connected client. */+ | 'not_delivered'/** The deployment cannot relay (no Redis / gateway). */- | 'relay_unsupported';+ | 'relay_unsupported'+ /** The run waited for a client (`waiting_for_client`) and none came in time. */+ | 'wait_timeout';++/**+ * Reasons a client can still fix by showing up: the run parks in+ * `waiting_for_client` for them instead of failing (U4c). `relay_unsupported`+ * is a deployment gap no client can close.+ */+const CLIENT_WAITABLE_REASONS = new Set<string>(CLIENT_LLM_WAITABLE_REASONS);export type ClientLlmTimeoutStage = 'first_chunk' | 'total';@@ -29,9 +40,10 @@ export type ClientLlmLostReason =export const createClientLlmExecutorUnavailableError = (provider: string,reason: ClientLlmUnavailableReason,+ extra?: Record<string, unknown>,) =>AgentRuntimeError.chat({- error: { reason, recoverable: true },+ error: { reason, recoverable: true, ...extra },errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,provider,});@@ -67,6 +79,29 @@ export const isClientLlmRelayError = (error: unknown) => {);};+/**+ * The reason of an unavailable-executor error a client can still fix, read off+ * either the thrown error or its persisted form (`formatErrorForState` keeps the+ * detail under `body`). `undefined` for anything else.+ */+export const getClientLlmWaitableReason = (+ error: unknown,+): ClientLlmUnavailableReason | undefined => {+ if (!error || typeof error !== 'object') return;+ const { body, errorType, type } = error as {+ body?: { reason?: unknown };+ errorType?: unknown;+ type?: unknown;+ };+ if (+ errorType !== AgentRuntimeErrorType.ClientLlmExecutorUnavailable &&+ type !== AgentRuntimeErrorType.ClientLlmExecutorUnavailable+ )+ return;+ const reason = (getErrorDetail(error).reason ?? body?.reason) as ClientLlmUnavailableReason;+ return CLIENT_WAITABLE_REASONS.has(reason) ? reason : undefined;+};+/*** Retries a relay failure may take (U4b): a lost executor is re-dispatched as a* fresh attempt (new `callId`) up to twice, a missed first chunk once. A misseddiff --git a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.tsindex 50a71cc0604..3d9e8721e41 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts@@ -1,7 +1,11 @@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';+import {+ CLIENT_LLM_WAIT_CAPABILITY,+ 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@@ -17,7 +21,7 @@ import { LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER } from '@lobechat/agent-ga* - `llm_relay:stream:{callId}` Redis Stream of uploaded batches (`seq`, `body`)*/-export { LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER };+export { CLIENT_LLM_WAIT_CAPABILITY, 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/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex c8b45cac0ee..edd786207bb 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -209,6 +209,8 @@ export async function runStep(c: Context): Promise<Response> {toolMessageId,verifyAsyncToolBarrier,asyncToolVerifyAttempt,+ resumeClientLlm,+ clientLlmWaitExpired,lockRetryAttempt,} = { ...body, ...body.payload };@@ -293,6 +295,8 @@ export async function runStep(c: Context): Promise<Response> {!resumeAsyncTool &&!finishAfterAsyncTool &&!verifyAsyncToolBarrier &&+ !resumeClientLlm &&+ !clientLlmWaitExpired &&!groupMemberTimeout;// A previous invocation may have died part-way through its own inline loop.@@ -347,6 +351,7 @@ export async function runStep(c: Context): Promise<Response> {: await aiAgentService.executeStep({approvedToolCall,asyncToolVerifyAttempt,+ clientLlmWaitExpired,context,externalRetryCount,finishAfterAsyncTool,@@ -358,6 +363,7 @@ export async function runStep(c: Context): Promise<Response> {rejectAndContinue,rejectionReason,resumeAsyncTool,+ resumeClientLlm,retainStepLock: true,stepIndex,stepLockOwner,diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 10108d3a68b..6e92782cdc4 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1030,6 +1030,13 @@ const StartExecutionSchema = z.object({const acceptsMemberRuntimeEndOf = (streamFeatures: string[] | undefined): boolean =>streamFeatures?.includes('member_runtime_end') ?? false;+/** A client's declaration that it can run relayed LLM attempts (`agent_llm_relay`). */+const LlmExecutorSchema = z.object({+ capabilities: z.array(z.string()).max(16),+ clientId: z.string().min(1).max(128),+ providers: z.array(z.string()).max(256),+});+const ExecAgentSchema = z.object({includeFinalState: z.boolean().optional(),@@ -1052,13 +1059,7 @@ const ExecAgentSchema = z* it (`llm_execute`) for providers only this device can reach. Sent only* when the client is inside the `agent_llm_relay` rollout.*/- llmExecutor: z- .object({- capabilities: z.array(z.string()).max(16),- clientId: z.string().min(1).max(128),- providers: z.array(z.string()).max(256),- })- .optional(),+ llmExecutor: LlmExecutorSchema.optional(),/** The agent ID to run (either agentId or slug is required) */agentId: z.string().optional(),/** Application context for message storage */@@ -3217,6 +3218,28 @@ export const aiAgentRouter = router({});}),+ /**+ * Runs of the caller parked in `waiting_for_client`: their next LLM call needs+ * the user's device and no client took it. A client that can run the provider+ * continues them with `resumeClientLlmWait`.+ */+ listClientLlmWaits: aiAgentProcedure+ .input(z.object({ providers: z.array(z.string().min(1)).max(256).optional() }).optional())+ .query(async ({ input, ctx }) => {+ return ctx.aiAgentService.listClientLlmWaits(input?.providers);+ }),++ /**+ * Continue a run parked in `waiting_for_client` from the step it parked on,+ * with the calling client as the run's relay executor. `resumed: false` when+ * the run is no longer parked (already resumed, expired or stopped).+ */+ resumeClientLlmWait: aiAgentWriteProcedure+ .input(z.object({ llmExecutor: LlmExecutorSchema, operationId: z.string().min(1) }))+ .mutation(async ({ input, ctx }) => {+ return ctx.aiAgentService.resumeFromClientLlmWait(input);+ }),+interruptTask: aiAgentWriteProcedure.input(InterruptTaskSchema).mutation(async ({ input, ctx }) => {diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex acc99f507cd..c4867d44c37 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -158,7 +158,8 @@ export class AbandonOperationService {const shouldDispatchAbandonedLifecycle =state.status === 'running' ||state.status === 'waiting_for_human' ||- state.status === 'waiting_for_async_tool';+ state.status === 'waiting_for_async_tool' ||+ state.status === 'waiting_for_client';const message = `${ABANDONED_OPERATION_ERROR_PREFIX} ${reason}`;const error: ChatMessageError = {body: { message },@@ -407,7 +408,9 @@ export class AbandonOperationService {if (!op ||(!preClaimed &&- !['running', 'waiting_for_human', 'waiting_for_async_tool'].includes(op.status))+ !['running', 'waiting_for_human', 'waiting_for_async_tool', 'waiting_for_client'].includes(+ op.status,+ ))) {return;}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex c81701d8d2a..de2ca19e61b 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import type {Agent,+ AgentRunClientLlmWait,AgentRunLlmExecutor,AgentRuntimeContext,AgentState,@@ -38,15 +39,18 @@ import {import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';import {type ChatToolPayload,+ type ClientLlmWaitItem,type EvalToolForwardingConfig,type ExecSubAgentParams,type ExecSubAgentResult,type ExecVirtualSubAgentParams,+ type ResumeClientLlmWaitResult,type UIChatMessage,} from '@lobechat/types';import { ChatErrorType, RequestTrigger } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import debug from 'debug';+import pMap from 'p-map';import urlJoin from 'url-join';import {@@ -62,6 +66,19 @@ import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntiimport { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';import { runMayUseDevice } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import {+ buildClientLlmWait,+ buildClientLlmWaitMessageError,+ buildClientLlmWaitResumeContext,+ CLIENT_WAIT_REVERT_RETRY_DELAYS_MS,+ isClientLlmWaitExpiryOf,+ MIN_CLIENT_LLM_WAIT_REMAINING_MS,+} from '@/server/modules/AgentRuntime/llmRelay/clientWait';+import {+ createClientLlmExecutorUnavailableError,+ getClientLlmWaitableReason,+} from '@/server/modules/AgentRuntime/llmRelay/errors';+import { CLIENT_LLM_WAIT_CAPABILITY } from '@/server/modules/AgentRuntime/llmRelay/protocol';import { hasNonPersistedMessage } from '@/server/modules/AgentRuntime/messagePersistence';import {createRuntimeExecutors,@@ -125,6 +142,9 @@ if (process.env.VERCEL) {const log = debug('lobe-server:agent-runtime-service');+/** Tries for a client wait's notice or expiry error on the assistant row. */+const CLIENT_WAIT_ROW_WRITE_ATTEMPTS = 3;+/*** Base delay before the first `verifyAsyncToolBarrier` re-check fires after a* sub-agent completion found the parent not yet resumable. Long enough for@@ -738,11 +758,37 @@ export class AgentRuntimeService {// shows — the step-boundary check then persists the interrupted state.await this.coordinator.markInterrupted(operationId);- await this.coordinator.saveAgentState(operationId, {+ const parkedWait = state.status === 'waiting_for_client' ? state.clientLlmWait : undefined;+ const interruptedState: AgentState = {...state,+ ...(state.status === 'waiting_for_client' && { clientLlmWait: undefined }),lastModified: new Date().toISOString(),status: 'interrupted',- });+ };+ await this.coordinator.saveAgentState(operationId, interruptedState);++ // A run parked for a client has no step that would reach a boundary and+ // settle it, so settle it here — otherwise the row and the topic stay live+ // until the wait expires. Its waiting card goes too: nothing can continue it.+ if (state.status === 'waiting_for_client') {+ if (parkedWait?.assistantMessageId) {+ await this.messageModel+ .update(parkedWait.assistantMessageId, { error: null })+ .catch((error) => log('[%s] Failed to clear the waiting notice: %O', operationId, error));+ }+ if (await this.agentOperationModel.settleClientWait(operationId, 'interrupted')) {+ await this.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');+ } else if (parkedWait) {+ // The wait's expiry claimed the row first and has not finished (its+ // Redis state still read this park). Its retry would find the state+ // this Stop just wrote and give up, so finish it here as the row says.+ const row = await this.agentOperationModel.findById(operationId).catch(() => undefined);+ if (row?.status === 'error') {+ log('[%s] Stop lost to the wait expiry; finishing the expiry', operationId);+ await this.endExpiredClientLlmWait(operationId, state, parkedWait);+ }+ }+ }log('[%s] Operation interrupted', operationId);return true;@@ -1631,6 +1677,8 @@ export class AgentRuntimeService {toolMessageId,verifyAsyncToolBarrier,asyncToolVerifyAttempt,+ resumeClientLlm,+ clientLlmWaitExpired,externalRetryCount = 0,lockRetryAttempt = 0,inlineContinuation = false,@@ -1645,6 +1693,21 @@ export class AgentRuntimeService {return this.handleGroupMemberTimeout(groupMemberTimeout);}+ // Expiry check of a `waiting_for_client` park. It executes nothing: the CAS+ // on the durable row decides whether the wait (still parked, same park) ends+ // here or a resume already took the run. Ahead of the terminal-row guard+ // below, because a retried expiry whose first attempt settled the row but+ // failed to finish must still get to finish it.+ if (clientLlmWaitExpired) {+ const expired = await this.expireClientLlmWait(operationId, clientLlmWaitExpired);+ return {+ nextStepScheduled: false,+ state: expired ? { status: 'error' } : {},+ stepResult: null,+ success: true,+ };+ }+// Redis keeps the resumable step state, but the durable operation row is// the authority for cancellation/recovery. A queued QStash delivery can// outlive a crashed process and arrive after Goal recovery has atomically@@ -1810,6 +1873,7 @@ export class AgentRuntimeService {rejectAndContinue,rejectionReason,resumeAsyncTool,+ resumeClientLlm,toolMessageId,},priority: 'high',@@ -2027,6 +2091,19 @@ export class AgentRuntimeService {};}+ // A run parked for a client moves only through its own resume: any other+ // delivery (a duplicate, a stale redrive) would replay the call with no+ // client to take it.+ if (agentState.status === 'waiting_for_client' && !resumeClientLlm) {+ log('[%s][%d] Skipping step — operation is waiting for a client', operationId, stepIndex);+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }+// Agent Share: re-prove this visitor run's authorization on EVERY step.// A revocation only flips the `agent_shares` row — nothing tears down// an operation that was already created, so without this the run keeps@@ -2191,6 +2268,9 @@ export class AgentRuntimeService {// Handle human interventionlet currentContext = context;+ // The wait this step resumes, if any: a resumed call that finds no client+ // again re-parks under the same deadline, so retries never extend it.+ let resumedClientLlmWait: AgentRunClientLlmWait | undefined;let currentState = agentState;if (humanInput || approvedToolCall || rejectionReason) {@@ -2248,6 +2328,29 @@ export class AgentRuntimeService {);}+ // Continue a run parked in `waiting_for_client`: a client that can run the+ // provider asked for it (`resumeFromClientLlmWait` already recorded it as+ // the run's executor). Replay the parked LLM turn into the assistant row+ // it created, on the messages the parked step had.+ if (resumeClientLlm && currentState.status === 'waiting_for_client') {+ const wait = currentState.clientLlmWait;+ resumedClientLlmWait = wait;+ currentState = structuredClone(currentState);+ currentState.status = 'running';+ currentState.clientLlmWait = undefined;+ currentState.error = undefined;+ currentState.lastModified = new Date().toISOString();+ if (wait?.assistantMessageId)+ currentState.pendingAssistantMessageId = wait.assistantMessageId;+ currentContext = buildClientLlmWaitResumeContext(wait);+ log(+ '[%s][%d] Resuming from waiting_for_client (assistant=%s)',+ operationId,+ stepIndex,+ wait?.assistantMessageId,+ );+ }+// Finish a parked supervisor op WITHOUT another LLM turn (group// orchestration skipCallSupervisor / delegate). Refresh messages so the// final group conversation is captured, transition straight to `done`,@@ -2407,6 +2510,20 @@ export class AgentRuntimeService {stepResult.newState.status = 'interrupted';stepResult.newState.lastModified = new Date().toISOString();log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);+ } else if (stepResult.newState.status === 'error') {+ // No client could run the step's LLM call: park for one instead of+ // failing (U4c). The parked state is what the step started from, so+ // a resume replays the same call.+ const parkedState = await this.parkForClientLlm(+ operationId,+ stepResult.newState,+ currentContext,+ resumedClientLlmWait?.expiresAt,+ currentState,+ );+ if (parkedState) {+ stepResult = { ...stepResult, newState: parkedState, nextContext: undefined };+ }}// Decide whether to schedule next step (hoisted above the save: it also@@ -2747,11 +2864,15 @@ export class AgentRuntimeService {buildInvokeAgentResultAttributes({ completionReason: reason }),);- const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(- operationId,- stepResult.newState,- reason,- );+ // A client park is no completion: the run continues under this id.+ const completionSignalEvents =+ reason === 'waiting_for_client'+ ? []+ : await this.completionLifecycle.emitSignalEvents(+ operationId,+ stepResult.newState,+ reason,+ );logToolCallPc(operationId, stepIndex, 'post.completion_signals', () => ({ reason }));// Dispatch completion hooks@@ -2789,28 +2910,33 @@ export class AgentRuntimeService {// Finalize tracing snapshot. The error catch below uses the same// recorder so propagated failures still write the canonical S3// snapshot instead of orphaning the partial ().+ // A client park is no trace boundary: keep the partial so the resumed+ // steps extend the same trajectory and the real end finalizes it whole.const newStateError = stepResult.newState.error;- await this.traceRecorder.finalize(operationId, {- appendEventsToLastStep: completionSignalEvents,- completionReason: reason,- error: newStateError- ? {- attribution: newStateError.attribution,- body: newStateError.body,- category: newStateError.category,- countAsFailure: newStateError.countAsFailure,- httpStatus: newStateError.httpStatus,- message:- this.completionLifecycle.extractErrorMessage(newStateError) ??- JSON.stringify(newStateError),- numericId: newStateError.numericId,- retryable: newStateError.retryable,- severity: newStateError.severity,- type: String(newStateError.type ?? newStateError.errorType ?? 'unknown'),- }- : undefined,- state: stepResult.newState,- });+ if (reason === 'waiting_for_client') {+ await this.traceRecorder.flushPartial();+ } else+ await this.traceRecorder.finalize(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ error: newStateError+ ? {+ attribution: newStateError.attribution,+ body: newStateError.body,+ category: newStateError.category,+ countAsFailure: newStateError.countAsFailure,+ httpStatus: newStateError.httpStatus,+ message:+ this.completionLifecycle.extractErrorMessage(newStateError) ??+ JSON.stringify(newStateError),+ numericId: newStateError.numericId,+ retryable: newStateError.retryable,+ severity: newStateError.severity,+ type: String(newStateError.type ?? newStateError.errorType ?? 'unknown'),+ }+ : undefined,+ state: stepResult.newState,+ });logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason }));}@@ -3500,6 +3626,469 @@ export class AgentRuntimeService {return true;}+ // ==================== Waiting for a client (U4c) ====================++ /**+ * Park a step that failed because no client could run its LLM call — the+ * provider is reachable only from the user's device and no LobeHub client+ * took the call (a schedule, a bot, a CLI run, every tab closed). The run+ * waits in `waiting_for_client` on the state the step started from, its+ * assistant row says why, and an expiry check is armed. `undefined` when the+ * error is not one a client can fix, or nothing could resume or expire the+ * park (no queue) — the step then fails as before.+ */+ private async parkForClientLlm(+ operationId: string,+ errorState: AgentState,+ context: AgentRuntimeContext | undefined,+ notAfter?: string,+ stepStartState?: AgentState,+ ): Promise<AgentState | undefined> {+ const reason = getClientLlmWaitableReason(errorState.error);+ if (!reason || !this.queueService) return;++ // A client that started the run but predates the wait takes the parked+ // call's error as the run's end and settles it locally, while the row+ // stays parked under its topic. Fail the step for it as before.+ const declaredExecutor = errorState.host?.llmExecutor;+ if (declaredExecutor && !declaredExecutor.capabilities?.includes(CLIENT_LLM_WAIT_CAPABILITY)) {+ log("[%s] The run's client cannot wait for a client, failing instead", operationId);+ return;+ }++ const errorBody = (errorState.error as { body?: { provider?: unknown } } | undefined)?.body;+ const provider =+ (typeof errorBody?.provider === 'string' && errorBody.provider) ||+ errorState.modelRuntimeConfig?.provider ||+ 'unknown';++ const topicId = errorState.origin?.topicId;+ let assistantMessage: { id: string; parentId?: string | null } | undefined;+ if (topicId) {+ try {+ const row = await this.messageModel.findLatestAssistantByOperationId({+ operationId,+ topicId,+ });+ if (row?.id) assistantMessage = { id: row.id, parentId: row.parentId };+ } catch (error) {+ log('[%s] Failed to find the parked call assistant row: %O', operationId, error);+ }+ }++ // A client picks a wait up by subscribing to the run's stream, which needs+ // the run's topic and assistant row. Without them nothing could claim the+ // wait, so fail the step as before instead of parking it.+ if (!topicId || !assistantMessage) {+ log('[%s] No stream anchor to park on, failing instead', operationId);+ return;+ }++ const wait = buildClientLlmWait({ assistantMessage, context, notAfter, provider, reason });+ // A re-park with (almost) nothing left of its wait would arm an expiry that+ // can land before this step commits and be overwritten by it. The wait is+ // over anyway: fail the step with its actionable error instead.+ if (Date.parse(wait.expiresAt) - Date.now() < MIN_CLIENT_LLM_WAIT_REMAINING_MS) {+ log('[%s] Client wait already used up, failing instead', operationId);+ return;+ }+ const parkedState: AgentState = {+ ...errorState,+ // The call never ran, so it does not spend a step: the resume replays it+ // through `runtime.step`, which counts it (and applies the step limit)+ // then. Keeping the incremented count would count it twice and, at the+ // limit, replay it as a forced final answer.+ ...(stepStartState && {+ forceFinish: stepStartState.forceFinish,+ stepCount: stepStartState.stepCount,+ }),+ clientLlmWait: wait,+ error: undefined,+ lastModified: wait.parkedAt,+ status: 'waiting_for_client',+ };++ // Resume, expiry and Stop all key off the durable row, so it must say+ // `waiting_for_client` before anything advertises the wait. If it cannot,+ // fail the step as before rather than park a run nothing could settle.+ try {+ const recorded = await this.agentOperationModel.recordCompletion(operationId, {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ if (!recorded) {+ log('[%s] No durable row to park on, failing instead', operationId);+ return;+ }+ } catch (error) {+ log('[%s] Could not record the client wait, failing instead: %O', operationId, error);+ return;+ }++ // The expiry can fire at once (a re-park past its deadline), and it acts+ // only on the park it names: the parked state and the waiting notice must+ // already be in place, or it no-ops — or its terminal error is overwritten+ // by the notice — and the run waits with nothing left to end it.+ try {+ await this.coordinator.saveAgentState(operationId, parkedState);+ } catch (error) {+ log('[%s] Could not save the parked state, failing instead: %O', operationId, error);+ return;+ }++ // The notice is the only thing a client that cannot run the provider sees+ // (its relay error handler re-reads the server-owned row), so a transient+ // failure is retried rather than left as a silent park.+ await this.updateAssistantRowWithRetry(operationId, assistantMessage.id, {+ error: buildClientLlmWaitMessageError(wait),+ });++ try {+ await this.queueService.scheduleMessage({+ context: undefined,+ delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),+ endpoint: `${this.baseURL}/run`,+ operationId,+ payload: { clientLlmWaitExpired: wait.parkedAt },+ priority: 'normal',+ stepIndex: parkedState.stepCount,+ });+ } catch (error) {+ // Without the expiry the run could wait forever: fail it now instead+ // (the run's error then replaces the waiting notice on its row).+ log('[%s] Could not arm the client wait expiry, failing instead: %O', operationId, error);+ return;+ }++ log(+ '[%s] Parked in waiting_for_client (provider=%s, reason=%s, until %s)',+ operationId,+ provider,+ reason,+ wait.expiresAt,+ );+ return parkedState;+ }++ /**+ * Continue a run parked in `waiting_for_client` from the step it parked on.+ * The asking client becomes the run's relay executor, so the replayed call+ * is delivered to it. Single-fire: concurrent resumes (an automatic one and+ * a click) race on the durable row and one wins.+ */+ async resumeFromClientLlmWait(params: {+ llmExecutor?: AgentRunLlmExecutor;+ operationId: string;+ }): Promise<ResumeClientLlmWaitResult> {+ const { llmExecutor, operationId } = params;+ const state = await this.coordinator.loadAgentState(operationId);+ if (!state || state.status !== 'waiting_for_client') return { resumed: false };+ if (state.origin?.userId && state.origin.userId !== this.userId) return { resumed: false };++ // Past its deadline the wait is over even if the expiry is still in flight+ // (QStash can deliver late): leave the run to it rather than run the call+ // after the advertised time.+ const expiresAt = Date.parse(state.clientLlmWait?.expiresAt ?? '');+ if (Number.isFinite(expiresAt) && Date.now() >= expiresAt) return { resumed: false };++ const won = await this.agentOperationModel.tryResumeFromClientWait(operationId);+ if (!won) return { resumed: false };++ const wait = state.clientLlmWait;+ // Past the claim, everything up to the queued step must land, or the run+ // goes back to its wait: a `running` row with nothing queued is one that no+ // resume, expiry or Stop can reach.+ try {+ await this.coordinator.saveAgentState(operationId, {+ ...state,+ host: { ...state.host, ...(llmExecutor && { llmExecutor }) },+ lastModified: new Date().toISOString(),+ });++ // A Stop that landed after the claim could not settle the `running` row,+ // and the save above may have overwritten its `interrupted` state. It+ // marks the interrupt before saving, so any such Stop shows here; a later+ // one saves after this and the queued step stops on it.+ if (await this.coordinator.isInterrupted(operationId)) {+ log('[%s] Stopped while being resumed; settling as interrupted', operationId);+ const interruptedState: AgentState = {+ ...state,+ clientLlmWait: undefined,+ lastModified: new Date().toISOString(),+ status: 'interrupted',+ };+ await this.coordinator.saveAgentState(operationId, interruptedState);+ if (await this.agentOperationModel.settleRunning(operationId, 'interrupted')) {+ await this.completionLifecycle.dispatchHooks(+ operationId,+ interruptedState,+ 'interrupted',+ );+ }+ return { resumed: false };+ }++ if (wait?.assistantMessageId) {+ try {+ await this.messageModel.update(wait.assistantMessageId, { error: null });+ } catch (error) {+ log('[%s] Failed to clear the waiting notice: %O', operationId, error);+ }+ }++ await this.queueService?.scheduleMessage({+ context: undefined,+ delay: 100,+ endpoint: `${this.baseURL}/run`,+ operationId,+ payload: { resumeClientLlm: true },+ priority: 'high',+ stepIndex: state.stepCount,+ });+ } catch (error) {+ log('[%s] Could not hand the run to a client, staying parked: %O', operationId, error);+ await this.restoreClientLlmWait(operationId, state);+ throw error;+ }++ log('[%s] Resumed from waiting_for_client at step %d', operationId, state.stepCount);+ return {+ assistantMessageId: wait?.assistantMessageId,+ resumed: true,+ topicId: state.origin?.topicId ?? undefined,+ };+ }++ /**+ * Put a run whose resume claim could not be completed back into its wait.+ * Other transitions may have raced the claim, so this re-reads the run+ * first. If a Stop moved it on (its settle could not match the claimed+ * `running` row), the row is settled to match instead of re-parked. If it is+ * still this park, the durable row goes back first — it is what resume,+ * expiry and Stop key off — and the expiry is re-armed, because one that+ * fired while the row read `running` gave up. Each step is best-effort so+ * one failure does not skip the rest.+ */+ private async restoreClientLlmWait(operationId: string, parkedState: AgentState) {+ const wait = parkedState.clientLlmWait;+ const current = await this.coordinator.loadAgentState(operationId).catch(() => null);+ const stillParked =+ current?.status === 'waiting_for_client' &&+ current.clientLlmWait?.parkedAt === wait?.parkedAt;++ if (!stillParked) {+ if (current?.status === 'interrupted') {+ const settled = await this.agentOperationModel+ .settleRunning(operationId, 'interrupted')+ .catch(() => false);+ if (settled) {+ await this.completionLifecycle+ .dispatchHooks(operationId, current, 'interrupted')+ .catch((error) => log('[%s] Failed to finish the stop: %O', operationId, error));+ }+ }+ return;+ }++ // The visible wait is only worth restoring once the row is parked again:+ // with the row stuck `running`, no resume, expiry or Stop can reach it, and+ // the abandoned-run watchdog is what settles it.+ if (!(await this.revertClientWaitResumeWithRetry(operationId))) {+ log('[%s] Could not re-park the durable row; leaving it to the watchdog', operationId);+ return;+ }+ await this.coordinator+ .saveAgentState(operationId, parkedState)+ .catch((error) => log('[%s] Failed to restore the parked state: %O', operationId, error));+ if (wait?.assistantMessageId) {+ await this.messageModel+ .update(wait.assistantMessageId, { error: buildClientLlmWaitMessageError(wait) })+ .catch((error) => log('[%s] Failed to restore the waiting notice: %O', operationId, error));+ }+ if (!wait) return;++ // Duplicate expiries are no-ops (they match on `parkedAt` and the row CAS).+ if (Date.now() >= Date.parse(wait.expiresAt)) {+ await this.expireClientLlmWait(operationId, wait.parkedAt).catch((error) =>+ log('[%s] Failed to expire the overdue wait: %O', operationId, error),+ );+ return;+ }+ await this.queueService+ ?.scheduleMessage({+ context: undefined,+ delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),+ endpoint: `${this.baseURL}/run`,+ operationId,+ payload: { clientLlmWaitExpired: wait.parkedAt },+ priority: 'normal',+ stepIndex: parkedState.stepCount,+ })+ .catch((error) => log('[%s] Failed to re-arm the wait expiry: %O', operationId, error));+ }++ /** Put the claimed row back to `waiting_for_client`, riding out a transient DB error. */+ private async revertClientWaitResumeWithRetry(operationId: string): Promise<boolean> {+ for (const delayMs of CLIENT_WAIT_REVERT_RETRY_DELAYS_MS) {+ if (delayMs) await new Promise((resolve) => setTimeout(resolve, delayMs));+ try {+ // `false` means the row is no longer the claimed `running` one, so it+ // is not ours to put back.+ return await this.agentOperationModel.revertClientWaitResume(operationId);+ } catch (error) {+ log('[%s] Failed to re-park the durable row: %O', operationId, error);+ }+ }+ return false;+ }++ /**+ * Runs of this user parked in `waiting_for_client`, with what a client needs+ * to pick one up: the provider it must be able to run, and where the run's+ * conversation lives so it can subscribe to the stream before resuming.+ */+ async listClientLlmWaits(providers?: string[]): Promise<ClientLlmWaitItem[]> {+ const rows = await this.agentOperationModel.listWaitingForClient({ providers });+ const items = await pMap(+ rows,+ async (row): Promise<ClientLlmWaitItem | undefined> => {+ const state = await this.coordinator.loadAgentState(row.id).catch(() => null);+ const wait = state?.clientLlmWait;+ if (state?.status !== 'waiting_for_client' || !wait) return;+ return {+ agentId: state.origin?.agentId ?? undefined,+ assistantMessageId: wait.assistantMessageId,+ expiresAt: wait.expiresAt,+ operationId: row.id,+ provider: wait.provider,+ threadId: state.origin?.threadId ?? undefined,+ topicId: state.origin?.topicId ?? row.topicId ?? undefined,+ };+ },+ { concurrency: 4 },+ );+ return items.filter((item): item is ClientLlmWaitItem => !!item);+ }++ /**+ * End a `waiting_for_client` park nobody resumed in time. A no-op unless the+ * run is still parked on the very wait that armed this check; the durable+ * row CAS keeps a racing resume from being killed.+ */+ private async expireClientLlmWait(operationId: string, parkedAt: string): Promise<boolean> {+ const state = await this.coordinator.loadAgentState(operationId);++ // A redelivery after this expiry already ended the run but its lifecycle+ // delivery threw (a critical hook asks QStash to retry): deliver it again,+ // like a retried terminal step does.+ if (state?.status === 'error' && isClientLlmWaitExpiryOf(state, parkedAt)) {+ log('[%s] Redelivering the lifecycle of an expired client wait', operationId);+ await this.finishClientLlmWaitExpiry(operationId, state);+ return true;+ }++ if (state?.status !== 'waiting_for_client' || state.clientLlmWait?.parkedAt !== parkedAt) {+ return false;+ }++ // Redis still holds this exact park. A row this CAS cannot claim is one a+ // resume took (`running`), unless it is already `error`: then an earlier+ // delivery of this expiry settled it and failed before finishing (resumes,+ // Stop and failing steps all move the Redis state off this park first), so+ // finish it now — QStash retries the delivery that threw.+ const settled = await this.agentOperationModel.settleClientWait(operationId);+ if (!settled) {+ const row = await this.agentOperationModel.findById(operationId);+ if (row?.status !== 'error') return false;+ log('[%s] Finishing a client wait expiry that settled but did not finish', operationId);+ }++ await this.endExpiredClientLlmWait(operationId, state, state.clientLlmWait);++ log('[%s] waiting_for_client expired (parked at %s)', operationId, parkedAt);+ return true;+ }++ /**+ * The terminal half of an expiry, once the durable row reads `error`: the+ * parked call's row, the Redis state (which ends the stream) and the+ * lifecycle. `state` is the run as it was parked on `wait`.+ */+ private async endExpiredClientLlmWait(+ operationId: string,+ state: AgentState,+ wait: AgentRunClientLlmWait,+ ) {+ const provider = wait.provider;+ const finalState: AgentState = {+ ...state,+ clientLlmWait: undefined,+ error: formatErrorForState(+ createClientLlmExecutorUnavailableError(provider, 'wait_timeout', {+ waitedSince: wait.parkedAt,+ }),+ ),+ lastModified: new Date().toISOString(),+ status: 'error',+ };++ // The row gets the terminal error first: the save below ends the stream+ // with a `uiMessages` snapshot read from the DB, and an open tab adopts it,+ // so writing it later would leave that tab on the waiting notice. The+ // lifecycle writes the same error again when it finalizes the run.+ // A transient failure is retried here: the lifecycle's later write emits+ // no message patch, so a tab that took the stale snapshot would keep the+ // dead waiting notice until reload.+ const assistantMessageId = wait.assistantMessageId;+ if (assistantMessageId && finalState.error) {+ const message = this.completionLifecycle.extractErrorMessage(finalState.error);+ const error = { ...finalState.error, body: finalState.error.body ?? { message }, message };+ await this.updateAssistantRowWithRetry(operationId, assistantMessageId, { error });+ }++ // Ends the stream (`agent_runtime_end`) and finalizes the run like any failure.+ await this.coordinator.saveAgentState(operationId, finalState);+ await this.completionLifecycle.emitSignalEvents(operationId, finalState, 'error');+ await this.finishClientLlmWaitExpiry(operationId, finalState);+ }++ /**+ * Write a client-wait notice or error onto the assistant row, retrying a+ * transient failure: what a connected tab shows next is read from this row.+ */+ private async updateAssistantRowWithRetry(+ operationId: string,+ messageId: string,+ value: Parameters<MessageModel['update']>[1],+ ) {+ for (let attempt = 1; attempt <= CLIENT_WAIT_ROW_WRITE_ATTEMPTS; attempt += 1) {+ try {+ await this.messageModel.update(messageId, value);+ return;+ } catch (error) {+ log('[%s] Failed to write the assistant row (%d): %O', operationId, attempt, error);+ if (attempt < CLIENT_WAIT_ROW_WRITE_ATTEMPTS) {+ await new Promise((resolve) => setTimeout(resolve, 100 * attempt));+ }+ }+ }+ }++ /** Lifecycle delivery of an expired client wait; safe to repeat on redelivery. */+ private async finishClientLlmWaitExpiry(operationId: string, finalState: AgentState) {+ const provider = (finalState.error as { body?: { provider?: string } } | undefined)?.body+ ?.provider;+ await this.completionLifecycle.dispatchHooks(operationId, finalState, 'error');+ await this.traceRecorder.finalize(operationId, {+ completionReason: 'error',+ error: {+ message: `No LobeHub client picked up the ${provider ?? 'local model'} call in time`,+ type: String(finalState.error?.type ?? 'ClientLlmExecutorUnavailable'),+ },+ state: finalState,+ });+ }+/*** Arm the next bounded `verifyAsyncToolBarrier` re-check for a parent op whose* resume attempt found it not yet resumable. Skipped for terminal states@@ -4502,6 +5091,9 @@ export class AgentRuntimeService {// Parked waiting for an async tool result (client tool / sub-agent)if (state.status === 'waiting_for_async_tool') return false;+ // Parked waiting for a client to run the next LLM call+ if (state.status === 'waiting_for_client') return false;+// Error occurredif (state.status === 'error') return false;@@ -4628,6 +5220,7 @@ export class AgentRuntimeService {if (state.status === 'interrupted') return 'interrupted';if (state.status === 'waiting_for_human') return 'waiting_for_human';if (state.status === 'waiting_for_async_tool') return 'waiting_for_async_tool';+ if (state.status === 'waiting_for_client') return 'waiting_for_client';// Checked ahead of 'done' on purpose: a run the repeat guard cut short ends// in exactly that status, having emitted a turn with no tool calls. Reading// it as a plain 'done' is what made these runs uncountable.diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 857b22652a8..8982a148b46 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -331,7 +331,13 @@ export class CompletionLifecycle {*/private statusForReason(reason: string,- ): 'done' | 'error' | 'interrupted' | 'waiting_for_human' | 'waiting_for_async_tool' {+ ):+ | 'done'+ | 'error'+ | 'interrupted'+ | 'waiting_for_human'+ | 'waiting_for_async_tool'+ | 'waiting_for_client' {switch (reason) {case 'error': {return 'error';@@ -345,6 +351,9 @@ export class CompletionLifecycle {case 'waiting_for_async_tool': {return 'waiting_for_async_tool';}+ case 'waiting_for_client': {+ return 'waiting_for_client';+ }default: {return 'done';}@@ -368,7 +377,8 @@ export class CompletionLifecycle {reason === 'cost_limit' ||reason === 'tool_call_repeat_limit' ||reason === 'waiting_for_human' ||- reason === 'waiting_for_async_tool'+ reason === 'waiting_for_async_tool' ||+ reason === 'waiting_for_client'? reason: this.statusForReason(reason);@@ -926,7 +936,9 @@ export class CompletionLifecycle {// schedules a fresh continuation operation and then retires this parked// segment; the continuation receives the serialized hooks through// `host.hooks`.- const isAsyncToolPark = reason === 'waiting_for_async_tool';+ // `waiting_for_client` (no client to run the next LLM call) parks the same+ // operation the same way: it resumes under this id or expires to `error`.+ const isAsyncToolPark = reason === 'waiting_for_async_tool' || reason === 'waiting_for_client';let shouldRetainHooksForRetry = false;try {diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 26a0bfdfcf7..a6855f2b10d 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -892,6 +892,20 @@ describe('CompletionLifecycle.dispatchHooks — async-tool park', () => {expect(unregisterSpy).not.toHaveBeenCalled();});+ it('treats a waiting_for_client park the same way: persisted, no onComplete, hooks kept', async () => {+ const lifecycle = buildLifecycle();+ const persistSpy = vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});+ const clientPark = { ...parkedState, status: 'waiting_for_client' };++ await lifecycle.dispatchHooks('op-1', clientPark, 'waiting_for_client');++ expect(persistSpy).toHaveBeenCalledWith('op-1', clientPark, 'waiting_for_client', undefined);+ expect(dispatchSpy).not.toHaveBeenCalled();+ expect(unregisterSpy).not.toHaveBeenCalled();+ });+it('fires onComplete and unregisters on a terminal completion', async () => {const lifecycle = buildLifecycle();vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);diff --git a/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.tsnew file mode 100644index 00000000000..89f11ea76ca--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts@@ -0,0 +1,1102 @@+// @vitest-environment node+import { AgentRuntimeErrorType } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import { createClientLlmExecutorUnavailableError } from '@/server/modules/AgentRuntime/llmRelay/errors';++import { AgentRuntimeService } from '../AgentRuntimeService';++vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ findLatestAssistantByOperationId: vi.fn(),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));+vi.mock('@/server/modules/AgentRuntime', () => ({+ AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {+ return {+ createAgentOperation: vi.fn(),+ getOperationMetadata: vi.fn(),+ hasQueuedMessages: vi.fn().mockResolvedValue(false),+ isInterrupted: vi.fn().mockResolvedValue(false),+ loadAgentState: vi.fn(),+ markInterrupted: vi.fn().mockResolvedValue(undefined),+ refreshStepLock: vi.fn().mockResolvedValue(true),+ releaseStepLock: vi.fn().mockResolvedValue(undefined),+ saveAgentState: vi.fn(),+ saveStepResult: vi.fn(),+ tryClaimStep: vi.fn().mockResolvedValue(true),+ };+ }),+ createStreamEventManager: vi.fn(function () {+ return {+ cleanupOperation: vi.fn(),+ publishAgentRuntimeEnd: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ publishStreamEvent: vi.fn(),+ };+ }),+}));+vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({+ createRuntimeExecutors: vi.fn(function () {+ return {};+ }),+}));+vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));+vi.mock('@/server/services/queue/impls', () => ({ LocalQueueServiceImpl: class {} }));+vi.mock('@/server/services/toolExecution', () => ({+ ToolExecutionService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));+vi.mock('@/server/services/toolExecution/builtin', () => ({+ BuiltinToolsExecutor: vi.fn().mockImplementation(function () {+ return {};+ }),+}));+vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({+ dynamicInterventionAudits: [],+}));++const OPERATION_ID = 'op-local-model';+const NOW = Date.parse('2026-10-04T08:00:00.000Z');++const runningState = (overrides: Record<string, unknown> = {}) => ({+ host: {},+ lastModified: new Date(NOW).toISOString(),+ messages: [{ content: 'hi', role: 'user' }],+ metadata: {},+ modelRuntimeConfig: { model: 'qwen', provider: 'lmstudio' },+ origin: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ status: 'running',+ stepCount: 1,+ ...overrides,+});++const unavailableErrorState = (+ reason: Parameters<typeof createClientLlmExecutorUnavailableError>[1],+) =>+ runningState({+ error: formatErrorForState(createClientLlmExecutorUnavailableError('lmstudio', reason)),+ status: 'error',+ stepCount: 2,+ });++const waitingState = (overrides: Record<string, unknown> = {}) =>+ runningState({+ clientLlmWait: {+ assistantMessageId: 'msg-assistant',+ expiresAt: new Date(NOW + 600_000).toISOString(),+ parentMessageId: 'msg-user',+ parkedAt: new Date(NOW).toISOString(),+ provider: 'lmstudio',+ reason: 'no_executor',+ },+ status: 'waiting_for_client',+ stepCount: 2,+ ...overrides,+ });++const llmExecutor = {+ capabilities: ['llm_relay@1', 'llm_client_wait@1'],+ clientId: 'tab-b',+ providers: ['lmstudio'],+};++const createService = () => {+ const scheduleMessage = vi.fn().mockResolvedValue('queued');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ const messageModel = (service as any).messageModel;+ const operationModel = (service as any).agentOperationModel;+ const completionLifecycle = (service as any).completionLifecycle;++ let stored: any;+ coordinator.loadAgentState = vi.fn(async () => stored);+ coordinator.saveStepResult = vi.fn(async (_id: string, result: any) => {+ stored = result.newState;+ });+ coordinator.saveAgentState = vi.fn(async (_id: string, state: any) => {+ stored = state;+ });+ operationModel.findById = vi.fn().mockResolvedValue({ status: 'running' });+ operationModel.touchRunning = vi.fn().mockResolvedValue(undefined);+ operationModel.tryResumeFromClientWait = vi.fn().mockResolvedValue(true);+ operationModel.settleClientWait = vi.fn().mockResolvedValue(true);+ operationModel.recordCompletion = vi.fn().mockResolvedValue(true);+ vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);+ const dispatchHooks = vi.spyOn(completionLifecycle, 'dispatchHooks').mockResolvedValue(undefined);+ const traceFinalize = vi+ .spyOn((service as any).traceRecorder, 'finalize')+ .mockResolvedValue(undefined);+ const traceFlushPartial = vi+ .spyOn((service as any).traceRecorder, 'flushPartial')+ .mockResolvedValue(undefined);++ const mockStep = (result: any) => {+ const step = vi.fn().mockResolvedValue(result);+ (service as any).createAgentRuntime = vi.fn().mockResolvedValue({ runtime: { step } });+ return step;+ };++ return {+ coordinator,+ traceFinalize,+ traceFlushPartial,+ dispatchHooks,+ getStored: () => stored,+ messageModel,+ mockStep,+ operationModel,+ scheduleMessage,+ service,+ setStored: (state: any) => {+ stored = state;+ },+ };+};++describe('waiting_for_client (U4c)', () => {+ beforeEach(() => {+ vi.useFakeTimers({ now: NOW, toFake: ['Date'] });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('parking', () => {+ it.each(['no_executor', 'claim_timeout', 'not_delivered'] as const)(+ 'parks a step whose LLM call found no client (%s) instead of failing the run',+ async (reason) => {+ const t = createService();+ t.setStored(runningState());+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({+ id: 'msg-assistant',+ parentId: 'msg-user',+ });+ t.mockStep({ events: [], newState: unavailableErrorState(reason), nextContext: undefined });++ const result = await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ const parked = t.getStored();+ expect(parked.status).toBe('waiting_for_client');+ expect(parked.error).toBeUndefined();+ expect(parked.clientLlmWait).toEqual({+ assistantMessageId: 'msg-assistant',+ context: { phase: 'user_input' },+ expiresAt: new Date(NOW + 600_000).toISOString(),+ parentMessageId: 'msg-user',+ parkedAt: new Date(NOW).toISOString(),+ provider: 'lmstudio',+ reason,+ });+ expect(result.nextStepScheduled).toBe(false);++ // The durable row is parked before anything advertises the wait.+ expect(t.operationModel.recordCompletion).toHaveBeenCalledWith(OPERATION_ID, {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ expect(t.operationModel.recordCompletion.mock.invocationCallOrder[0]).toBeLessThan(+ t.messageModel.update.mock.invocationCallOrder[0],+ );++ // The assistant row says why the run waits, flagged for the waiting card.+ expect(t.messageModel.update).toHaveBeenCalledWith('msg-assistant', {+ error: expect.objectContaining({+ body: expect.objectContaining({+ provider: 'lmstudio',+ reason,+ waitingForClient: true,+ }),+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ }),+ });++ // Only the expiry check is queued — no next step.+ expect(t.scheduleMessage).toHaveBeenCalledTimes(1);+ expect(t.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ delay: 600_000,+ operationId: OPERATION_ID,+ payload: { clientLlmWaitExpired: new Date(NOW).toISOString() },+ stepIndex: 1,+ }),+ );++ // No trace boundary: the partial carries over to the resumed steps.+ expect(t.traceFinalize).not.toHaveBeenCalled();+ expect(t.traceFlushPartial).toHaveBeenCalled();++ // Persisted as a park: same lifecycle as an async-tool park, no completion.+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'waiting_for_client' }),+ 'waiting_for_client',+ );+ },+ );++ it.each([+ ['a client that cannot wait', ['llm_relay@1'], 'error'],+ ['a client that can wait', ['llm_relay@1', 'llm_client_wait@1'], 'waiting_for_client'],+ ])(+ 'for a run started by %s (%j), the step ends as %s',+ async (_label, capabilities, status) => {+ const t = createService();+ const host = { llmExecutor: { capabilities, clientId: 'tab-a', providers: ['lmstudio'] } };+ t.setStored(runningState({ host }));+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({+ id: 'msg-assistant',+ parentId: 'msg-user',+ });+ t.mockStep({+ events: [],+ newState: { ...unavailableErrorState('no_executor'), host },+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ expect(t.getStored().status).toBe(status);+ },+ );++ it('retries a failed waiting-notice write so the park is visible', async () => {+ const t = createService();+ t.setStored(runningState());+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({+ id: 'msg-assistant',+ parentId: 'msg-user',+ });+ t.messageModel.update.mockRejectedValueOnce(new Error('db blip'));+ t.mockStep({+ events: [],+ newState: unavailableErrorState('no_executor'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ const noticeWrites = t.messageModel.update.mock.calls.filter(+ ([id, value]: any[]) => id === 'msg-assistant' && value?.error?.body?.waitingForClient,+ );+ expect(noticeWrites).toHaveLength(2);+ expect(t.getStored().status).toBe('waiting_for_client');+ });++ it('parks on the step count the call started from, so the replay does not spend a step', async () => {+ const t = createService();+ // The parked call is the run's last allowed step.+ t.setStored(runningState({ maxSteps: 2, stepCount: 1 }));+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({+ id: 'msg-assistant',+ parentId: 'msg-user',+ });+ // `runtime.step` counted the call and hit the limit before it failed.+ t.mockStep({+ events: [],+ newState: { ...unavailableErrorState('no_executor'), forceFinish: true, maxSteps: 2 },+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ const parked = t.getStored();+ expect(parked.status).toBe('waiting_for_client');+ expect(parked.stepCount).toBe(1);+ expect(parked.forceFinish).toBeUndefined();+ });++ it.each([+ ['the durable row cannot be written', () => Promise.reject(new Error('db down'))],+ ['there is no durable row to park', () => Promise.resolve(false)],+ ])('fails the step instead of parking when %s', async (_label, recordCompletion) => {+ const t = createService();+ t.setStored(runningState());+ t.operationModel.recordCompletion = vi.fn(recordCompletion);+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({ id: 'msg-assistant' });+ t.mockStep({+ events: [],+ newState: unavailableErrorState('no_executor'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ expect(t.getStored().status).toBe('error');+ expect(t.getStored().clientLlmWait).toBeUndefined();+ expect(t.messageModel.update).not.toHaveBeenCalledWith(+ 'msg-assistant',+ expect.objectContaining({+ error: expect.objectContaining({+ body: expect.objectContaining({ waitingForClient: true }),+ }),+ }),+ );+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ });++ it('fails the step instead of parking when it has no assistant row to reconnect on', async () => {+ const t = createService();+ t.setStored(runningState());+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue(undefined);+ t.mockStep({+ events: [],+ newState: unavailableErrorState('no_executor'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ expect(t.getStored().status).toBe('error');+ expect(t.operationModel.recordCompletion).not.toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'waiting_for_client' }),+ );+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ });++ it('keeps failing a step a client cannot fix (relay_unsupported)', async () => {+ const t = createService();+ t.setStored(runningState());+ t.mockStep({+ events: [],+ newState: unavailableErrorState('relay_unsupported'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ expect(t.getStored().status).toBe('error');+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ expect(t.dispatchHooks).toHaveBeenCalledWith(OPERATION_ID, expect.anything(), 'error');+ });++ it('honours AGENT_LLM_RELAY_CLIENT_WAIT_MS for the wait window', async () => {+ vi.stubEnv('AGENT_LLM_RELAY_CLIENT_WAIT_MS', '60000');+ try {+ const t = createService();+ t.setStored(runningState());+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({ id: 'msg-assistant' });+ t.mockStep({+ events: [],+ newState: unavailableErrorState('no_executor'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });++ expect(t.getStored().clientLlmWait.expiresAt).toBe(new Date(NOW + 60_000).toISOString());+ expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 60_000 }));+ } finally {+ vi.unstubAllEnvs();+ }+ });+ });++ describe('resuming', () => {+ it('records the asking client as executor and replays the parked step', async () => {+ const t = createService();+ t.setStored(waitingState());++ const result = await t.service.resumeFromClientLlmWait({+ llmExecutor,+ operationId: OPERATION_ID,+ });++ expect(result).toEqual({+ assistantMessageId: 'msg-assistant',+ resumed: true,+ topicId: 'tpc-1',+ });+ expect(t.operationModel.tryResumeFromClientWait).toHaveBeenCalledWith(OPERATION_ID);+ expect(t.getStored().host.llmExecutor).toEqual(llmExecutor);+ expect(t.messageModel.update).toHaveBeenCalledWith('msg-assistant', { error: null });+ expect(t.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: OPERATION_ID,+ payload: { resumeClientLlm: true },+ stepIndex: 2,+ }),+ );+ });++ it('resumes once when two clients race (CAS lost)', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.tryResumeFromClientWait.mockResolvedValue(false);++ const result = await t.service.resumeFromClientLlmWait({+ llmExecutor,+ operationId: OPERATION_ID,+ });++ expect(result.resumed).toBe(false);+ expect(t.coordinator.saveAgentState).not.toHaveBeenCalled();+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ });++ it('stays parked and resumable when the resume step cannot be enqueued', async () => {+ const t = createService();+ const parked = waitingState();+ t.setStored(parked);+ t.operationModel.revertClientWaitResume = vi.fn().mockResolvedValue(true);+ t.scheduleMessage.mockRejectedValueOnce(new Error('QStash 503'));++ await expect(+ t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID }),+ ).rejects.toThrow('QStash 503');++ expect(t.operationModel.revertClientWaitResume).toHaveBeenCalledWith(OPERATION_ID);+ expect(t.getStored()).toEqual(parked);+ expect(t.messageModel.update).toHaveBeenLastCalledWith('msg-assistant', {+ error: expect.objectContaining({+ body: expect.objectContaining({ waitingForClient: true }),+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ }),+ });+ });++ it('stays parked when saving the claimed state fails, even if restoring it fails too', async () => {+ const t = createService();+ const parked = waitingState();+ t.setStored(parked);+ t.operationModel.revertClientWaitResume = vi.fn().mockResolvedValue(true);+ t.coordinator.saveAgentState = vi.fn().mockRejectedValue(new Error('redis down'));++ await expect(+ t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID }),+ ).rejects.toThrow('redis down');++ expect(t.operationModel.revertClientWaitResume).toHaveBeenCalledWith(OPERATION_ID);+ expect(t.scheduleMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({ payload: { resumeClientLlm: true } }),+ );+ expect(t.messageModel.update).toHaveBeenLastCalledWith('msg-assistant', {+ error: expect.objectContaining({+ body: expect.objectContaining({ waitingForClient: true }),+ }),+ });+ });++ it('fails instead of re-parking once the original wait is used up', async () => {+ const t = createService();+ t.setStored(+ waitingState({+ clientLlmWait: {+ assistantMessageId: 'msg-assistant',+ context: { phase: 'user_input' },+ expiresAt: new Date(NOW + 1000).toISOString(),+ parkedAt: new Date(NOW - 600_000).toISOString(),+ provider: 'lmstudio',+ reason: 'no_executor',+ },+ }),+ );+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({ id: 'msg-assistant' });+ t.mockStep({+ events: [],+ newState: unavailableErrorState('not_delivered'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ operationId: OPERATION_ID,+ resumeClientLlm: true,+ stepIndex: 2,+ });++ // No expiry could race the step's own commit: the run just fails.+ expect(t.getStored().status).toBe('error');+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ });++ it('has the re-park in place before arming its expiry', async () => {+ const t = createService();+ const deadline = new Date(NOW + 10_000).toISOString();+ t.setStored(+ waitingState({+ clientLlmWait: {+ assistantMessageId: 'msg-assistant',+ context: { phase: 'user_input' },+ expiresAt: deadline,+ parkedAt: new Date(NOW - 600_000).toISOString(),+ provider: 'lmstudio',+ reason: 'no_executor',+ },+ }),+ );+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({ id: 'msg-assistant' });+ t.mockStep({+ events: [],+ newState: unavailableErrorState('not_delivered'),+ nextContext: undefined,+ });+ // What an immediately delivered expiry would see when it runs.+ let seenByExpiry: any;+ let noticeWritten = false;+ t.messageModel.update.mockImplementation(async (_id: string, value: any) => {+ if (value.error?.body?.waitingForClient) noticeWritten = true;+ });+ t.scheduleMessage.mockImplementation(async (message: any) => {+ if (message.payload?.clientLlmWaitExpired) {+ seenByExpiry = { noticeWritten, state: structuredClone(t.getStored()) };+ }+ return 'queued';+ });++ await t.service.executeStep({+ operationId: OPERATION_ID,+ resumeClientLlm: true,+ stepIndex: 2,+ });++ expect(t.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ delay: 10_000,+ payload: { clientLlmWaitExpired: expect.any(String) },+ }),+ );+ expect(seenByExpiry.state.status).toBe('waiting_for_client');+ expect(seenByExpiry.state.clientLlmWait.parkedAt).toBe(new Date(NOW).toISOString());+ expect(seenByExpiry.noticeWritten).toBe(true);+ });++ it('keeps the original deadline when a resumed call finds no client again', async () => {+ const t = createService();+ const deadline = new Date(NOW + 120_000).toISOString();+ t.setStored(+ waitingState({+ clientLlmWait: {+ assistantMessageId: 'msg-assistant',+ context: { phase: 'user_input' },+ expiresAt: deadline,+ parkedAt: new Date(NOW - 480_000).toISOString(),+ provider: 'lmstudio',+ reason: 'no_executor',+ },+ }),+ );+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({ id: 'msg-assistant' });+ t.mockStep({+ events: [],+ newState: unavailableErrorState('not_delivered'),+ nextContext: undefined,+ });++ await t.service.executeStep({+ operationId: OPERATION_ID,+ resumeClientLlm: true,+ stepIndex: 2,+ });++ expect(t.getStored().status).toBe('waiting_for_client');+ expect(t.getStored().clientLlmWait.expiresAt).toBe(deadline);+ expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 120_000 }));+ });++ it('leaves a wait past its deadline to the (late) expiry instead of resuming it', async () => {+ const t = createService();+ t.setStored(+ waitingState({+ clientLlmWait: {+ assistantMessageId: 'msg-assistant',+ expiresAt: new Date(NOW - 1).toISOString(),+ parkedAt: new Date(NOW - 600_000).toISOString(),+ provider: 'lmstudio',+ reason: 'no_executor',+ },+ }),+ );++ const result = await t.service.resumeFromClientLlmWait({+ llmExecutor,+ operationId: OPERATION_ID,+ });++ expect(result.resumed).toBe(false);+ expect(t.operationModel.tryResumeFromClientWait).not.toHaveBeenCalled();+ expect(t.scheduleMessage).not.toHaveBeenCalled();+ });++ it('retries a failed durable rollback before restoring the wait', async () => {+ vi.useFakeTimers({ now: NOW, toFake: ['Date', 'setTimeout'] });+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.revertClientWaitResume = vi+ .fn()+ .mockRejectedValueOnce(new Error('db blip'))+ .mockResolvedValue(true);+ t.scheduleMessage.mockRejectedValueOnce(new Error('QStash 503')).mockResolvedValue('queued');++ const resume = t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID });+ const settled = expect(resume).rejects.toThrow('QStash 503');+ await vi.runAllTimersAsync();+ await settled;++ expect(t.operationModel.revertClientWaitResume).toHaveBeenCalledTimes(2);+ expect(t.getStored().status).toBe('waiting_for_client');+ expect(t.messageModel.update).toHaveBeenLastCalledWith('msg-assistant', {+ error: expect.objectContaining({+ body: expect.objectContaining({ waitingForClient: true }),+ }),+ });+ });++ it('does not restore a wait whose durable row cannot be put back', async () => {+ vi.useFakeTimers({ now: NOW, toFake: ['Date', 'setTimeout'] });+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.revertClientWaitResume = vi.fn().mockRejectedValue(new Error('db down'));+ t.scheduleMessage.mockRejectedValueOnce(new Error('QStash 503')).mockResolvedValue('queued');++ const resume = t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID });+ const settled = expect(resume).rejects.toThrow('QStash 503');+ await vi.runAllTimersAsync();+ await settled;++ expect(t.operationModel.revertClientWaitResume).toHaveBeenCalledTimes(3);+ // No waiting notice or expiry advertising a wait nothing can resume.+ expect(t.messageModel.update).not.toHaveBeenCalledWith('msg-assistant', {+ error: expect.objectContaining({+ body: expect.objectContaining({ waitingForClient: true }),+ }),+ });+ expect(t.scheduleMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({ clientLlmWaitExpired: expect.any(String) }),+ }),+ );+ });++ it('re-arms the expiry when rolling back, since one may have fired during the claim', async () => {+ const t = createService();+ const parked = waitingState();+ t.setStored(parked);+ t.operationModel.revertClientWaitResume = vi.fn().mockResolvedValue(true);+ t.scheduleMessage.mockRejectedValueOnce(new Error('QStash 503')).mockResolvedValue('queued');++ await expect(+ t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID }),+ ).rejects.toThrow('QStash 503');++ expect(t.getStored().status).toBe('waiting_for_client');+ expect(t.scheduleMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({+ payload: { clientLlmWaitExpired: new Date(NOW).toISOString() },+ }),+ );+ });++ it('does not replay the call when a Stop lands between the claim and its save', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.settleRunning = vi.fn().mockResolvedValue(true);+ // Stop ran after the claim: its sentinel is set, its settle missed the+ // `running` row, and the claim's save overwrote its `interrupted` state.+ t.coordinator.isInterrupted.mockResolvedValue(true);++ await expect(+ t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID }),+ ).resolves.toEqual({ resumed: false });++ expect(t.scheduleMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({ payload: { resumeClientLlm: true } }),+ );+ expect(t.getStored().status).toBe('interrupted');+ expect(t.operationModel.settleRunning).toHaveBeenCalledWith(OPERATION_ID, 'interrupted');+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'interrupted' }),+ 'interrupted',+ );+ });++ it('settles a Stop that raced the claim instead of re-parking over it', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.revertClientWaitResume = vi.fn().mockResolvedValue(true);+ t.operationModel.settleRunning = vi.fn().mockResolvedValue(true);+ // Stop lands while the row reads `running`: it saves `interrupted`, and its+ // own settle (which only matches a parked row) cannot apply.+ t.scheduleMessage.mockImplementationOnce(async () => {+ t.setStored({ ...t.getStored(), clientLlmWait: undefined, status: 'interrupted' });+ throw new Error('QStash 503');+ });++ await expect(+ t.service.resumeFromClientLlmWait({ llmExecutor, operationId: OPERATION_ID }),+ ).rejects.toThrow('QStash 503');++ expect(t.operationModel.revertClientWaitResume).not.toHaveBeenCalled();+ expect(t.getStored().status).toBe('interrupted');+ expect(t.operationModel.settleRunning).toHaveBeenCalledWith(OPERATION_ID, 'interrupted');+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'interrupted' }),+ 'interrupted',+ );+ });++ it('does nothing for a run that is not parked', async () => {+ const t = createService();+ t.setStored(runningState());++ const result = await t.service.resumeFromClientLlmWait({+ llmExecutor,+ operationId: OPERATION_ID,+ });++ expect(result.resumed).toBe(false);+ expect(t.operationModel.tryResumeFromClientWait).not.toHaveBeenCalled();+ });++ it('re-runs the parked LLM turn into its own assistant row on resume', async () => {+ const t = createService();+ t.setStored(waitingState());+ const step = t.mockStep({+ events: [],+ newState: runningState({ status: 'done', stepCount: 3 }),+ nextContext: undefined,+ });++ await t.service.executeStep({+ operationId: OPERATION_ID,+ resumeClientLlm: true,+ stepIndex: 2,+ });++ expect(step).toHaveBeenCalledTimes(1);+ const [state, context] = step.mock.calls[0];+ expect(state.status).toBe('running');+ expect(state.clientLlmWait).toBeUndefined();+ expect(state.messages).toEqual([{ content: 'hi', role: 'user' }]);+ expect(state.pendingAssistantMessageId).toBe('msg-assistant');+ expect(context).toEqual({+ payload: { assistantMessageId: 'msg-assistant', parentMessageId: 'msg-user' },+ phase: 'user_input',+ });+ });++ it('replays the parked continuation context, not a generic user turn', async () => {+ const t = createService();+ t.setStored(runningState());+ t.messageModel.findLatestAssistantByOperationId.mockResolvedValue({+ id: 'msg-assistant',+ parentId: 'msg-tool',+ });+ const parkedContext = {+ payload: { parentMessageId: 'msg-tool' },+ phase: 'sub_agents_batch_result',+ stepContext: { hasQueuedMessages: false },+ };+ t.mockStep({+ events: [],+ newState: unavailableErrorState('no_executor'),+ nextContext: undefined,+ });+ await t.service.executeStep({+ context: parkedContext as any,+ operationId: OPERATION_ID,+ stepIndex: 1,+ });+ expect(t.getStored().clientLlmWait.context).toEqual({+ payload: { parentMessageId: 'msg-tool' },+ phase: 'sub_agents_batch_result',+ });++ const step = t.mockStep({+ events: [],+ newState: runningState({ status: 'done', stepCount: 3 }),+ nextContext: undefined,+ });+ await t.service.executeStep({+ operationId: OPERATION_ID,+ resumeClientLlm: true,+ stepIndex: 2,+ });++ const [state, context] = step.mock.calls[0];+ expect(context).toMatchObject({+ payload: { parentMessageId: 'msg-tool' },+ phase: 'sub_agents_batch_result',+ });+ expect(state.pendingAssistantMessageId).toBe('msg-assistant');+ });++ it('ignores a plain step delivery while the run waits for a client', async () => {+ const t = createService();+ t.setStored(waitingState());+ const step = t.mockStep({ events: [], newState: runningState(), nextContext: undefined });++ const result = await t.service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(step).not.toHaveBeenCalled();+ expect(result.state.status).toBe('waiting_for_client');+ });+ });++ describe('expiry', () => {+ it('ends a run nobody picked up with an actionable wait_timeout error', async () => {+ const t = createService();+ t.setStored(waitingState());++ const result = await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(result.state).toEqual({ status: 'error' });+ expect(t.operationModel.settleClientWait).toHaveBeenCalledWith(OPERATION_ID);+ const final = t.getStored();+ expect(final.status).toBe('error');+ expect(final.clientLlmWait).toBeUndefined();+ expect(final.error).toMatchObject({+ body: expect.objectContaining({ reason: 'wait_timeout' }),+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ });+ // The error lands on the assistant row through the normal failure path.+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'error' }),+ 'error',+ );+ });++ it('writes the expiry error onto the assistant row before ending the stream', async () => {+ const t = createService();+ t.setStored(waitingState());+ // The end event's `uiMessages` snapshot is read from the DB inside this+ // save; record what the assistant row held at that moment.+ let rowErrorAtEnd: unknown;+ t.coordinator.saveAgentState.mockImplementationOnce(async (_id: string, state: any) => {+ const writes = t.messageModel.update.mock.calls.filter(+ ([id]: any[]) => id === 'msg-assistant',+ );+ rowErrorAtEnd = writes.at(-1)?.[1]?.error;+ t.setStored(state);+ });++ await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(rowErrorAtEnd).toMatchObject({+ body: expect.objectContaining({ reason: 'wait_timeout' }),+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ });+ });++ it('retries a failed expiry-row write before ending the stream', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.messageModel.update.mockRejectedValueOnce(new Error('db blip'));+ let rowWritesAtEnd = 0;+ t.coordinator.saveAgentState.mockImplementationOnce(async (_id: string, state: any) => {+ rowWritesAtEnd = t.messageModel.update.mock.calls.filter(+ ([id]: any[]) => id === 'msg-assistant',+ ).length;+ t.setStored(state);+ });++ await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ // The failed write and its successful retry both happened before the end.+ expect(rowWritesAtEnd).toBe(2);+ });++ it('finishes on retry when an earlier delivery settled the row but failed to finish', async () => {+ const t = createService();+ t.setStored(waitingState());+ // First delivery: the CAS settled the row, then the Redis write failed.+ t.coordinator.saveAgentState.mockRejectedValueOnce(new Error('redis down'));+ await expect(+ t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ }),+ ).rejects.toThrow('redis down');+ expect(t.getStored().status).toBe('waiting_for_client');++ // The retry finds the row already terminal and the same park in Redis.+ t.operationModel.settleClientWait.mockResolvedValue(false);+ t.operationModel.findById.mockResolvedValue({ status: 'error' });++ const result = await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(result.state).toEqual({ status: 'error' });+ expect(t.getStored()).toMatchObject({ clientLlmWait: undefined, status: 'error' });+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'error' }),+ 'error',+ );+ });++ it('redelivers the lifecycle when a critical hook failed after the run ended', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.dispatchHooks.mockRejectedValueOnce(new Error('critical hook delivery failed'));+ const expire = () =>+ t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ await expect(expire()).rejects.toThrow('critical hook delivery failed');+ expect(t.getStored().status).toBe('error');++ // QStash redelivers; the durable row is terminal and Redis already says error.+ t.operationModel.findById.mockResolvedValue({ status: 'error' });+ const result = await expire();++ expect(result.state).toEqual({ status: 'error' });+ expect(t.dispatchHooks).toHaveBeenCalledTimes(2);+ expect(t.dispatchHooks).toHaveBeenLastCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'error' }),+ 'error',+ );+ });++ it('is a no-op once the run left that wait (resumed, or parked again later)', async () => {+ const t = createService();+ t.setStored(waitingState());++ await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW - 1000).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });+ t.setStored(runningState({ stepCount: 3 }));+ await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(t.operationModel.settleClientWait).not.toHaveBeenCalled();+ expect(t.coordinator.saveAgentState).not.toHaveBeenCalled();+ expect(t.dispatchHooks).not.toHaveBeenCalled();+ });++ it('leaves the run alone when a resume wins the durable row first', async () => {+ const t = createService();+ t.setStored(waitingState());+ t.operationModel.settleClientWait.mockResolvedValue(false);++ await t.service.executeStep({+ clientLlmWaitExpired: new Date(NOW).toISOString(),+ operationId: OPERATION_ID,+ stepIndex: 2,+ });++ expect(t.coordinator.saveAgentState).not.toHaveBeenCalled();+ expect(t.dispatchHooks).not.toHaveBeenCalled();+ });+ });++ it('settles a waiting run when it is stopped', async () => {+ const t = createService();+ t.setStored(waitingState());++ await expect(t.service.interruptOperation(OPERATION_ID)).resolves.toBe(true);++ expect(t.getStored().status).toBe('interrupted');+ expect(t.getStored().clientLlmWait).toBeUndefined();+ // The waiting card goes with the wait: nothing can continue a stopped run.+ expect(t.messageModel.update).toHaveBeenCalledWith('msg-assistant', { error: null });+ expect(t.operationModel.settleClientWait).toHaveBeenCalledWith(OPERATION_ID, 'interrupted');+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'interrupted' }),+ 'interrupted',+ );+ });++ it('finishes the expiry a Stop lost the row to, so the run does not hang half-ended', async () => {+ const t = createService();+ t.setStored(waitingState());+ // The expiry settled the row to `error` and failed before saving Redis.+ t.operationModel.settleClientWait = vi.fn().mockResolvedValue(false);+ t.operationModel.findById.mockResolvedValue({ status: 'error' });++ await expect(t.service.interruptOperation(OPERATION_ID)).resolves.toBe(true);++ // Redis ends as the row says, which a retried expiry can redeliver.+ expect(t.getStored()).toMatchObject({+ error: expect.objectContaining({+ body: expect.objectContaining({ reason: 'wait_timeout' }),+ }),+ status: 'error',+ });+ expect(t.dispatchHooks).toHaveBeenCalledWith(+ OPERATION_ID,+ expect.objectContaining({ status: 'error' }),+ 'error',+ );+ expect(t.dispatchHooks).not.toHaveBeenCalledWith(+ OPERATION_ID,+ expect.anything(),+ 'interrupted',+ );+ });+});diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex aa3a74cd9bc..58385f654cd 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -135,7 +135,8 @@ export type StepCompletionReason =| 'cost_limit'| 'tool_call_repeat_limit'| 'waiting_for_human'- | 'waiting_for_async_tool';+ | 'waiting_for_async_tool'+ | 'waiting_for_client';// ==================== Execution Params ====================@@ -147,6 +148,12 @@ export interface AgentExecutionParams {* (treated as attempt 1) on the first re-check armed by a completion bridge.*/asyncToolVerifyAttempt?: number;+ /**+ * Expiry check of a `waiting_for_client` park, carrying the park's+ * `parkedAt`. Scheduled when the run parks; ends the run with an actionable+ * error if it is still parked on that same wait. Runs without the step lock.+ */+ clientLlmWaitExpired?: string;context?: AgentRuntimeContext;externalRetryCount?: number;/**@@ -194,6 +201,11 @@ export interface AgentExecutionParams {* via `tryResumeParentFromAsyncTool`.*/resumeAsyncTool?: boolean;+ /**+ * Continue a run parked in `waiting_for_client`: replay the parked LLM call+ * now that a client asked to run it. Scheduled by `resumeFromClientLlmWait`.+ */+ resumeClientLlm?: boolean;/*** Keep the operation lock held after this step returns. Used by the inline* step loop so the lock spans the whole invocation rather than being droppeddiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex d066d9419ae..9b6124f7eea 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -361,6 +361,18 @@ export class AiAgentService {return this.agentRuntimeService.executeStep(params);}+ /** Continue a run parked in `waiting_for_client` (see AgentRuntimeService). */+ resumeFromClientLlmWait(+ params: Parameters<AgentRuntimeService['resumeFromClientLlmWait']>[0],+ ): ReturnType<AgentRuntimeService['resumeFromClientLlmWait']> {+ return this.agentRuntimeService.resumeFromClientLlmWait(params);+ }++ /** Runs of this user parked in `waiting_for_client`. */+ listClientLlmWaits(providers?: string[]): ReturnType<AgentRuntimeService['listClientLlmWaits']> {+ return this.agentRuntimeService.listClientLlmWaits(providers);+ }+/** Mint a lock owner that spans a whole inline step loop. */createOperationLockOwner(operationId: string): string {return this.agentRuntimeService.createOperationLockOwner(operationId);diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 918efd5bd6e..650498e96ef 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -3433,6 +3433,25 @@ describe('GoalService', () => {});});+ it('leaves a run parked for a client alone however long it has waited', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Wait for a local-model client',+ 'op-waiting-client',+ new Date('2026-01-01T00:10:00.000Z'),+ );+ // Parked in waiting_for_client (U4c): resumable until its own expiry.+ await serverDB+ .update(agentOperations)+ .set({ completionReason: 'waiting_for_client', status: 'waiting_for_client' })+ .where(eq(agentOperations.id, 'op-waiting-client'));++ const waiting = await service.tick(graph.goal.id);++ expect(timeoutSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ });+it('leaves a run that just ended to its own completion hook', async () => {const { created, graph, runSpy, service, timeoutSpy } = await setup('Wait for the completion hook',diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 0cfa10427a2..f77d5df1220 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -27,6 +27,7 @@ import type {TaskTopicHandoff,WorkVersionEventItem,} from '@lobechat/types';+import { isAgentOperationInFlight } from '@lobechat/types';import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';import { TRPCError } from '@trpc/server';import { sql } from 'drizzle-orm';@@ -3708,14 +3709,6 @@ export class GoalService {};}-/** Operation states that still own their run; the lease path reclaims them, not this. */-const IN_FLIGHT_OPERATION_STATUSES = new Set([- 'idle',- 'running',- 'waiting_for_async_tool',- 'waiting_for_human',-]);-/*** Whether a Task topic is still `running` although its run has already ended.*@@ -3735,7 +3728,9 @@ const isOrphanedRun = async (staleBefore: Date,): Promise<boolean> => {const operation = await operationModel.findById(operationId);- if (!operation || IN_FLIGHT_OPERATION_STATUSES.has(operation.status)) return false;+ // Still-owned states (including a run parked for a client) are the lease+ // path's to reclaim, not this.+ if (!operation || isAgentOperationInFlight(operation.status)) return false;const endedAt = operation.completedAt ?? operation.updatedAt;return new Date(endedAt) < staleBefore;};diff --git a/apps/server/src/services/verify/sweep.ts b/apps/server/src/services/verify/sweep.tsindex fecbe6b8ecb..f4c37ac4795 100644--- a/apps/server/src/services/verify/sweep.ts+++ b/apps/server/src/services/verify/sweep.ts@@ -1,4 +1,5 @@import type { VerifyCheckItem } from '@lobechat/types';+import { isAgentOperationInFlight } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -15,14 +16,6 @@ import { VerifyStatusService } from './statusService';const log = debug('lobe-server:verify-sweep');-/** An operation in any of these can still produce a verdict. */-const LIVE_OPERATION_STATUSES = new Set([- 'idle',- 'running',- 'waiting_for_human',- 'waiting_for_async_tool',-]);-const PENDING_RESULT_STATUSES = new Set(['pending', 'running']);const SWEEP_PAGE_SIZE = 100;@@ -154,7 +147,8 @@ const recoverRun = async (// Its verifier is still working — `settleVerifierCheckFromTerminal` owns// this row's ending, and stamping it `errored` now would discard a verdict// that is still coming.- if (verifierOp && LIVE_OPERATION_STATUSES.has(verifierOp.status)) return 'skipped';+ // A still-live verifier (parked ones included) can still produce a verdict.+ if (verifierOp && isAgentOperationInFlight(verifierOp.status)) return 'skipped';}}diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tsindex aa970e342dd..6cdad3b0af5 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -11,6 +11,7 @@ import {scanOperationFileEdits,} from '@lobechat/builtin-tools/fileEditScan';import type { WorkVersionCumulativeUsage, WorkVersionMetadata } from '@lobechat/types';+import { isAgentOperationInFlight } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -324,8 +325,8 @@ export const registerWorksForOperation = async (// spawned AFTER its parent already reached a terminal state and ran its tree// scan, so the parent will never scan again and the repair's edits would be// lost. Distinguish by the parent's status:- // - parent still active (idle / running / parked — waiting_for_human or- // waiting_for_async_tool) → it will scan the whole+ // - parent still active (idle / running / parked — waiting_for_human,+ // waiting_for_async_tool or waiting_for_client) → it will scan the whole// subtree on its own completion, so no-op here to avoid the duplicate.// - parent already terminal (done / error / interrupted) → register this// op's OWN edits (a legitimately new version for the repair), scanning@@ -334,12 +335,7 @@ export const registerWorksForOperation = async (if (completingOp.parentOperationId) {const parentOp = await operationModel.findById(completingOp.parentOperationId);const parentStatus = parentOp?.status;- const parentActive =- !parentStatus ||- parentStatus === 'idle' ||- parentStatus === 'running' ||- parentStatus === 'waiting_for_human' ||- parentStatus === 'waiting_for_async_tool';+ const parentActive = !parentStatus || isAgentOperationInFlight(parentStatus);if (parentActive) {log('[%s] Skipping file Work registration: parent operation is still active (%s)',diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e7424349caa..72bd5460bdf 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -178,6 +178,12 @@"cliRateLimitGuide.schedule.titleAfterReset": "Scheduled {{name}} to continue after the limit resets","cliRateLimitGuide.schedule.titleForApprox": "Scheduled {{name}} to continue in about {{duration}}","cliRateLimitGuide.title": "{{name}} is temporarily unavailable",+ "clientLlmWait.continue": "Continue on this device",+ "clientLlmWait.continueFailed": "Could not continue the run on this device. Try again.",+ "clientLlmWait.descElsewhere": "This run needs {{provider}}, which only your own device can reach. Open LobeHub on the device running {{provider}} and the run continues on its own. It stops waiting at {{time}}.",+ "clientLlmWait.descHere": "This run needs {{provider}}, which only your own device can reach. Continue it on this device, or it stops waiting at {{time}}.",+ "clientLlmWait.notWaiting": "This run is no longer waiting. It may have been picked up by another device, stopped, or timed out.",+ "clientLlmWait.title": "Waiting for a LobeHub client to run {{provider}}","codeBuddyInstallGuide.actions.openDocs": "Open Install Guide","codeBuddyInstallGuide.actions.openSystemTools": "Open System Tools","codeBuddyInstallGuide.afterInstall": "After installing, run CodeBuddy and use /login to sign in, then retry your message or click Re-detect in System Tools.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 1986308ac97..62f21f0a5cf 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -178,6 +178,12 @@"cliRateLimitGuide.schedule.titleAfterReset": "已安排 {{name}} 在限额重置后继续运行","cliRateLimitGuide.schedule.titleForApprox": "已安排 {{name}} 在约 {{duration}} 后继续运行","cliRateLimitGuide.title": "{{name}} 暂时不可用",+ "clientLlmWait.continue": "在此设备继续",+ "clientLlmWait.continueFailed": "未能在此设备继续这次运行,请重试。",+ "clientLlmWait.descElsewhere": "这次运行需要调用 {{provider}},它只能从你自己的设备访问。在运行 {{provider}} 的设备上打开 LobeHub 后会自动继续;{{time}} 前仍无人接手将停止等待。",+ "clientLlmWait.descHere": "这次运行需要调用 {{provider}},它只能从你自己的设备访问。可以在当前设备继续;{{time}} 前仍无人接手将停止等待。",+ "clientLlmWait.notWaiting": "这次运行已不在等待,可能已被其他设备接手、已停止或已超时。",+ "clientLlmWait.title": "正在等待能运行 {{provider}} 的 LobeHub 客户端","codeBuddyInstallGuide.actions.openDocs": "打开安装指南","codeBuddyInstallGuide.actions.openSystemTools": "打开系统工具","codeBuddyInstallGuide.afterInstall": "安装完成后,请运行 CodeBuddy 并使用 /login 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex 77d606d0724..14fdc1f7e93 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -342,6 +342,40 @@ describe('AgentStreamClient', () => {expect(client.connectionStatus).toBe('disconnected');});+ it('stays connected through a parked LLM call error, then ends on the run end', async () => {+ // The run waits for a client (`waiting_for_client`) and streams on in+ // this session once one resumes it.+ const client = createClient();+ const ws = await connectAndAuth(client);++ ws.simulateMessage({+ event: {+ data: {+ body: { reason: 'no_executor', recoverable: true },+ error: 'ClientLlmExecutorUnavailable',+ },+ operationId: 'op-123',+ stepIndex: 0,+ timestamp: 1,+ type: 'error',+ },+ type: 'agent_event',+ });+ expect(client.connectionStatus).toBe('connected');++ ws.simulateMessage({+ event: {+ data: {},+ operationId: 'op-123',+ stepIndex: 1,+ timestamp: 2,+ type: 'agent_runtime_end',+ },+ type: 'agent_event',+ });+ expect(client.connectionStatus).toBe('disconnected');+ });+it('should NOT disconnect on a forwarded terminal for a different operationId', async () => {// Single-connection WS multiplexing: a broadcast member's// agent_runtime_end is mirrored onto the supervisor's channel. It mustdiff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex be359564d74..4f5767458d1 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -1,4 +1,5 @@import { MirroredTerminalEchoGuard } from './mirroredTerminalEcho';+import { isSessionTerminalEvent } from './terminalEvent';import type {AgentStreamClientEvents,AgentStreamClientOptions,@@ -296,7 +297,7 @@ export class AgentStreamClient extends TypedEmitter {// sibling/supervisor streaming. Events with no operationId (legacy// gateway) are treated as this op's, preserving old behavior.const isOwnTerminal =- (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') &&+ isSessionTerminalEvent(agentEvent) &&(!agentEvent.operationId || agentEvent.operationId === this.operationId);if (this.resumeMode) {diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 64c5636a15b..e4fe87b29eb 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -43,7 +43,13 @@ export type {ResumeCompleteInfo,ToolResultPayload,} from './mux/types';-export { CLIENT_PROTOCOL_VERSION, LLM_RELAY_CAPABILITY, LLM_RELAY_LEASE_HEADER } from './protocol';+export {+ CLIENT_LLM_WAIT_CAPABILITY,+ CLIENT_PROTOCOL_VERSION,+ LLM_RELAY_CAPABILITY,+ LLM_RELAY_LEASE_HEADER,+} from './protocol';+export { isSessionTerminalEvent } from './terminalEvent';export type {AgentInterventionInteractionKind,AgentInterventionProvider,diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.tsindex 770855a4e46..10bf01d1ac0 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts@@ -605,6 +605,35 @@ describe('GatewayMuxClient', () => {expect(sub.active).toBe(true);});+ it('does not end on a parked LLM call error, only on the run end after it', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage({+ event: {+ data: {+ body: { reason: 'not_delivered', recoverable: true },+ error: 'ClientLlmExecutorUnavailable',+ },+ operationId: 'op-1',+ stepIndex: 0,+ timestamp: 1,+ type: 'error',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ });+ expect(sub.active).toBe(true);+ expect(onComplete).not.toHaveBeenCalled();++ ws.simulateMessage(agentEvent('op-1', '2', 'agent_runtime_end'));+ expect(sub.active).toBe(false);+ });+it('does NOT end on a mirrored member terminal for a different operationId', async () => {const { mux } = createMux();const ws = await connectAndReady(mux);diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.tsindex 49e6313ceb2..b0b540e875f 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts@@ -1,4 +1,5 @@import { MirroredTerminalEchoGuard } from '../mirroredTerminalEcho';+import { isSessionTerminalEvent } from '../terminalEvent';import type {AgentStreamEvent,AgentStreamSessionCompletion,@@ -221,7 +222,7 @@ class OperationSubscriptionImpl implements OperationSubscription {// subscription — only THIS op's terminal (or one with no operationId,// legacy gateway) is terminal here. Mirrors v1 exactly.const isOwnTerminal =- (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') &&+ isSessionTerminalEvent(agentEvent) &&(!agentEvent.operationId || agentEvent.operationId === this.operationId);this.terminalEchoGuard.observe(agentEvent);this.listeners.emit('agent_event', agentEvent);diff --git a/packages/agent-gateway-client/src/protocol.ts b/packages/agent-gateway-client/src/protocol.tsindex 7c7538cedc1..e324cfe3ca5 100644--- a/packages/agent-gateway-client/src/protocol.ts+++ b/packages/agent-gateway-client/src/protocol.ts@@ -18,5 +18,13 @@ export const CLIENT_PROTOCOL_VERSION = 2 as const;*/export const LLM_RELAY_CAPABILITY = 'llm_relay@1';+/**+ * Declared alongside {@link LLM_RELAY_CAPABILITY} by a client that keeps a run+ * open while it waits for a client (`waiting_for_client`) instead of treating+ * the parked call's error as the run's end. The server parks a run its+ * declaring client started only if that client speaks this.+ */+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';diff --git a/packages/agent-gateway-client/src/terminalEvent.test.ts b/packages/agent-gateway-client/src/terminalEvent.test.tsnew file mode 100644index 00000000000..24e95039b54--- /dev/null+++ b/packages/agent-gateway-client/src/terminalEvent.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { isSessionTerminalEvent } from './terminalEvent';++const event = (type: string, data?: unknown) =>+ ({ data, operationId: 'op-1', stepIndex: 0, timestamp: 1, type }) as any;++describe('isSessionTerminalEvent', () => {+ it('ends the session on the run end and on ordinary errors', () => {+ expect(isSessionTerminalEvent(event('agent_runtime_end'))).toBe(true);+ expect(isSessionTerminalEvent(event('error', { message: 'boom' }))).toBe(true);+ });++ it.each(['claim_timeout', 'no_executor', 'not_delivered'])(+ 'keeps the session open for a parked LLM call (%s)',+ (reason) => {+ expect(+ isSessionTerminalEvent(+ event('error', { body: { reason }, error: 'ClientLlmExecutorUnavailable' }),+ ),+ ).toBe(false);+ expect(+ isSessionTerminalEvent(+ event('error', { body: { reason }, errorType: 'ClientLlmExecutorUnavailable' }),+ ),+ ).toBe(false);+ },+ );++ it('ends the session for unavailable reasons the run does not wait on', () => {+ for (const reason of ['relay_unsupported', 'wait_timeout']) {+ expect(+ isSessionTerminalEvent(+ event('error', { body: { reason }, error: 'ClientLlmExecutorUnavailable' }),+ ),+ ).toBe(true);+ }+ });++ it('ignores non-terminal event types', () => {+ expect(isSessionTerminalEvent(event('stream_chunk'))).toBe(false);+ });+});diff --git a/packages/agent-gateway-client/src/terminalEvent.ts b/packages/agent-gateway-client/src/terminalEvent.tsnew file mode 100644index 00000000000..390fd70db05--- /dev/null+++ b/packages/agent-gateway-client/src/terminalEvent.ts@@ -0,0 +1,28 @@+import type { AgentStreamEvent } from './types';++/**+ * `ClientLlmExecutorUnavailable` reasons the server parks a run on in+ * `waiting_for_client` instead of failing it. Mirrors+ * `CLIENT_LLM_WAITABLE_REASONS` in `@lobechat/types` (this package has no deps).+ */+const CLIENT_LLM_WAITABLE_REASONS = new Set(['claim_timeout', 'no_executor', 'not_delivered']);++/**+ * Whether an agent event ends its operation's stream session. An `error` from+ * a relayed LLM call no client took does not: the run waits for a client and+ * streams on once one resumes it (or ends with `agent_runtime_end`), and the+ * error is replayed to every subscriber that joins during the wait.+ */+export const isSessionTerminalEvent = (event: AgentStreamEvent): boolean => {+ if (event.type === 'agent_runtime_end') return true;+ if (event.type !== 'error') return false;++ const data = event.data as { body?: { reason?: unknown }; error?: unknown; errorType?: unknown };+ const errorType = data?.errorType ?? data?.error;+ const reason = data?.body?.reason;+ return !(+ errorType === 'ClientLlmExecutorUnavailable' &&+ typeof reason === 'string' &&+ CLIENT_LLM_WAITABLE_REASONS.has(reason)+ );+};diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 6b2c24a1efa..2156f3d35ef 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -589,6 +589,10 @@ export class GeneralChatAgent implements Agent {): AgentInstruction {const payloadWithAllowedToolNames = {...payload,+ // A resume-seeded placeholder (tool-first resume, client-wait resume) is+ // filled by the first LLM turn whichever phase plans it.+ ...(!payload.assistantMessageId &&+ state.pendingAssistantMessageId && { assistantMessageId: state.pendingAssistantMessageId }),...this.getAllowedToolNamesPayload(),};const compressionEnabled = this.config.compressionConfig?.enabled ?? true;diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 408bc128f9b..29e12d8a772 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -2237,6 +2237,34 @@ describe('GeneralChatAgent', () => {});});+ it('fills a resume-seeded assistant placeholder and keeps the summary prompt', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState({+ messages: [{ role: 'user', content: 'Execute tasks' }] as any,+ pendingAssistantMessageId: 'msg-parked',+ });++ const context = createMockContext('sub_agents_batch_result', {+ parentMessageId: 'task-parent-msg',+ results: [],+ });++ const result = (await agent.runner(context, state)) as any;++ expect(result.type).toBe('call_llm');+ expect(result.payload.assistantMessageId).toBe('msg-parked');+ expect(result.payload.messages.at(-1)).toEqual({+ content:+ 'All tasks above have been completed. Please summarize the results or continue with your response following user query language.',+ role: 'user',+ });+ });+it('should return call_llm even when some tasks failed', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex e44bda9d4ab..d432eaf5902 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -29,7 +29,7 @@ import type {UserInterventionConfig,} from '@lobechat/types';-import type { AgentInstructionRequestHumanApprove } from './instruction';+import type { AgentInstructionRequestHumanApprove, AgentRuntimeContext } from './instruction';import type { Cost, CostLimit, Usage } from './usage';/**@@ -198,6 +198,31 @@ export interface AgentRunHostEnvelope {queue?: { retries?: number; retryDelay?: string };}+/**+ * A run parked because the LLM call of its next step can only run on the+ * user's device, and no client was there to take it (U4c). The step is+ * replayed from `resume` once a client that can execute `provider` asks to+ * continue; past `expiresAt` the run ends with an actionable error instead.+ */+export interface AgentRunClientLlmWait {+ /** The step's assistant row; the resumed call fills it instead of a new one. */+ assistantMessageId?: string;+ /**+ * The context the parked step ran with (minus per-step data), replayed on+ * resume so the call is rebuilt exactly — some phases add prompt content the+ * state does not hold. Absent on parks recorded before it existed.+ */+ context?: Pick<AgentRuntimeContext, 'initialContext' | 'metadata' | 'payload' | 'phase'>;+ expiresAt: string;+ /** Parent of the parked call's assistant row, for the replayed step. */+ parentMessageId?: string;+ /** Identifies this park, so a stale expiry check of an earlier one is a no-op. */+ parkedAt: string;+ provider: string;+ /** Why nobody executed the call (`no_executor`, `claim_timeout`, `not_delivered`). */+ reason: string;+}+/** A client's declaration that it can run relayed LLM attempts. */export interface AgentRunLlmExecutor {/** Relay protocol versions the client speaks, e.g. `llm_relay@1`. */@@ -326,6 +351,11 @@ export interface AgentState {* Current calculated cost for this session.* Updated after each billable operation.*/+ /**+ * Set while the run is parked in `waiting_for_client`: the step's LLM call+ * needs the user's device and no client was there to run it.+ */+ clientLlmWait?: AgentRunClientLlmWait;cost: Cost;/*** Optional cost limits configuration.@@ -498,6 +528,7 @@ export interface AgentState {| 'running'| 'waiting_for_human'| 'waiting_for_async_tool'+ | 'waiting_for_client'| 'done'| 'error'| 'interrupted';diff --git a/packages/agent-runtime/src/utils/status.ts b/packages/agent-runtime/src/utils/status.tsindex 771d45b4bd1..2704c2786b5 100644--- a/packages/agent-runtime/src/utils/status.ts+++ b/packages/agent-runtime/src/utils/status.ts@@ -3,13 +3,16 @@ import type { AgentState } from '../types/state';/*** Parked statuses are non-terminal, resumable pauses: the operation is still* alive but waiting on something out-of-band — human approval- * (`waiting_for_human`) or an async tool / sub-agent result- * (`waiting_for_async_tool`). They are deliberately distinct from `interrupted`+ * (`waiting_for_human`), an async tool / sub-agent result+ * (`waiting_for_async_tool`), or a client to run an LLM call only the user's+ * device can make (`waiting_for_client`). They are deliberately distinct from `interrupted`* (user cancel) and the terminal `done` / `error`, so the completion lifecycle* never stamps `completedAt` and the scheduler keeps treating them as active.*/export const isParkedStatus = (status: AgentState['status']): boolean =>- status === 'waiting_for_human' || status === 'waiting_for_async_tool';+ status === 'waiting_for_human' ||+ status === 'waiting_for_async_tool' ||+ status === 'waiting_for_client';/*** Blocked statuses halt the step loop — a parked pause or a user interrupt.diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex 85b9d6e370a..25d8148c73c 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { matchesAgentInterventionContinuationProvenance } from '@/business/server/agent-run/agentInterventionIdentity';import { getTestDB } from '../../core/getTestDB';-import { agentOperations, topics, users } from '../../schemas';+import { agentOperations, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentOperationModel } from '../agentOperation';@@ -691,6 +691,71 @@ describe('AgentOperationModel', () => {});});+ describe('client wait resume claim', () => {+ const park = async (model: AgentOperationModel, operationId: string) => {+ await model.recordStart({ operationId });+ await model.recordCompletion(operationId, {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ };++ it('claims and reverts only within the caller workspace', async () => {+ await serverDB+ .insert(workspaces)+ .values({ id: 'ws-wait', name: 'ws-wait', primaryOwnerId: userId, slug: 'ws-wait' })+ .onConflictDoNothing();+ const inWorkspace = new AgentOperationModel(serverDB, userId, 'ws-wait');+ await park(inWorkspace, 'op-wait-ws');++ const personal = new AgentOperationModel(serverDB, userId);+ expect(await personal.tryResumeFromClientWait('op-wait-ws')).toBe(false);+ expect((await inWorkspace.findById('op-wait-ws'))?.status).toBe('waiting_for_client');++ expect(await inWorkspace.tryResumeFromClientWait('op-wait-ws')).toBe(true);+ expect(await personal.revertClientWaitResume('op-wait-ws')).toBe(false);+ expect((await inWorkspace.findById('op-wait-ws'))?.status).toBe('running');++ expect(await inWorkspace.revertClientWaitResume('op-wait-ws')).toBe(true);+ expect((await inWorkspace.findById('op-wait-ws'))?.status).toBe('waiting_for_client');++ await serverDB.delete(workspaces).where(eq(workspaces.id, 'ws-wait'));+ });++ it('lists only waits for the asking client providers before the limit', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'op-wait-mine', provider: 'lmstudio' });+ await model.recordCompletion('op-wait-mine', {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ for (const id of ['op-wait-other-1', 'op-wait-other-2']) {+ await model.recordStart({ operationId: id, provider: 'ollama' });+ await model.recordCompletion(id, {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ }++ const rows = await model.listWaitingForClient({ limit: 1, providers: ['lmstudio'] });++ expect(rows.map((row) => row.id)).toEqual(['op-wait-mine']);+ });++ it('resumes a personal wait once', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await park(model, 'op-wait-personal');++ expect(await model.tryResumeFromClientWait('op-wait-personal')).toBe(true);+ expect(await model.tryResumeFromClientWait('op-wait-personal')).toBe(false);+ expect(+ await new AgentOperationModel(serverDB, otherUserId).revertClientWaitResume(+ 'op-wait-personal',+ ),+ ).toBe(false);+ });+ });+describe('claimStaleRedrive', () => {const makeStale = async (operationId: string) =>serverDBdiff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 3e03ab4e584..fa57ca16e6e 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -5,7 +5,7 @@ import {type ServerDefaultHeterogeneousRelayInvocation,type VerifyRunStatus,} from '@lobechat/types';-import { and, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';+import { and, desc, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';import { today } from '@/utils/time';@@ -245,6 +245,7 @@ export class AgentOperationModel {'running','waiting_for_human','waiting_for_async_tool',+ 'waiting_for_client',]),eq(agentOperations.status, params.status),),@@ -368,6 +369,7 @@ export class AgentOperationModel {'running','waiting_for_human','waiting_for_async_tool',+ 'waiting_for_client',]);}@@ -881,6 +883,84 @@ export class AgentOperationModel {return rows.length === 1;}+ /**+ * Atomically flip an op parked in `waiting_for_client` back to `running`.+ * True only for the single winner, so a manual "continue" racing an+ * automatic one resumes the run once.+ */+ async tryResumeFromClientWait(operationId: string): Promise<boolean> {+ const rows = await this.db+ .update(agentOperations)+ .set({ status: 'running' })+ .where(+ and(+ eq(agentOperations.id, operationId),+ this.ownership(),+ eq(agentOperations.status, 'waiting_for_client'),+ ),+ )+ .returning({ id: agentOperations.id });+ return rows.length === 1;+ }++ /**+ * Undo a won `tryResumeFromClientWait` whose resume step never got enqueued,+ * so the run stays parked (resumable, expirable, stoppable) instead of+ * sitting in `running` with nothing scheduled.+ */+ async revertClientWaitResume(operationId: string): Promise<boolean> {+ const rows = await this.db+ .update(agentOperations)+ .set({ status: 'waiting_for_client' })+ .where(+ and(+ eq(agentOperations.id, operationId),+ this.ownership(),+ eq(agentOperations.status, 'running'),+ ),+ )+ .returning({ id: agentOperations.id });+ return rows.length === 1;+ }++ /**+ * Retire an op still parked in `waiting_for_client` (its wait ran out or it+ * was stopped while waiting). Only matches the parked row, so a run a client+ * already resumed is never settled under it.+ */+ async settleClientWait(+ operationId: string,+ status: 'error' | 'interrupted' = 'error',+ ): Promise<boolean> {+ return this.settleFrom(operationId, status, ['waiting_for_client']);+ }++ /**+ * Operations of this user parked in `waiting_for_client`, newest first.+ * `providers` narrows to the ones the asking client can run before the+ * limit applies, so waits for another device's providers cannot crowd out+ * the ones it could take.+ */+ async listWaitingForClient(options: { limit?: number; providers?: string[] } = {}) {+ const { limit = 20, providers } = options;+ return this.db+ .select({+ id: agentOperations.id,+ provider: agentOperations.provider,+ topicId: agentOperations.topicId,+ })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.status, 'waiting_for_client'),+ this.ownership(),+ providers ? inArray(agentOperations.provider, providers) : undefined,+ ),+ )+ .orderBy(desc(agentOperations.createdAt))+ .limit(limit);+ }+// ============================================// Verify (delivery checker)// ============================================diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex c5a200ac431..3b25258b9e4 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -107,6 +107,7 @@ const LIVE_OPERATION_STATUSES = new Set(['running','waiting_for_human','waiting_for_async_tool',+ 'waiting_for_client',]);/** Parked states are exempt from the abandoned-age backstop — see above. */const UNBOUNDED_OPERATION_STATUSES = new Set(['waiting_for_human', 'waiting_for_async_tool']);@@ -120,6 +121,7 @@ const UNBOUNDED_OPERATION_STATUSES = new Set(['waiting_for_human', 'waiting_for_const CLIENT_UNSETTLEABLE_OPERATION_STATUSES = new Set<AgentOperationStatus>(['running','waiting_for_async_tool',+ 'waiting_for_client',]);export interface SettleRunningOperationOptions {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex edc38171550..b058446ddb8 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -856,6 +856,15 @@ export default {'messageAction.regenerate': 'Regenerate','messageAction.select': 'Select','messageLink.openInSideBrowser': 'Open in side browser',+ 'clientLlmWait.title': 'Waiting for a LobeHub client to run {{provider}}',+ 'clientLlmWait.descHere':+ 'This run needs {{provider}}, which only your own device can reach. Continue it on this device, or it stops waiting at {{time}}.',+ 'clientLlmWait.descElsewhere':+ 'This run needs {{provider}}, which only your own device can reach. Open LobeHub on the device running {{provider}} and the run continues on its own. It stops waiting at {{time}}.',+ 'clientLlmWait.continue': 'Continue on this device',+ 'clientLlmWait.notWaiting':+ 'This run is no longer waiting. It may have been picked up by another device, stopped, or timed out.',+ 'clientLlmWait.continueFailed': 'Could not continue the run on this device. Try again.','heteroRateLimit.cancelFailed':'Could not cancel the scheduled continuation. It may already be claimed or running. Refresh the conversation to check its status.','messageForward.bar.cancel': 'Cancel',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 6090ae1e0a0..bdeef4d3e2e 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -245,6 +245,52 @@ export interface ExecAgentLlmExecutor {providers: string[];}+/**+ * `ClientLlmExecutorUnavailable` reasons a client can still fix by showing up:+ * the server parks the run in `waiting_for_client` for them instead of failing+ * it (U4c), and owns what its assistant row shows.+ */+export const CLIENT_LLM_WAITABLE_REASONS: readonly string[] = [+ 'claim_timeout',+ 'no_executor',+ 'not_delivered',+];++/** Whether a (stream or persisted) error is one the server parks the run on. */+export const isClientLlmWaitableError = (error: unknown): boolean => {+ if (!error || typeof error !== 'object') return false;+ const { body, type } = error as { body?: { reason?: unknown }; type?: unknown };+ return (+ type === 'ClientLlmExecutorUnavailable' &&+ typeof body?.reason === 'string' &&+ CLIENT_LLM_WAITABLE_REASONS.includes(body.reason)+ );+};++/**+ * A run parked in `waiting_for_client`: its next LLM call needs the user's+ * device and no client took it. What a client needs to pick it up.+ */+export interface ClientLlmWaitItem {+ agentId?: string;+ /** Assistant row the resumed call fills. */+ assistantMessageId?: string;+ /** When the run stops waiting and ends with an error. */+ expiresAt: string;+ operationId: string;+ /** The provider the client must be able to reach. */+ provider: string;+ threadId?: string;+ topicId?: string;+}++/** What `resumeClientLlmWait` did; `resumed: false` once the run is no longer parked. */+export interface ResumeClientLlmWaitResult {+ assistantMessageId?: string;+ resumed: boolean;+ topicId?: string;+}+export interface ExecAgentParams {/** The agent ID to run (either agentId or slug is required) */agentId?: string;diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.tsindex cc612e798ea..2fdcbb6b0dc 100644--- a/packages/types/src/agentOperation.ts+++ b/packages/types/src/agentOperation.ts@@ -6,12 +6,14 @@ export type AgentOperationStatus =| 'interrupted'| 'running'| 'waiting_for_async_tool'+ | 'waiting_for_client'| 'waiting_for_human';const IN_FLIGHT_OPERATION_STATUSES = new Set<AgentOperationStatus>(['idle','running','waiting_for_async_tool',+ 'waiting_for_client','waiting_for_human',]);@@ -32,4 +34,5 @@ export type AgentOperationCompletionReason =/** The same tool call was requested over and over; a guard cut the run short. */| 'tool_call_repeat_limit'| 'waiting_for_async_tool'+ | 'waiting_for_client'| 'waiting_for_human';diff --git a/src/features/Conversation/Error/ClientLlmWaitingCard.tsx b/src/features/Conversation/Error/ClientLlmWaitingCard.tsxnew file mode 100644index 00000000000..f7d34edfab9--- /dev/null+++ b/src/features/Conversation/Error/ClientLlmWaitingCard.tsx@@ -0,0 +1,110 @@+import { Icon } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';+import dayjs from 'dayjs';+import { MonitorSmartphone } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useProviderName } from '@/hooks/useProviderName';+import { getLlmExecutorDeclarationFor } from '@/services/llmRelay';+import { useChatStore } from '@/store/chat';++import { dataSelectors, useConversationStore } from '../store';+import BaseErrorForm from './BaseErrorForm';++/**+ * Parks this client already tried to pick up on its own, so a pick-up that+ * parks again (the call went out before the socket counted) leaves the rest to+ * the user's click instead of looping.+ */+const autoContinued = new Set<string>();++interface ClientLlmWaitingCardProps {+ expiresAt?: string;+ id: string;+ provider: string;+}++const ClientLlmWaitingCard = memo<ClientLlmWaitingCardProps>(({ expiresAt, id, provider }) => {+ const { t } = useTranslation('chat');+ const providerName = useProviderName(provider);+ const context = useConversationStore((s) => s.context);+ const operationId = useConversationStore(+ (s) => dataSelectors.getDbMessageById(id)(s)?.metadata?.operationId,+ );+ const updateMessageError = useConversationStore((s) => s.updateMessageError);+ const [loading, setLoading] = useState(false);++ // Only a client that declares it can run the provider may take the call.+ const canContinueHere = !!operationId && !!getLlmExecutorDeclarationFor(provider);++ const continueHere = useCallback(+ async (automatic: boolean) => {+ if (!operationId) return;+ setLoading(true);+ try {+ const resumed = await useChatStore.getState().continueClientLlmWait({+ agentId: context.agentId,+ assistantMessageId: id,+ operationId,+ provider,+ threadId: context.threadId,+ topicId: context.topicId ?? undefined,+ });+ if (resumed) {+ await updateMessageError(id, null);+ } else if (!automatic) {+ toast.info(t('clientLlmWait.notWaiting'));+ }+ } catch (error) {+ console.error('[ClientLlmWaitingCard] Failed to continue the run:', error);+ if (!automatic) toast.error(t('clientLlmWait.continueFailed'));+ } finally {+ setLoading(false);+ }+ },+ [+ context.agentId,+ context.threadId,+ context.topicId,+ id,+ operationId,+ provider,+ t,+ updateMessageError,+ ],+ );++ // This client coming online is what the run waits for: pick it up once.+ useEffect(() => {+ if (!canContinueHere || !operationId) return;+ const key = `${operationId}:${expiresAt ?? ''}`;+ if (autoContinued.has(key)) return;+ autoContinued.add(key);+ void continueHere(true);+ }, [canContinueHere, continueHere, expiresAt, operationId]);++ const time = expiresAt ? dayjs(expiresAt).format('HH:mm') : '';++ return (+ <BaseErrorForm+ avatar={<Icon icon={MonitorSmartphone} size={24} />}+ title={t('clientLlmWait.title', { provider: providerName })}+ action={+ canContinueHere ? (+ <Button loading={loading} type={'primary'} onClick={() => void continueHere(false)}>+ {t('clientLlmWait.continue')}+ </Button>+ ) : undefined+ }+ desc={t(canContinueHere ? 'clientLlmWait.descHere' : 'clientLlmWait.descElsewhere', {+ provider: providerName,+ time,+ })}+ />+ );+});++ClientLlmWaitingCard.displayName = 'ClientLlmWaitingCard';++export default ClientLlmWaitingCard;diff --git a/src/features/Conversation/Error/clientLlmWait.test.ts b/src/features/Conversation/Error/clientLlmWait.test.tsnew file mode 100644index 00000000000..cdd3b1626a0--- /dev/null+++ b/src/features/Conversation/Error/clientLlmWait.test.ts@@ -0,0 +1,42 @@+import { AgentRuntimeErrorType } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { readClientLlmWait } from './clientLlmWait';++describe('readClientLlmWait', () => {+ it('reads a waiting_for_client notice off the assistant row', () => {+ expect(+ readClientLlmWait({+ body: {+ expiresAt: '2026-10-04T08:10:00.000Z',+ provider: 'lmstudio',+ waitingForClient: true,+ },+ message: 'Waiting',+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ }),+ ).toEqual({+ expiresAt: '2026-10-04T08:10:00.000Z',+ provider: 'lmstudio',+ waitingForClient: true,+ });+ });++ it('leaves a final unavailable error (the wait ran out) to the regular error card', () => {+ expect(+ readClientLlmWait({+ body: { provider: 'lmstudio', reason: 'wait_timeout' },+ message: 'No client',+ type: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,+ }),+ ).toBeUndefined();+ expect(+ readClientLlmWait({+ body: { provider: 'lmstudio', waitingForClient: true },+ message: 'other',+ type: AgentRuntimeErrorType.ProviderBizError,+ }),+ ).toBeUndefined();+ expect(readClientLlmWait(null)).toBeUndefined();+ });+});diff --git a/src/features/Conversation/Error/clientLlmWait.ts b/src/features/Conversation/Error/clientLlmWait.tsnew file mode 100644index 00000000000..2917ca1b358--- /dev/null+++ b/src/features/Conversation/Error/clientLlmWait.ts@@ -0,0 +1,21 @@+import type { ChatMessageError } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';++export interface ClientLlmWaitBody {+ expiresAt?: string;+ provider: string;+ waitingForClient: true;+}++/**+ * The assistant row of a run parked in `waiting_for_client`: the server could+ * not find a client to run an LLM call only the user's device can reach.+ */+export const readClientLlmWait = (+ error: ChatMessageError | null | undefined,+): ClientLlmWaitBody | undefined => {+ if (error?.type !== AgentRuntimeErrorType.ClientLlmExecutorUnavailable) return;+ const body = error.body as Partial<ClientLlmWaitBody> | undefined;+ if (body?.waitingForClient !== true || typeof body.provider !== 'string') return;+ return body as ClientLlmWaitBody;+};diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 8905c1dce68..f5c1577671e 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -35,6 +35,7 @@ import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfiimport { getRuntimeErrorMessage } from '@/utils/locale/runtimeErrorMessage';import ChatInvalidAPIKey from './ChatInvalidApiKey';+import { readClientLlmWait } from './clientLlmWait';import { type DedicatedErrorCardType, isDedicatedErrorCardType } from './dedicatedErrorCards';import { isHeterogeneousAgentStatusGuideError } from './heterogeneous';import { useHeterogeneousAutoRetry } from './useHeterogeneousAutoRetry';@@ -117,6 +118,11 @@ const QuotaLimitError = dynamic(() => import('./QuotaLimitError'), { loading, ssconst TraceIdError = dynamic(() => import('./TraceIdError'), { loading, ssr: false });+const ClientLlmWaitingCard = dynamic(() => import('./ClientLlmWaitingCard'), {+ loading,+ ssr: false,+});+// `UnknownChatFetchError` is excluded: its localized copy is a generic// "unknown error" message, so the trace-id report UI is strictly more useful.const LEGACY_LOCALIZED_ERROR_TYPES = new Set<string>(@@ -469,6 +475,19 @@ const ErrorMessageExtra = memo<ErrorExtraProps>();}+ // A run parked in `waiting_for_client` is still alive: show what it waits+ // for and let this device take it, not a final error.+ const clientLlmWait = readClientLlmWait(error);+ if (clientLlmWait) {+ return (+ <ClientLlmWaitingCard+ expiresAt={clientLlmWait.expiresAt}+ id={data.id}+ provider={clientLlmWait.provider}+ />+ );+ }+if (enableBusinessFeatures && businessChatErrorMessageExtra)return businessChatErrorMessageExtra;diff --git a/src/hooks/useClientLlmWaitResume.test.ts b/src/hooks/useClientLlmWaitResume.test.tsnew file mode 100644index 00000000000..edccfd69d65--- /dev/null+++ b/src/hooks/useClientLlmWaitResume.test.ts@@ -0,0 +1,115 @@+import { renderHook } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ CLIENT_LLM_WAIT_POLL_MAX_MS,+ CLIENT_LLM_WAIT_POLL_MIN_MS,+ clientLlmWaitPollInterval,+ useClientLlmWaitResume,+} from './useClientLlmWaitResume';++const listClientLlmWaits = vi.fn();+const continueClientLlmWait = vi.fn();++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { listClientLlmWaits: (providers?: string[]) => listClientLlmWaits(providers) },+}));+vi.mock('@/services/llmRelay', () => ({+ buildLlmExecutorDeclaration: () => ({ clientId: 'tab-a', providers: ['lmstudio'] }),+ getLlmExecutorDeclarationFor: (provider: string) =>+ provider === 'lmstudio' ? { clientId: 'tab-a', providers: ['lmstudio'] } : undefined,+}));+vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => ({ continueClientLlmWait }) },+}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: any) => selector({ isSignedIn: true, isUserStateInit: true }),+}));+vi.mock('@/store/serverConfig', () => ({+ useServerConfigStore: (selector: any) =>+ selector({+ featureFlags: { enableLlmRelay: true },+ serverConfig: { agentGatewayUrl: 'wss://gateway' },+ }),+}));+vi.mock('@/store/aiInfra', () => ({+ useAiInfraStore: (selector: any) => selector({ enabledAiProviders: [{ id: 'lmstudio' }] }),+}));++const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++const flush = async () => {+ for (let i = 0; i < 5; i++) await Promise.resolve();+};++describe('useClientLlmWaitResume', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ listClientLlmWaits.mockReset();+ continueClientLlmWait.mockReset().mockResolvedValue(undefined);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('picks up a run that parks after this client opened the app', async () => {+ const parked = { operationId: 'op-1', provider: 'lmstudio', topicId: 'tpc-1' };+ listClientLlmWaits.mockResolvedValueOnce([]).mockResolvedValue([parked]);++ renderHook(() => useClientLlmWaitResume(), { wrapper });+ await vi.advanceTimersByTimeAsync(0);+ await flush();+ expect(listClientLlmWaits).toHaveBeenCalledTimes(1);+ expect(continueClientLlmWait).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(CLIENT_LLM_WAIT_POLL_MIN_MS);+ await flush();++ expect(listClientLlmWaits).toHaveBeenCalledTimes(2);+ // Only the providers this client can run, so the server limit applies after.+ expect(listClientLlmWaits).toHaveBeenLastCalledWith(['lmstudio']);+ expect(continueClientLlmWait).toHaveBeenCalledWith(parked);+ });++ it('keeps polling after a failed list, so a later wait is still picked up', async () => {+ const parked = { operationId: 'op-3', provider: 'lmstudio', topicId: 'tpc-3' };+ vi.spyOn(console, 'error').mockImplementation(() => {});+ listClientLlmWaits.mockRejectedValueOnce(new Error('502')).mockResolvedValue([parked]);++ renderHook(() => useClientLlmWaitResume(), { wrapper });+ await vi.advanceTimersByTimeAsync(0);+ await flush();+ expect(listClientLlmWaits).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(CLIENT_LLM_WAIT_POLL_MIN_MS);+ await flush();++ expect(listClientLlmWaits).toHaveBeenCalledTimes(2);+ expect(continueClientLlmWait).toHaveBeenCalledWith(parked);+ });++ it('leaves runs for providers this client cannot reach', async () => {+ listClientLlmWaits.mockResolvedValue([+ { operationId: 'op-2', provider: 'ollama', topicId: 'tpc-2' },+ ]);++ renderHook(() => useClientLlmWaitResume(), { wrapper });+ await vi.advanceTimersByTimeAsync(0);+ await flush();++ expect(continueClientLlmWait).not.toHaveBeenCalled();+ });+});++describe('clientLlmWaitPollInterval', () => {+ it('backs off while nothing waits, capped well inside the wait window', () => {+ expect(clientLlmWaitPollInterval(0)).toBe(CLIENT_LLM_WAIT_POLL_MIN_MS);+ expect(clientLlmWaitPollInterval(1)).toBe(CLIENT_LLM_WAIT_POLL_MIN_MS * 2);+ expect(clientLlmWaitPollInterval(10)).toBe(CLIENT_LLM_WAIT_POLL_MAX_MS);+ expect(clientLlmWaitPollInterval(-1)).toBe(CLIENT_LLM_WAIT_POLL_MIN_MS);+ });+});diff --git a/src/hooks/useClientLlmWaitResume.ts b/src/hooks/useClientLlmWaitResume.tsnew file mode 100644index 00000000000..cd3e289b57b--- /dev/null+++ b/src/hooks/useClientLlmWaitResume.ts@@ -0,0 +1,73 @@+import { useRef } from 'react';+import useSWR from 'swr';++import { gatewayKeys } from '@/libs/swr/keys';+import { aiAgentService } from '@/services/aiAgent';+import { buildLlmExecutorDeclaration, getLlmExecutorDeclarationFor } from '@/services/llmRelay';+import { useAiInfraStore } from '@/store/aiInfra';+import { useChatStore } from '@/store/chat';+import { useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';++/**+ * Pick up runs parked in `waiting_for_client` when this client comes online+ * (U4c): a schedule, a bot or a CLI run whose next LLM call needs a provider+ * only the user's device can reach, started while no LobeHub client was open.+ * Checked on entry, after the provider list this client can run is known, then+ * polled while the app stays open — a run can park long after this client+ * started. The poll backs off while nothing is waiting (30 s up to 2 min, well+ * inside the 10 min wait window) and resets once a wait shows up. Runs for+ * providers this client cannot reach are left for another device.+ */+export const CLIENT_LLM_WAIT_POLL_MIN_MS = 30_000;+export const CLIENT_LLM_WAIT_POLL_MAX_MS = 120_000;++/** Next poll delay after `idlePolls` consecutive polls that found nothing. */+export const clientLlmWaitPollInterval = (idlePolls: number) =>+ Math.min(CLIENT_LLM_WAIT_POLL_MIN_MS * 2 ** Math.max(idlePolls, 0), CLIENT_LLM_WAIT_POLL_MAX_MS);++export const useClientLlmWaitResume = (): void => {+ const idlePollsRef = useRef(0);+ const isReady = useUserStore((s) => s.isUserStateInit && !!s.isSignedIn);+ const relayEnabled = useServerConfigStore((s) => !!s.featureFlags.enableLlmRelay);+ const agentGatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);+ const providersReady = useAiInfraStore((s) => (s.enabledAiProviders?.length ?? 0) > 0);++ useSWR(+ isReady && relayEnabled && agentGatewayUrl && providersReady+ ? gatewayKeys.clientLlmWaits()+ : null,+ async () => {+ const providers = buildLlmExecutorDeclaration()?.providers ?? [];+ let listed: Awaited<ReturnType<typeof aiAgentService.listClientLlmWaits>>;+ try {+ listed = await aiAgentService.listClientLlmWaits(providers);+ } catch (error) {+ // Never surface it to SWR: an errored key stops its interval, and with+ // retries off nothing would poll again. Count it as an idle poll.+ console.error('[useClientLlmWaitResume] Failed to list waiting runs:', error);+ idlePollsRef.current += 1;+ return 0;+ }+ const waits = listed.filter((wait) => !!getLlmExecutorDeclarationFor(wait.provider));++ // One at a time: each pick-up subscribes to its run's stream first.+ for (const wait of waits) {+ try {+ await useChatStore.getState().continueClientLlmWait(wait);+ } catch (error) {+ console.error('[useClientLlmWaitResume] Failed to continue %s:', wait.operationId, error);+ }+ }+ idlePollsRef.current = waits.length > 0 ? 0 : idlePollsRef.current + 1;+ return waits.length;+ },+ {+ refreshInterval: () => clientLlmWaitPollInterval(idlePollsRef.current - 1),+ revalidateIfStale: false,+ revalidateOnFocus: false,+ revalidateOnReconnect: true,+ shouldRetryOnError: false,+ },+ );+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 99d9209eb1b..a8295908257 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1461,6 +1461,7 @@ export const openInAppKeys = {detect: def('openInApp:detect', () => ['openInApp:detect']),};export const gatewayKeys = {+ clientLlmWaits: def('gateway:clientLlmWaits', () => ['gateway:clientLlmWaits']),reconnect: def('gateway:reconnect', (operationId: string) => ['gateway:reconnect', operationId]),};export const userKeys = {diff --git a/src/routes/(main)/_layout/ClientLlmWaitResume.tsx b/src/routes/(main)/_layout/ClientLlmWaitResume.tsxnew file mode 100644index 00000000000..d6cfdb08ac8--- /dev/null+++ b/src/routes/(main)/_layout/ClientLlmWaitResume.tsx@@ -0,0 +1,13 @@+import { memo } from 'react';++import { useClientLlmWaitResume } from '@/hooks/useClientLlmWaitResume';++/** Render-less: continues runs that wait for this client to run a local model. */+const ClientLlmWaitResume = memo(() => {+ useClientLlmWaitResume();+ return null;+});++ClientLlmWaitResume.displayName = 'ClientLlmWaitResume';++export default ClientLlmWaitResume;diff --git a/src/routes/(main)/_layout/authMount.test.ts b/src/routes/(main)/_layout/authMount.test.tsindex 26f18cb64fb..43c96b8fc54 100644--- a/src/routes/(main)/_layout/authMount.test.ts+++ b/src/routes/(main)/_layout/authMount.test.ts@@ -45,6 +45,7 @@ vi.mock('@/features/HotkeyHelperPanel', nullComponent);vi.mock('@/features/NavPanel/Shell', nullComponent);vi.mock('@/layout/GlobalProvider/CmdkLazy', nullComponent);vi.mock('./GatewayMuxWarmup', nullComponent);+vi.mock('./ClientLlmWaitResume', nullComponent);vi.mock('./RegisterHotkeys', nullComponent);vi.mock('../home', nullComponent);vi.mock('../home/_layout', passthrough);diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex 0269fb5d281..f5444efc88a 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -36,6 +36,7 @@ import CmdkLazy from '@/layout/GlobalProvider/CmdkLazy';import dynamic from '@/libs/next/dynamic';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';+import ClientLlmWaitResume from './ClientLlmWaitResume';import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';import GatewayMuxWarmup from './GatewayMuxWarmup';import RegisterHotkeys from './RegisterHotkeys';@@ -94,6 +95,7 @@ const Layout: FC = () => {<Suspense fallback={null}><HotkeyHelperPanel /><GatewayMuxWarmup />+ <ClientLlmWaitResume /><HeteroRestartRecovery /><RegisterHotkeys /><CmdkLazy />diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex 81a409800b9..3fe2dd438be 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -25,6 +25,7 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfiimport DesktopHome from '../home';import DesktopHomeLayout from '../home/_layout';+import ClientLlmWaitResume from './ClientLlmWaitResume';import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';import GatewayMuxWarmup from './GatewayMuxWarmup';import RegisterHotkeys from './RegisterHotkeys';@@ -68,6 +69,7 @@ const Layout: FC = () => {<Suspense fallback={null}><HotkeyHelperPanel /><GatewayMuxWarmup />+ <ClientLlmWaitResume /><RegisterHotkeys /><CmdkLazy /><GlobalApprovalNotification />diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex e5ca22239d7..534f4617800 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -1,8 +1,11 @@import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';import type {+ ClientLlmWaitItem,ExecAgentAppContext,+ ExecAgentLlmExecutor,ExecAgentResult,+ ResumeClientLlmWaitResult,RuntimeMentionedAgent,ScheduleAgentRunParams,ScheduleAgentRunResult,@@ -347,6 +350,22 @@ class AiAgentService {return await lambdaClient.aiAgent.interruptTask.mutate(params);}+ /** Runs parked in `waiting_for_client`, waiting for a client to run their LLM call. */+ /** Runs parked for a client, narrowed to `providers` (the ones this client can run). */+ async listClientLlmWaits(providers?: string[]): Promise<ClientLlmWaitItem[]> {+ return await lambdaClient.aiAgent.listClientLlmWaits.query(+ providers ? { providers } : undefined,+ );+ }++ /** Continue a run parked in `waiting_for_client`, with this client as its executor. */+ async resumeClientLlmWait(params: {+ llmExecutor: ExecAgentLlmExecutor;+ operationId: string;+ }): Promise<ResumeClientLlmWaitResult> {+ return await lambdaClient.aiAgent.resumeClientLlmWait.mutate(params);+ }+/*** Tell a running server operation whether user messages are queued behind it,* so it hands the turn back at its next step boundary.diff --git a/src/services/llmRelay/index.test.ts b/src/services/llmRelay/index.test.tsindex f26b6eaa991..c7ad88f5e84 100644--- a/src/services/llmRelay/index.test.ts+++ b/src/services/llmRelay/index.test.ts@@ -26,7 +26,7 @@ describe('buildLlmExecutorDeclaration', () => {it('declares the providers of the runtime state a chat page has loaded', () => {expect(buildLlmExecutorDeclaration()).toEqual({- capabilities: ['llm_relay@1'],+ capabilities: ['llm_relay@1', 'llm_client_wait@1'],clientId: 'tab-1',providers: ['lmstudio', 'ollama'],});diff --git a/src/services/llmRelay/index.ts b/src/services/llmRelay/index.tsindex d017740d082..125484720e9 100644--- a/src/services/llmRelay/index.ts+++ b/src/services/llmRelay/index.ts@@ -1,4 +1,4 @@-import { LLM_RELAY_CAPABILITY } from '@lobechat/agent-gateway-client';+import { CLIENT_LLM_WAIT_CAPABILITY, LLM_RELAY_CAPABILITY } from '@lobechat/agent-gateway-client';import type { ExecAgentLlmExecutor } from '@lobechat/types';import { initializeWithClientStore } from '@/services/chat/mecha/clientModelRuntime';@@ -44,8 +44,20 @@ export const buildLlmExecutorDeclaration = (): ExecAgentLlmExecutor | undefined.slice(0, 256);return {- capabilities: [LLM_RELAY_CAPABILITY],+ capabilities: [LLM_RELAY_CAPABILITY, CLIENT_LLM_WAIT_CAPABILITY],clientId: getLlmRelayClientId(),providers,};};++/**+ * This client's executor declaration when it covers `provider`, i.e. it can+ * pick up a run parked in `waiting_for_client` for that provider.+ */+export const getLlmExecutorDeclarationFor = (+ provider: string | undefined,+): ExecAgentLlmExecutor | undefined => {+ if (!provider) return;+ const declaration = buildLlmExecutorDeclaration();+ return declaration?.providers.includes(provider) ? declaration : undefined;+};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.clientLlmWait.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.clientLlmWait.test.tsnew file mode 100644index 00000000000..ff6c32b8c2f--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.clientLlmWait.test.ts@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentService } from '@/services/aiAgent';+import { getLlmExecutorDeclarationFor } from '@/services/llmRelay';++import { GatewayActionImpl } from '../transports/gateway/gateway';++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { resumeClientLlmWait: vi.fn() },+}));++vi.mock('@/services/llmRelay', () => ({+ getLlmExecutorDeclarationFor: vi.fn(),+ getLlmRelayClientId: () => 'tab-b',+}));++const declaration = { capabilities: ['llm_relay@1'], clientId: 'tab-b', providers: ['lmstudio'] };++const params = {+ agentId: 'agt-1',+ assistantMessageId: 'msg-assistant',+ operationId: 'op-1',+ provider: 'lmstudio',+ topicId: 'tpc-1',+};++const createAction = (status?: string) => {+ const state: any = {+ gatewayConnections: status ? { 'op-1': { status } } : {},+ internal_dispatchMessage: vi.fn(),+ };+ const action = new GatewayActionImpl(vi.fn(), () => state);+ const reconnect = vi.fn(async () => {+ state.gatewayConnections['op-1'] = { status: 'connected' };+ });+ (action as any).reconnectToGatewayOperation = reconnect;+ return { action, reconnect, state };+};++describe('continueClientLlmWait', () => {+ beforeEach(() => {+ vi.mocked(aiAgentService.resumeClientLlmWait).mockClear();+ vi.mocked(getLlmExecutorDeclarationFor).mockReturnValue(declaration);+ vi.mocked(aiAgentService.resumeClientLlmWait).mockResolvedValue({ resumed: true });+ });++ it('subscribes to the run first, then resumes it with this client as the executor', async () => {+ const { action, reconnect } = createAction();++ await expect(action.continueClientLlmWait(params)).resolves.toBe(true);++ expect(reconnect).toHaveBeenCalledWith(+ expect.objectContaining({ assistantMessageId: 'msg-assistant', operationId: 'op-1' }),+ );+ expect(aiAgentService.resumeClientLlmWait).toHaveBeenCalledWith({+ llmExecutor: declaration,+ operationId: 'op-1',+ });+ expect(reconnect.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(aiAgentService.resumeClientLlmWait).mock.invocationCallOrder[0],+ );+ });++ it('drops the local waiting notice whichever caller wins the resume', async () => {+ const { action, state } = createAction('connected');++ await action.continueClientLlmWait(params);++ expect(state.internal_dispatchMessage).toHaveBeenCalledWith(+ { id: 'msg-assistant', type: 'updateMessage', value: { error: null } },+ { conversationContext: { agentId: 'agt-1', threadId: undefined, topicId: 'tpc-1' } },+ );+ });++ it('keeps the local notice when another caller already resumed the run', async () => {+ vi.mocked(aiAgentService.resumeClientLlmWait).mockResolvedValueOnce({ resumed: false });+ const { action, state } = createAction('connected');++ await expect(action.continueClientLlmWait(params)).resolves.toBe(false);++ expect(state.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('reuses a stream this tab is already subscribed to', async () => {+ const { action, reconnect } = createAction('connected');++ await action.continueClientLlmWait(params);++ expect(reconnect).not.toHaveBeenCalled();+ expect(aiAgentService.resumeClientLlmWait).toHaveBeenCalled();+ });++ it('does not claim the wait while the gateway socket never connects', async () => {+ vi.useFakeTimers();+ try {+ // The socket stays handshaking and never reaches `connected`.+ const { action } = createAction('connecting');++ const pending = action.continueClientLlmWait(params);+ await vi.advanceTimersByTimeAsync(10_000);++ await expect(pending).resolves.toBe(false);+ expect(aiAgentService.resumeClientLlmWait).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves the run alone when this client cannot reach the provider', async () => {+ vi.mocked(getLlmExecutorDeclarationFor).mockReturnValue(undefined);+ const { action, reconnect } = createAction();++ await expect(action.continueClientLlmWait(params)).resolves.toBe(false);++ expect(reconnect).not.toHaveBeenCalled();+ expect(aiAgentService.resumeClientLlmWait).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 7697171fb34..f3df7252797 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -3289,6 +3289,25 @@ describe('GatewayActionImpl', () => {);});+ it('shares one attempt between concurrent reconnects to the same run', async () => {+ const { action, startOperation } = createReconnectTestAction({ id: 'ast-1' });+ const params = {+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ };++ // E.g. the topic's own reconnect and a waiting_for_client card, both+ // before the token refresh lands.+ await Promise.all([+ action.reconnectToGatewayOperation(params),+ action.reconnectToGatewayOperation(params),+ ]);++ expect(startOperation).toHaveBeenCalledTimes(1);+ expect(aiAgentService.refreshGatewayToken).toHaveBeenCalledTimes(1);+ });+it('omits startTime when createdAt is not a parseable date', async () => {const { action, startOperation } = createReconnectTestAction({createdAt: 'not-a-date',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.tsindex 77a0bba4ee2..7a6b6b7c339 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts@@ -1428,6 +1428,51 @@ describe('createGatewayEventHandler', () => {expect(store.markTopicUnread).not.toHaveBeenCalled();});+ it.each(['no_executor', 'claim_timeout', 'not_delivered'])(+ 'leaves a relay call no client took (%s) to the server: no failure, no row write',+ async (reason) => {+ const store = createMockStore();+ const handler = createHandler(store);++ // What a replay on reconnect delivers long after the run parked.+ handler(+ makeEvent('error', {+ error: { reason, recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'lmstudio',+ }),+ );+ await flush();++ expect(store.failOperation).not.toHaveBeenCalled();+ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(messageService.updateMessageError).not.toHaveBeenCalled();+ expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({ value: expect.objectContaining({ error: expect.anything() }) }),+ expect.anything(),+ );+ // It shows what the server wrote instead (the waiting notice).+ expect(messageService.getMessages).toHaveBeenCalled();+ },+ );++ it('still fails the run on a relay error no client can fix (wait_timeout)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ error: { reason: 'wait_timeout', recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'lmstudio',+ }),+ );+ await flush();++ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(messageService.updateMessageError).toHaveBeenCalled();+ });+it('error event preserves runtime payload errorType and budget context', async () => {const store = createMockStore();const handler = createHandler(store);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 7102eddcd1e..c6e85f14fb2 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -6,6 +6,7 @@ import {type ConnectionStatus,createOperationClient,type GatewayMuxClient,+ isSessionTerminalEvent,type MuxOpLifecycleMessage,type OperationClient,type OperationClientOptions,@@ -43,7 +44,7 @@ import {type ResumeToolResultParam,} from '@/services/aiAgent';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';-import { getLlmRelayClientId } from '@/services/llmRelay';+import { getLlmExecutorDeclarationFor, getLlmRelayClientId } from '@/services/llmRelay';import { messageService } from '@/services/message';import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';@@ -323,6 +324,38 @@ const isSuccessfulGatewayCompletion = (params: {// ─── Action Implementation ───+interface ReconnectToGatewayOperationParams {+ /**+ * Agent that owns the rendered conversation. Callers outside the agent route+ * (task detail / home run drawer) MUST pass it: `activeAgentId` is whatever+ * the last agent page left behind — `undefined` on the home surface — and the+ * streamed messages would land in a `main_undefined_<topicId>` bucket nobody+ * renders, leaving a connected-but-frozen panel.+ */+ agentId?: string;+ /**+ * Present on the agent-share visitor surface. Routes the token refresh and+ * cancellation through the share-authorized `shareChat` procedures instead+ * of the owner-scoped ones: a visitor has no owner-scoped access to the+ * creator's topic/operation rows, and the Gateway channel is registered+ * under the VISITOR's id, so only a visitor-signed token can reconnect it+ * — see `shareChat.refreshGatewayToken`'s JSDoc.+ */+ agentShareId?: string;+ assistantMessageId: string;+ heteroType?: string | null;+ operationId: string;+ scope?: string;+ /**+ * Server-written ISO timestamp of when the run claimed the topic — carried+ * on the topic's `runningOperation` marker so elapsed-time anchors survive+ * a page refresh even when the messages list hasn't loaded yet.+ */+ startedAt?: string;+ threadId?: string | null;+ topicId: string;+}+export class GatewayActionImpl {readonly #get: () => ChatStore;readonly #set: Setter;@@ -358,6 +391,9 @@ export class GatewayActionImpl {*/readonly #muxFallbacks = new Map<string, { mux: GatewayMuxClient; redial: () => void }>();+ /** Reconnects still being established, by server operation id. */+ readonly #reconnectsInFlight = new Map<string, Promise<void>>();+constructor(set: Setter, get: () => ChatStore, _api?: unknown) {void _api;this.#set = set;@@ -580,7 +616,9 @@ export class GatewayActionImpl {// treat as this op's to preserve prior behavior).client.on('agent_event', (event) => {const isOwnOp = !event.operationId || event.operationId === operationId;- if (isOwnOp && (event.type === 'agent_runtime_end' || event.type === 'error')) {+ // Same rule the transport ends the session by: a parked LLM call's error+ // is not the run's end.+ if (isOwnOp && isSessionTerminalEvent(event)) {receivedTerminalEvent = true;}// Only a clean completion counts as success — a cancel ('interrupted') or@@ -1520,41 +1558,85 @@ export class GatewayActionImpl {};/**- * Reconnect to an existing Gateway operation after page reload.- * Reads runningOperation from topic metadata, refreshes the JWT token,- * and establishes a new WebSocket connection with event replay.+ * Pick up a run parked in `waiting_for_client` on this client: its next LLM+ * call needs a provider only the user's device can reach, and no client was+ * there to run it. The replayed call is delivered only to clients subscribed+ * to the run's stream, so subscribe first (unless this tab already is), then+ * ask the server to continue with this client as the executor.+ *+ * Resolves `false` when this client cannot run the provider or the run is no+ * longer parked (another client already took it, it expired or was stopped).*/- reconnectToGatewayOperation = async (params: {- /**- * Agent that owns the rendered conversation. Callers outside the agent route- * (task detail / home run drawer) MUST pass it: `activeAgentId` is whatever- * the last agent page left behind — `undefined` on the home surface — and the- * streamed messages would land in a `main_undefined_<topicId>` bucket nobody- * renders, leaving a connected-but-frozen panel.- */+ continueClientLlmWait = async (params: {agentId?: string;- /**- * Present on the agent-share visitor surface. Routes the token refresh and- * cancellation through the share-authorized `shareChat` procedures instead- * of the owner-scoped ones: a visitor has no owner-scoped access to the- * creator's topic/operation rows, and the Gateway channel is registered- * under the VISITOR's id, so only a visitor-signed token can reconnect it- * — see `shareChat.refreshGatewayToken`'s JSDoc.- */- agentShareId?: string;- assistantMessageId: string;- heteroType?: string | null;+ assistantMessageId?: string;operationId: string;- scope?: string;- /**- * Server-written ISO timestamp of when the run claimed the topic — carried- * on the topic's `runningOperation` marker so elapsed-time anchors survive- * a page refresh even when the messages list hasn't loaded yet.- */- startedAt?: string;+ provider: string;threadId?: string | null;- topicId: string;- }): Promise<void> => {+ topicId?: string;+ }): Promise<boolean> => {+ const { agentId, assistantMessageId, operationId, provider, threadId, topicId } = params;+ const llmExecutor = getLlmExecutorDeclarationFor(provider);+ if (!llmExecutor) return false;++ const isConnected = () => {+ const status = this.#get().gatewayConnections[operationId]?.status;+ return !!status && status !== 'disconnected';+ };+ if (!isConnected() && assistantMessageId && topicId) {+ await this.reconnectToGatewayOperation({+ agentId,+ assistantMessageId,+ operationId,+ threadId,+ topicId,+ });+ }+ // A socket still handshaking when the call goes out is not counted as a+ // recipient: claiming the wait then only re-parks the run. Leave it parked+ // for a later attempt (or another client) instead.+ const connected = await waitForGatewayConnected(+ () => this.#get().gatewayConnections[operationId]?.status,+ );+ if (!connected) return false;++ const { resumed } = await aiAgentService.resumeClientLlmWait({ llmExecutor, operationId });+ // Whichever caller won (the conversation's card or the app-level pick-up),+ // drop the waiting notice locally: the resumed step streams into this row+ // and the server already cleared it.+ if (resumed && assistantMessageId && agentId && topicId) {+ this.#get().internal_dispatchMessage(+ { id: assistantMessageId, type: 'updateMessage', value: { error: null } },+ { conversationContext: { agentId, threadId, topicId } },+ );+ }+ return resumed;+ };++ /**+ * Reconnect to an existing Gateway operation after page reload.+ * Reads runningOperation from topic metadata, refreshes the JWT token,+ * and establishes a new WebSocket connection with event replay.+ */+ reconnectToGatewayOperation = (params: ReconnectToGatewayOperationParams): Promise<void> => {+ // Several surfaces ask for the same run's stream at once (the topic's own+ // reconnect, a `waiting_for_client` card, the app-level wait pick-up). The+ // connection guard below only sees a connection once the token refresh is+ // done, so concurrent callers would each start a local operation and only+ // the last connection would ever see the run end. Share one attempt.+ const inFlight = this.#reconnectsInFlight.get(params.operationId);+ if (inFlight) return inFlight;++ const attempt = this.#reconnectToGatewayOperation(params).finally(() => {+ this.#reconnectsInFlight.delete(params.operationId);+ });+ this.#reconnectsInFlight.set(params.operationId, attempt);+ return attempt;+ };++ #reconnectToGatewayOperation = async (+ params: ReconnectToGatewayOperationParams,+ ): Promise<void> => {const { agentShareId, assistantMessageId, heteroType, operationId, topicId, scope, threadId } =params;@@ -2084,3 +2166,16 @@ export class GatewayActionImpl {}export type GatewayAction = Pick<GatewayActionImpl, keyof GatewayActionImpl>;++const GATEWAY_CONNECT_WAIT_MS = 5000;++/** Resolve once the connection reads `connected`, or after a bounded wait. */+const waitForGatewayConnected = async (+ readStatus: () => ConnectionStatus | undefined,+): Promise<boolean> => {+ const deadline = Date.now() + GATEWAY_CONNECT_WAIT_MS;+ while (readStatus() !== 'connected' && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ return readStatus() === 'connected';+};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.tsindex 0d3d57da3aa..a0994670a66 100644--- 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.ts@@ -126,6 +126,32 @@ describe('createGatewayEventHandler — LLM relay', () => {]);});+ it('keeps handling the run after a parked call error, so a resume streams into it', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'msg-1',+ context,+ operationId: 'op-1',+ });++ // No client took the call: the run parks in `waiting_for_client`.+ handler(+ makeEvent('error', {+ body: { reason: 'no_executor', recoverable: true },+ error: 'ClientLlmExecutorUnavailable',+ }),+ );+ await flush();+ // A client resumed it; the replayed call reaches this session.+ handler(makeEvent('llm_execute', execute({ callId: 'op-1:1:1', stepIndex: 1 })));++ expect(relay.execute).toHaveBeenCalledWith(+ expect.objectContaining({ callId: 'op-1:1:1' }),+ expect.anything(),+ );+ expect(relay.cancelOperation).not.toHaveBeenCalled();+ });+it('applies the echo when another client ran the call', async () => {const store = createStore();const handler = createGatewayEventHandler(() => store, {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex f1e31f15e36..668ef988d3f 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -14,9 +14,11 @@ import type {ToolStartData,ToolStateChunkData,} from '@lobechat/agent-gateway-client';+import { isSessionTerminalEvent } from '@lobechat/agent-gateway-client';import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';import type { BuiltinToolResult, ConversationContext, UIChatMessage } from '@lobechat/types';+import { isClientLlmWaitableError } from '@lobechat/types';import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { readConversationMessages } from '@/helpers/conversationMessageRead';@@ -622,7 +624,9 @@ export const createGatewayEventHandler = (return;}- if (event.type === 'agent_runtime_end' || event.type === 'error') {+ // A parked LLM call's error is not terminal: the run streams on in this+ // same session once a client resumes it.+ if (isSessionTerminalEvent(event)) {terminalState = event.type === 'error' ? 'error' : 'completed';// A relayed attempt this tab still runs for the run is moot now.llmRelayExecutor.cancelOperation(event.operationId || gatewayOperationId);@@ -1429,6 +1433,20 @@ export const createGatewayEventHandler = (const messageError = normalizeHeterogeneousMessageError(normalizeChatMessageError(event.data),);++ // A relayed LLM call no client took: the server parks the run in+ // `waiting_for_client` (or, if it cannot, fails it and writes the+ // error itself), so this is not the run's end and the row is not ours+ // to write — persisting it here would replace the waiting notice, and+ // a stream replay on reconnect would do so long after the park. Show+ // what the server wrote instead.+ if (isClientLlmWaitableError(messageError)) {+ get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);+ endReasoningIfNeeded();+ await refreshMessagesFromDb().catch(console.error);+ return;+ }+const errorMessage = messageError.message;void emitAgentSignal({