Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-runtime): remote Claude Code Human-in-the-loop via stream long-poll (#16557)

Arvin Xu588e654923a6
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index c35eb5c869f..fa87f6aadff 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -1,9 +1,12 @@
import { randomUUID } from 'node:crypto';
import { once } from 'node:events';
import { createWriteStream } from 'node:fs';
-import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
+import os from 'node:os';
import path from 'node:path';
+import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
+import { AskUserMcpServer } from '@lobechat/heterogeneous-agents/askUser';
import type {
AgentContentBlock,
AgentImageSource,
@@ -484,6 +487,95 @@ const exec = async (options: ExecOptions): Promise<void> => {
serverIngester = new SerialServerIngester(sink);
}
+ // ─── AskUserQuestion MCP β€” remote Human-in-the-loop (claude-code only) ──────
+ //
+ // Mount the same `lobe_cc` MCP server the desktop app uses, but resolve the
+ // bridge over the server's Redis stream instead of Electron IPC:
+ // - request out: `bridge.events()` ride the normal ingest sink β†’ server
+ // `heteroIngest` β†’ Redis stream β†’ renderer shows the AskUserQuestion card.
+ // - response back: the sandbox can't read Redis, so a long-poll pulls the
+ // `agent_intervention_response` off the stream (published by the browser's
+ // `submitHeteroIntervention`) and resolves the pending bridge call.
+ // The bridge's own 5-min timeout is the backstop, so a dropped poll or an
+ // absent user never strands CC.
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+ let askServer: AskUserMcpServer | undefined;
+ let askBridge: AskUserBridge | undefined;
+ let askMcpConfigPath: string | undefined;
+ const askPollAbort = new AbortController();
+ if (serverIngest && agentType === 'claude-code' && serverIngester) {
+ askServer = new AskUserMcpServer();
+ await askServer.start();
+ askBridge = askServer.registerOperation(operationId);
+ askMcpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);
+ await writeFile(
+ askMcpConfigPath,
+ JSON.stringify({
+ mcpServers: {
+ lobe_cc: {
+ alwaysLoad: true,
+ type: 'http',
+ url: askServer.urlForOperation(operationId),
+ },
+ },
+ }),
+ 'utf8',
+ );
+
+ // (i) Forward bridge events into the same ordered ingest path as CC's. The
+ // request always goes out. For responses, only forward the ones the browser
+ // can't have published itself β€” producer-side timeout / session_ended β€” so
+ // the renderer's card un-sticks; browser-originated answers (success /
+ // user_cancelled) are already on the stream via `submitHeteroIntervention`.
+ void (async () => {
+ for await (const event of askBridge!.events()) {
+ if (event.type === 'agent_intervention_response') {
+ const reason = (event.data as { cancelReason?: string })?.cancelReason;
+ if (reason !== 'timeout' && reason !== 'session_ended') continue;
+ }
+ serverIngester!.push(event as AgentStreamEvent);
+ }
+ })();
+
+ // (ii) Long-poll the server for the user's answer β€” only while a question is
+ // actually pending, so an idle run holds no server invocation.
+ void (async () => {
+ const client = await getTrpcClient();
+ let lastEventId = '$';
+ while (!askPollAbort.signal.aborted) {
+ if (askBridge!.pendingCount === 0) {
+ await sleep(200);
+ continue;
+ }
+ try {
+ const res = await client.aiAgent.waitInterventionResponse.query({
+ lastEventId,
+ operationId,
+ });
+ lastEventId = res.lastEventId;
+ for (const event of res.events) {
+ const data = event.data as {
+ cancelReason?: 'session_ended' | 'timeout' | 'user_cancelled';
+ cancelled?: boolean;
+ result?: unknown;
+ toolCallId: string;
+ };
+ // Idempotent: resolve() no-ops on an unknown / already-settled id.
+ askBridge!.resolve(data.toolCallId, {
+ cancelReason: data.cancelReason,
+ cancelled: data.cancelled,
+ result: data.result,
+ });
+ }
+ } catch {
+ // Transient (server hiccup / token refresh) β€” back off and retry.
+ // The bridge's 5-min timeout still bounds the overall wait.
+ await sleep(1000);
+ }
+ }
+ })();
+ }
+
/**
* Spawn one agent process and stream all its events into the server ingester.
*
@@ -689,7 +781,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
// ─── First run (with --resume if provided) ───────────────────────────────
const interceptResume = !!options.resume;
- const extraArgs = buildExtraArgs(options);
+ const extraArgs = [
+ ...(buildExtraArgs(options) ?? []),
+ // Point CC at the lobe_cc AskUserQuestion MCP server we just mounted.
+ ...(askMcpConfigPath ? ['--mcp-config', askMcpConfigPath] : []),
+ ];
const first = await runOneAgent(
{
agentType: options.type,
@@ -780,6 +876,16 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
}
+ // Tear down the AskUserQuestion MCP: stop polling, cancel any in-flight
+ // pending (β†’ CC's tool returns cleanly), close the server, drop the temp
+ // config. Best-effort β€” the process is about to exit anyway.
+ askPollAbort.abort();
+ if (askServer) {
+ askServer.unregisterOperation(operationId);
+ await askServer.stop().catch(() => {});
+ }
+ if (askMcpConfigPath) await unlink(askMcpConfigPath).catch(() => {});
+
if (code !== null) process.exit(result.ingestError ? 1 : code);
if (signal === 'SIGINT') process.exit(130);
if (signal === 'SIGTERM') process.exit(143);
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 91378daa3dd..aa8782f2c8f 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -182,6 +182,14 @@ export class GatewayStreamNotifier implements IStreamEventManager {
return this.inner.subscribeStreamEvents(operationId, lastEventId, onEvents, signal);
}
+ async readEventsOnce(
+ operationId: string,
+ lastEventId?: string,
+ blockMs?: number,
+ ): Promise<{ events: StreamEvent[]; lastEventId: string }> {
+ return this.inner.readEventsOnce(operationId, lastEventId, blockMs);
+ }
+
async getStreamHistory(operationId: string, count?: number): Promise<StreamEvent[]> {
return this.inner.getStreamHistory(operationId, count);
}
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
index bb0ced16537..9f40761e9a8 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
@@ -139,6 +139,30 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
return stream.slice(-count).reverse();
}
+ /**
+ * Single bounded read β€” the long-poll primitive (see `IStreamEventManager`).
+ * The in-memory manager is non-blocking: it returns immediately with whatever
+ * is already buffered after `lastEventId`. `'$'` means "from now", so the
+ * first poll returns nothing and hands back the current tail cursor; later
+ * polls return events appended since. `blockMs` is ignored (tests/local dev
+ * only β€” the Redis manager provides the real blocking wait).
+ */
+ async readEventsOnce(
+ operationId: string,
+ lastEventId: string = '$',
+ _blockMs: number = 0,
+ ): Promise<{ events: StreamEvent[]; lastEventId: string }> {
+ const stream = this.streams.get(operationId) ?? [];
+
+ if (lastEventId === '$') {
+ return { events: [], lastEventId: stream.at(-1)?.id ?? '0' };
+ }
+
+ const idx = stream.findIndex((e) => e.id === lastEventId);
+ const events = idx >= 0 ? stream.slice(idx + 1) : stream.slice();
+ return { events, lastEventId: events.at(-1)?.id ?? lastEventId };
+ }
+
async cleanupOperation(operationId: string): Promise<void> {
this.streams.delete(operationId);
this.subscribers.delete(operationId);
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index efe43b29a72..0e2c98ae49a 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -359,6 +359,65 @@ export class StreamEventManager {
log('Subscription ended for operation %s', operationId);
}
+ /**
+ * Single bounded read β€” the long-poll primitive (see `IStreamEventManager`).
+ * One `XREAD BLOCK`, no loop: returns events after `lastEventId` (blocking up
+ * to `blockMs` for the first), or an empty list on timeout. The returned
+ * `lastEventId` is always a CONCRETE stream id, never the `'$'` sentinel β€” the
+ * caller threads it into its next call to stay gap-free.
+ *
+ * `lastEventId` defaults to `'$'` (only events published after this call
+ * lands) so a fresh poll doesn't replay history. We resolve `'$'` to the
+ * stream's current tail id BEFORE blocking, because Redis re-evaluates `'$'`
+ * as "the tail at read time" on every `XREAD`: returning `'$'` unchanged on a
+ * timeout would re-anchor the next poll to whatever the tail is by then,
+ * silently skipping any event published in the gap between this call resolving
+ * and the next one being issued. Pinning a concrete id (the last entry now, or
+ * `'0'` on an empty/absent stream) closes that gap.
+ */
+ async readEventsOnce(
+ operationId: string,
+ lastEventId: string = '$',
+ blockMs: number = 25_000,
+ ): Promise<{ events: StreamEvent[]; lastEventId: string }> {
+ const streamKey = `${this.STREAM_PREFIX}:${operationId}`;
+
+ // Resolve the '$' sentinel to a concrete tail id up front (see doc above).
+ // A timeout on a blocking XREAD means nothing was appended after this id, so
+ // it is still the true tail β€” safe to hand back for the next poll.
+ let fromId = lastEventId;
+ if (fromId === '$') {
+ const tail = await this.redis.xrevrange(streamKey, '+', '-', 'COUNT', 1);
+ fromId = tail.length > 0 ? tail[0][0] : '0';
+ }
+
+ const results = await this.redis.xread('BLOCK', blockMs, 'STREAMS', streamKey, fromId);
+ if (!results || results.length === 0) return { events: [], lastEventId: fromId };
+
+ const [, messages] = results[0];
+ const events: StreamEvent[] = [];
+ let currentLastId = fromId;
+
+ for (const [id, fields] of messages) {
+ const eventData: any = {};
+ for (let i = 0; i < fields.length; i += 2) {
+ const key = fields[i];
+ const value = fields[i + 1];
+ if (key === 'data') {
+ eventData[key] = JSON.parse(value);
+ } else if (key === 'stepIndex' || key === 'timestamp') {
+ eventData[key] = parseInt(value);
+ } else {
+ eventData[key] = value;
+ }
+ }
+ events.push({ ...eventData, id } as StreamEvent);
+ currentLastId = id;
+ }
+
+ return { events, lastEventId: currentLastId };
+ }
+
/**
* Get stream event history
*/
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 4f50edd7309..f1c10f3a471 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -29,6 +29,7 @@ function createMockInner(): IStreamEventManager & { calls: Record<string, any[][
publishAgentRuntimeInit: track('publishAgentRuntimeInit') as any,
publishStreamChunk: track('publishStreamChunk') as any,
publishStreamEvent: track('publishStreamEvent') as any,
+ readEventsOnce: track('readEventsOnce') as any,
subscribeStreamEvents: track('subscribeStreamEvents') as any,
};
}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
index bdb7fcfd954..ac3dc4012e3 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
@@ -45,6 +45,57 @@ describe('InMemoryStreamEventManager', () => {
});
});
+ describe('readEventsOnce', () => {
+ it("returns nothing but a tail cursor for '$' (from-now semantics)", async () => {
+ await manager.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'agent_runtime_init',
+ });
+
+ const { events, lastEventId } = await manager.readEventsOnce('op-1', '$');
+ expect(events).toHaveLength(0);
+ // Cursor points at the current tail so the next poll reads strictly forward.
+ expect(lastEventId).not.toBe('$');
+ });
+
+ it('returns events after the cursor and advances it', async () => {
+ const firstId = await manager.publishStreamEvent('op-1', {
+ data: { n: 1 },
+ stepIndex: 0,
+ type: 'agent_runtime_init',
+ });
+ await manager.publishStreamEvent('op-1', {
+ data: { result: { a: 1 }, toolCallId: 't1' },
+ stepIndex: 1,
+ type: 'agent_intervention_response',
+ });
+
+ const { events, lastEventId } = await manager.readEventsOnce('op-1', firstId);
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe('agent_intervention_response');
+ expect(events[0].data).toMatchObject({ toolCallId: 't1' });
+ expect(lastEventId).toBe(events[0].id);
+ });
+
+ it('is empty with an unchanged cursor when nothing is newer', async () => {
+ const id = await manager.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'agent_runtime_init',
+ });
+ const { events, lastEventId } = await manager.readEventsOnce('op-1', id);
+ expect(events).toHaveLength(0);
+ expect(lastEventId).toBe(id);
+ });
+
+ it("returns empty with a '0' cursor for an unknown operation", async () => {
+ const { events, lastEventId } = await manager.readEventsOnce('nope', '$');
+ expect(events).toHaveLength(0);
+ expect(lastEventId).toBe('0');
+ });
+ });
+
describe('subscribe', () => {
it('should return an unsubscribe function', async () => {
const callback = vi.fn();
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
index 167c7042e90..3c801a475a5 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
@@ -298,6 +298,102 @@ describe('StreamEventManager', () => {
});
});
+ describe('readEventsOnce', () => {
+ it("resolves '$' to the current tail and returns it (not '$') on timeout", async () => {
+ // Stream has a tail entry; xread then times out (no newer events).
+ mockRedis.xrevrange.mockResolvedValue([['7-0', ['type', 'stream_chunk']]]);
+ mockRedis.xread.mockResolvedValue(null);
+
+ const res = await streamManager.readEventsOnce('op-1', '$', 25_000);
+
+ // '$' was resolved to the concrete tail before blocking…
+ expect(mockRedis.xrevrange).toHaveBeenCalledWith(
+ 'agent_runtime_stream:op-1',
+ '+',
+ '-',
+ 'COUNT',
+ 1,
+ );
+ expect(mockRedis.xread).toHaveBeenCalledWith(
+ 'BLOCK',
+ 25_000,
+ 'STREAMS',
+ 'agent_runtime_stream:op-1',
+ '7-0',
+ );
+ // …so the timeout hands back the concrete id, keeping the next poll gap-free.
+ expect(res).toEqual({ events: [], lastEventId: '7-0' });
+ });
+
+ it("resolves '$' on an empty stream to '0'", async () => {
+ mockRedis.xrevrange.mockResolvedValue([]);
+ mockRedis.xread.mockResolvedValue(null);
+
+ const res = await streamManager.readEventsOnce('op-1', '$');
+
+ expect(mockRedis.xread).toHaveBeenCalledWith(
+ 'BLOCK',
+ expect.any(Number),
+ 'STREAMS',
+ 'agent_runtime_stream:op-1',
+ '0',
+ );
+ expect(res).toEqual({ events: [], lastEventId: '0' });
+ });
+
+ it('does not resolve an explicit cursor and blocks from it directly', async () => {
+ mockRedis.xread.mockResolvedValue(null);
+
+ const res = await streamManager.readEventsOnce('op-1', '5-0');
+
+ expect(mockRedis.xrevrange).not.toHaveBeenCalled();
+ expect(mockRedis.xread).toHaveBeenCalledWith(
+ 'BLOCK',
+ expect.any(Number),
+ 'STREAMS',
+ 'agent_runtime_stream:op-1',
+ '5-0',
+ );
+ expect(res).toEqual({ events: [], lastEventId: '5-0' });
+ });
+
+ it('parses events and advances the cursor to the last id', async () => {
+ mockRedis.xread.mockResolvedValue([
+ [
+ 'agent_runtime_stream:op-1',
+ [
+ [
+ '8-0',
+ [
+ 'type',
+ 'agent_intervention_response',
+ 'stepIndex',
+ '2',
+ 'operationId',
+ 'op-1',
+ 'data',
+ JSON.stringify({ toolCallId: 't1' }),
+ 'timestamp',
+ '123',
+ ],
+ ],
+ ],
+ ],
+ ]);
+
+ const res = await streamManager.readEventsOnce('op-1', '5-0');
+
+ expect(res.lastEventId).toBe('8-0');
+ expect(res.events).toHaveLength(1);
+ expect(res.events[0]).toMatchObject({
+ id: '8-0',
+ type: 'agent_intervention_response',
+ stepIndex: 2,
+ data: { toolCallId: 't1' },
+ });
+ });
+ });
+
describe('stripFinalStateInEventData', () => {
it('returns data unchanged when finalState is absent', () => {
const data = { phase: 'execution_complete', reason: 'done' };
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 71ab07ac848..9e45d56d445 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -162,6 +162,24 @@ export interface IStreamEventManager {
event: Omit<StreamEvent, 'operationId' | 'timestamp'>,
) => Promise<string>;
+ /**
+ * Single bounded read of a stream β€” the long-poll primitive. Returns every
+ * event after `lastEventId`, blocking up to `blockMs` for the first one; on
+ * timeout returns an empty list. The returned `lastEventId` is always a
+ * CONCRETE stream id (never the `'$'` sentinel), so the caller can immediately
+ * re-poll from it without a gap. Unlike `subscribeStreamEvents` this does NOT
+ * loop β€” one request, one bounded wait.
+ *
+ * Used by the heterogeneous `lh hetero exec` producer (which holds only an
+ * op-scoped JWT + tRPC, never Redis) to pull `agent_intervention_response`
+ * back into its in-process `AskUserBridge`. See `aiAgent.waitInterventionResponse`.
+ */
+ readEventsOnce: (
+ operationId: string,
+ lastEventId?: string,
+ blockMs?: number,
+ ) => Promise<{ events: StreamEvent[]; lastEventId: string }>;
+
/**
* Optional: dispatch a tool execution request to the client via Agent Gateway.
* Rejects if the gateway is unavailable β€” callers decide their fallback path.
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
new file mode 100644
index 00000000000..e5777937ca0
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
@@ -0,0 +1,213 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Shared in-memory stream backing both procedures. The remote HITL loop only
+// touches `publishStreamEvent` (browser leg) + `readEventsOnce` (exec leg), so a
+// tiny store-backed stub of the factory is enough to exercise the round-trip
+// without a live Redis. An unknown `lastEventId` reads from the start (mirrors
+// Redis `XREAD 0`); `'$'` means from-now.
+const { store } = vi.hoisted(() => ({ store: { events: [] as any[], seq: 0 } }));
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createStreamEventManager: () => ({
+ async publishStreamEvent(operationId: string, event: any) {
+ const id = String(++store.seq);
+ store.events.push({ ...event, id, operationId });
+ return id;
+ },
+ async readEventsOnce(operationId: string, lastEventId = '$') {
+ const all = store.events.filter((e) => e.operationId === operationId);
+ if (lastEventId === '$') return { events: [], lastEventId: all.at(-1)?.id ?? '0' };
+ const idx = all.findIndex((e) => e.id === lastEventId);
+ const events = idx >= 0 ? all.slice(idx + 1) : all.slice();
+ return { events, lastEventId: events.at(-1)?.id ?? lastEventId };
+ },
+ }),
+}));
+
+// Services constructed by the aiAgentProcedure / heteroAgentProcedure middleware
+// β€” stub so the test stays isolated from their real deps.
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/heterogeneousAgent', () => ({
+ HeterogeneousAgentService: vi.fn().mockImplementation(() => ({})),
+}));
+
+describe('aiAgentRouter β€” remote Human-in-the-loop', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ store.events.length = 0;
+ store.seq = 0;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ // Browser leg: user JWT.
+ const userCaller = () => aiAgentRouter.createCaller({ jwtPayload: { userId }, userId } as any);
+ // Exec leg: hetero-operation JWT (server-minted, ownership-exempt).
+ const heteroCaller = () =>
+ aiAgentRouter.createCaller({
+ jwtPayload: { userId },
+ oidcAuth: { purpose: 'hetero-operation', sub: userId },
+ userId,
+ } as any);
+ // Exec leg via an owner OIDC token (a desktop reusing its own session): a
+ // normal token whose `purpose` is NOT `hetero-operation` β†’ heteroAuthKind
+ // resolves to 'user', so the ownership guard applies.
+ const ownerTokenCaller = (sub: string) =>
+ aiAgentRouter.createCaller({
+ jwtPayload: { userId: sub },
+ oidcAuth: { sub },
+ userId: sub,
+ } as any);
+
+ const insertOperation = async (id: string, ownerId: string) => {
+ const { agentOperations } = await import('@/database/schemas');
+ await serverDB.insert(agentOperations).values({ id, status: 'running', userId: ownerId });
+ };
+
+ it('submit β†’ wait round-trips a structured answer, filtered to the response', async () => {
+ await userCaller().submitHeteroIntervention({
+ operationId: 'op-1',
+ result: { 'Which env?': 'prod' },
+ toolCallId: 't1',
+ });
+
+ const res = await heteroCaller().waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-1',
+ });
+
+ expect(res.events).toHaveLength(1);
+ expect(res.events[0].type).toBe('agent_intervention_response');
+ expect(res.events[0].data).toMatchObject({
+ result: { 'Which env?': 'prod' },
+ toolCallId: 't1',
+ });
+ expect(res.events[0].data.cancelled).toBeUndefined();
+ });
+
+ it('cancel clears the result and defaults the reason', async () => {
+ await userCaller().submitHeteroIntervention({
+ cancelled: true,
+ operationId: 'op-1',
+ result: { should: 'be dropped' },
+ toolCallId: 't2',
+ });
+
+ const res = await heteroCaller().waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-1',
+ });
+
+ expect(res.events[0].data).toMatchObject({
+ cancelReason: 'user_cancelled',
+ cancelled: true,
+ toolCallId: 't2',
+ });
+ expect(res.events[0].data.result).toBeUndefined();
+ });
+
+ it('waitInterventionResponse ignores non-intervention events on the stream', async () => {
+ // A plain stream event lands on the op's stream but is not an answer.
+ store.events.push({
+ data: {},
+ id: String(++store.seq),
+ operationId: 'op-1',
+ stepIndex: 0,
+ type: 'stream_chunk',
+ });
+
+ const res = await heteroCaller().waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-1',
+ });
+
+ expect(res.events).toHaveLength(0);
+ });
+
+ describe('waitInterventionResponse ownership guard', () => {
+ it('lets an owner token read its own operation', async () => {
+ await insertOperation('op-owned', userId);
+ await userCaller().submitHeteroIntervention({
+ operationId: 'op-owned',
+ result: { answer: 'yes' },
+ toolCallId: 't-own',
+ });
+
+ const res = await ownerTokenCaller(userId).waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-owned',
+ });
+
+ expect(res.events).toHaveLength(1);
+ expect(res.events[0].data).toMatchObject({ toolCallId: 't-own' });
+ });
+
+ it("rejects an owner token reading another user's operation", async () => {
+ const otherUserId = await createTestUser(serverDB);
+ await insertOperation('op-others', otherUserId);
+ // The victim's answer lands on the stream…
+ await userCaller().submitHeteroIntervention({
+ operationId: 'op-others',
+ result: { secret: 'leak me' },
+ toolCallId: 't-victim',
+ });
+
+ // …but a different signed-in user must not be able to long-poll it.
+ await expect(
+ ownerTokenCaller(userId).waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-others',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ await cleanupTestUser(serverDB, otherUserId);
+ });
+
+ it('rejects an owner token for an unknown operation id', async () => {
+ await expect(
+ ownerTokenCaller(userId).waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-missing',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('exempts the server-minted operation token from the ownership lookup', async () => {
+ // No agent_operations row exists for this id; the operation-token path
+ // must still succeed (it's trusted as server-minted).
+ const res = await heteroCaller().waitInterventionResponse({
+ lastEventId: '0',
+ operationId: 'op-no-row',
+ });
+
+ expect(res.events).toHaveLength(0);
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 22b53fdc18b..ce89027b7e3 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -18,10 +18,11 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
-import { topics } from '@/database/schemas';
+import { agentOperations, topics } from '@/database/schemas';
import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
import { AiChatService } from '@/server/services/aiChat';
@@ -415,6 +416,38 @@ const HeteroFinishSchema = z.object({
topicId: z.string().min(1),
});
+/**
+ * Schema for `aiAgent.waitInterventionResponse` β€” the exec-side long-poll. The
+ * `lh hetero exec` producer calls this in a loop while an `AskUserBridge`
+ * pending is in flight, draining `agent_intervention_response` events off the
+ * op's Redis stream (which the sandbox can't read directly). `lastEventId`
+ * threads the cursor forward across polls; `'$'` on the first call means
+ * "only events published from now on".
+ */
+const WaitInterventionResponseSchema = z.object({
+ blockMs: z.number().int().positive().max(30_000).default(25_000),
+ lastEventId: z.string().default('$'),
+ operationId: z.string().min(1),
+});
+
+/**
+ * Schema for `aiAgent.submitHeteroIntervention` β€” the browser leg of remote
+ * Human-in-the-loop. The user's answer to an `agent_intervention_request` is
+ * published back onto the op's Redis stream as an `agent_intervention_response`,
+ * where both the renderer (card β†’ resolved) and the exec long-poll converge on
+ * it by `toolCallId`. Mutually exclusive: `result` on submit, `cancelled` on
+ * skip/cancel.
+ */
+const SubmitHeteroInterventionSchema = z.object({
+ cancelReason: z.enum(['timeout', 'user_cancelled', 'session_ended']).optional(),
+ cancelled: z.boolean().optional(),
+ operationId: z.string().min(1),
+ result: z.unknown().optional(),
+ /** Producer step index; harmless placeholder β€” correlation is by toolCallId. */
+ stepIndex: z.number().int().nonnegative().default(0),
+ toolCallId: z.string().min(1),
+});
+
const aiAgentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -1317,6 +1350,94 @@ export const aiAgentRouter = router({
}
}),
+ /**
+ * Exec-side long-poll for remote Human-in-the-loop (op-JWT auth, same as
+ * `heteroIngest`). The `lh hetero exec` producer β€” which holds only an
+ * op-scoped JWT + tRPC and never the server's Redis β€” pulls
+ * `agent_intervention_response` events off the op's Redis stream through this
+ * server-mediated read, then resolves its in-process `AskUserBridge`. One
+ * bounded `XREAD BLOCK` per call; the producer loops while a pending is in
+ * flight, threading `lastEventId` forward so nothing is missed between polls.
+ */
+ waitInterventionResponse: heteroAgentProcedure
+ .input(WaitInterventionResponseSchema)
+ .query(async ({ input, ctx }) => {
+ const { operationId, lastEventId, blockMs } = input;
+
+ // Ownership guard, mirroring heteroIngest / heteroFinish. The op stream is
+ // read by `operationId` alone, so an owner-token caller (a logged-in
+ // desktop reusing its own OIDC session) must prove it owns THIS operation
+ // β€” otherwise any signed-in user could long-poll another run's
+ // `agent_intervention_response` payloads by id. Bind the guard to the
+ // operation row directly (tighter than the topic-level guard the write
+ // paths use, since the read has no topicId to key on). The operation-token
+ // path is exempt: it's server-minted and handed only to the sandbox /
+ // device running this op.
+ if (ctx.heteroAuthKind === 'user') {
+ const [operationRow] = await ctx.serverDB
+ .select({ userId: agentOperations.userId })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId))
+ .limit(1);
+
+ if (operationRow?.userId !== ctx.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Operation not found or not owned by the caller',
+ });
+ }
+ }
+
+ const streamEventManager = createStreamEventManager();
+ const { events, lastEventId: nextEventId } = await streamEventManager.readEventsOnce(
+ operationId,
+ lastEventId,
+ blockMs,
+ );
+
+ // Only intervention responses matter to the producer; everything else on
+ // the stream is already going out via its own outbound ingest path.
+ return {
+ events: events.filter((e) => e.type === 'agent_intervention_response'),
+ lastEventId: nextEventId,
+ };
+ }),
+
+ /**
+ * Browser leg of remote Human-in-the-loop (user auth). Publishes the user's
+ * answer to an `agent_intervention_request` back onto the op's Redis stream
+ * as an `agent_intervention_response`. Two consumers converge on it by
+ * `toolCallId`: the renderer (card β†’ resolved) and the exec long-poll
+ * (`waitInterventionResponse` β†’ `bridge.resolve`). Symmetric with the
+ * desktop path, which resolves the bridge over Electron IPC instead.
+ */
+ submitHeteroIntervention: aiAgentWriteProcedure
+ .input(SubmitHeteroInterventionSchema)
+ .mutation(async ({ input }) => {
+ const { operationId, toolCallId, stepIndex, result, cancelled, cancelReason } = input;
+
+ log(
+ 'submitHeteroIntervention: op=%s toolCallId=%s cancelled=%s',
+ operationId,
+ toolCallId,
+ cancelled ?? false,
+ );
+
+ const streamEventManager = createStreamEventManager();
+ await streamEventManager.publishStreamEvent(operationId, {
+ data: {
+ cancelReason: cancelled ? (cancelReason ?? 'user_cancelled') : undefined,
+ cancelled,
+ result: cancelled ? undefined : result,
+ toolCallId,
+ },
+ stepIndex,
+ type: 'agent_intervention_response',
+ });
+
+ return { success: true as const };
+ }),
+
processHumanIntervention: aiAgentWriteProcedure
.input(ProcessHumanInterventionSchema)
.mutation(async ({ input, ctx }) => {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index da9cb509fd5..bceacab2d68 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -2,6 +2,7 @@ import { type ConversationContext, RequestTrigger } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { lambdaClient } from '@/libs/trpc/client';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { useChatStore } from '../../../../store';
@@ -18,6 +19,7 @@ vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
aiAgent: {
processHumanIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },
+ submitHeteroIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },
},
},
}));
@@ -1942,12 +1944,13 @@ describe('ConversationControl actions', () => {
);
});
- it("CURRENT BEHAVIOR: falls back to global-state optimistic context (empty op) and still submits when the operation is GC'd", async () => {
- // Characterizes action.ts ~735/~758: when the resolved op has already been
- // garbage-collected (not present in `operations`), the optimistic context
- // is the empty object `{}` (global-state fallback) rather than carrying the
- // stale operationId β€” but the IPC submit STILL fires with that operationId,
- // and the call does NOT throw. Locked as-is.
+ it("falls back to global-state optimistic context and routes a GC'd op to the remote tRPC transport", async () => {
+ // When the resolved op has already been garbage-collected (not present in
+ // `operations`), the optimistic context is the empty object `{}`
+ // (global-state fallback) rather than carrying the stale operationId. With
+ // no live op to prove local-desktop provenance, the answer routes to the
+ // universal remote transport (tRPC) β€” the run has already ended, so this is
+ // a harmless no-op either way β€” and the call does NOT throw.
const { result } = renderHook(() => useChatStore());
const agentId = 'hetero-agent';
@@ -2004,14 +2007,16 @@ describe('ConversationControl actions', () => {
{},
);
- // IPC submit still fires with the (stale) resolved operationId + cancel.
- expect(submitInterventionSpy).toHaveBeenCalledWith(
+ // Remote tRPC submit fires with the (stale) resolved operationId + cancel;
+ // the desktop IPC path is not taken for a GC'd (non-local) op.
+ expect(lambdaClient.aiAgent.submitHeteroIntervention.mutate).toHaveBeenCalledWith(
expect.objectContaining({
cancelled: true,
operationId: 'gc-op-id',
toolCallId: 'cc_call_1',
}),
);
+ expect(submitInterventionSpy).not.toHaveBeenCalled();
});
it('flips topic status on the passed context, NOT the active topic, when submitting from a background conversation', async () => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index c03147402f0..a90792a0c43 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -7,6 +7,7 @@ import {
type UIChatMessage,
} from '@lobechat/types';
+import { lambdaClient } from '@/libs/trpc/client';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { displayMessageSelectors } from '@/store/chat/selectors';
@@ -815,7 +816,8 @@ export class ConversationControlActionImpl {
// matches the active conversation the user just clicked in. The IPC
// submit below stays unchanged: `bridge.resolve()` no-ops on unknown
// toolCallIds, so it's safe to fire even when the bridge is gone.
- const operationAlive = !!this.#get().operations[operationId];
+ const operation = this.#get().operations[operationId];
+ const operationAlive = !!operation;
if (!operationAlive) {
console.warn(
'[submitHeteroIntervention] operation already gone, using global-state fallback for optimistic write:',
@@ -860,22 +862,40 @@ export class ConversationControlActionImpl {
);
}
- // Forward to the producer (Electron main β†’ bridge.resolve). Dynamic
- // import keeps `@/services/electron/*` out of non-Electron bundles.
+ // Forward the answer to the producer over the transport THIS op actually
+ // ran on β€” read from the op itself, not re-derived from the current agent
+ // config (which drifts if the user changed the execution target after
+ // dispatch, or answers while a different agent is active).
+ //
+ // A local desktop CC run is an `execHeterogeneousAgent` op whose producer
+ // lives in the Electron main β†’ resolve the bridge over IPC. Anything else β€”
+ // a gateway-dispatched remote sandbox/device run (`execServerAgentRuntime`),
+ // or an op already GC'd after its waiting-for-human signal β€” is remote:
+ // publish the answer via tRPC β†’ Redis stream β†’ the exec's long-poll β†’
+ // `bridge.resolve()`. Local hetero ops stay `running` while CC is blocked on
+ // the question, so they are never GC'd out from under this check; that makes
+ // "not an alive execHeterogeneousAgent op" a safe signal for "remote".
+ // Both paths are idempotent on an unknown / already-settled toolCallId.
+ const isLocalDesktopHetero = operation?.type === 'execHeterogeneousAgent';
try {
- const { heterogeneousAgentService } = await import('@/services/electron/heterogeneousAgent');
- await heterogeneousAgentService.submitIntervention(
- actionType === 'submit'
- ? { operationId, result: payload ?? {}, toolCallId }
- : {
- cancelReason: actionType === 'skip' ? 'user_cancelled' : 'user_cancelled',
- cancelled: true,
- operationId,
- toolCallId,
- },
- );
+ if (isLocalDesktopHetero) {
+ // Dynamic import keeps `@/services/electron/*` out of non-Electron bundles.
+ const { heterogeneousAgentService } =
+ await import('@/services/electron/heterogeneousAgent');
+ await heterogeneousAgentService.submitIntervention(
+ actionType === 'submit'
+ ? { operationId, result: payload ?? {}, toolCallId }
+ : { cancelReason: 'user_cancelled', cancelled: true, operationId, toolCallId },
+ );
+ } else {
+ await lambdaClient.aiAgent.submitHeteroIntervention.mutate(
+ actionType === 'submit'
+ ? { operationId, result: payload ?? {}, toolCallId }
+ : { cancelReason: 'user_cancelled', cancelled: true, operationId, toolCallId },
+ );
+ }
} catch (err) {
- console.error('[submitHeteroIntervention] IPC submitIntervention failed:', err);
+ console.error('[submitHeteroIntervention] submitIntervention failed:', err);
}
// Sidebar topic row was swapped to the `waitingForHuman` hand icon when