π€― 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(hetero): steer a running Claude Code session with queued follow-ups (#22575)
Mochaf819a2d25b82
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 1f61425a190..b0d9d492d15 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -43,6 +43,7 @@ import type { Command } from 'commander';import { getTrpcClient } from '../api/client';import { cliVersion } from '../pkg';import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';+import { withHeteroSteer } from '../utils/heteroSteer';import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';import { log } from '../utils/logger';import { createOperationHeartbeat } from '../utils/OperationHeartbeat';@@ -1107,15 +1108,14 @@ const exec = async (options: ExecOptions): Promise<void> => {return { code: 1, signal: null as NodeJS.Signals | null };});- // Stream events. Each event is optionally written as JSONL and pushed- // into the ingester. When intercepting resume errors, a matching- // `error` event is withheld from the ingester and flags a retry instead.+ // Stream events (steering Claude Code, see withHeteroSteer); each is optionally written as JSONL+ // and pushed into the ingester. A resume `error` is withheld and flags a retry instead.let resumeNotFound = false;let sawTerminalError = false;let terminalErrorMessage: string | undefined;let terminalErrorData: Record<string, unknown> | undefined;try {- for await (const event of handle.events) {+ for await (const event of withHeteroSteer(handle, !!sink && { getTrpcClient, operationId })) {if (interceptResumeErrors && event.type === 'error') {const data = event.data as Record<string, unknown> | undefined;const msg = String(data?.message ?? data?.error ?? '');diff --git a/apps/cli/src/utils/heteroSteer.test.ts b/apps/cli/src/utils/heteroSteer.test.tsnew file mode 100644index 00000000000..03e3626bb32--- /dev/null+++ b/apps/cli/src/utils/heteroSteer.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it, vi } from 'vitest';++import { type HeteroSteerClient, withHeteroSteer } from './heteroSteer';++vi.mock('./logger', () => ({ log: { debug: vi.fn() } }));++type Event = { data?: any; type: string };++/** An event stream the test pushes into, ended with `end()`. */+const createStream = () => {+ const queue: Event[] = [];+ let wake: (() => void) | undefined;+ let ended = false;+ const events: AsyncIterable<Event> = {+ async *[Symbol.asyncIterator]() {+ for (;;) {+ if (queue.length > 0) {+ yield queue.shift()!;+ continue;+ }+ if (ended) return;+ await new Promise<void>((resolve) => (wake = resolve));+ }+ },+ };+ return {+ end: () => {+ ended = true;+ wake?.();+ },+ events,+ push: (event: Event) => {+ queue.push(event);+ wake?.();+ },+ };+};++const collect = async (iterable: AsyncIterable<Event>) => {+ const out: Event[] = [];+ for await (const event of iterable) out.push(event);+ return out;+};++const replay = (uuid: string): Event => ({+ data: { phase: 'user_message', uuid },+ type: 'step_complete',+});+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++const createClient = (messages: Array<{ content: string; messageId: string } | null>) => {+ const wait = vi.fn(async (_input: unknown, options?: { signal?: AbortSignal }) => {+ const next = messages.shift();+ if (next !== undefined) return { message: next };+ // Hold like the long-poll until the loop is stopped.+ await new Promise((_resolve, reject) =>+ options?.signal?.addEventListener('abort', () => reject(new Error('aborted'))),+ );+ return { message: null };+ });+ const giveBack = vi.fn(async () => ({ success: true }));+ const client: HeteroSteerClient = {+ aiAgent: { returnHeteroSteer: { mutate: giveBack }, waitHeteroSteer: { mutate: wait } },+ };+ return { client, giveBack, wait };+};++describe('withHeteroSteer', () => {+ it('types a queued follow-up into the session and forwards only its replay', async () => {+ const { client, wait } = createClient([null, { content: 'use pnpm', messageId: 'msg-1' }]);+ const sendUserMessage = vi.fn(async () => true);+ const stream = createStream();++ const out = collect(+ withHeteroSteer(+ { events: stream.events, sendUserMessage },+ { getTrpcClient: async () => client, operationId: 'op-1' },+ ),+ );+ await vi.waitFor(() => expect(sendUserMessage).toHaveBeenCalled());+ stream.push(replay('uuid-prompt'));+ stream.push({ data: { newStep: true }, type: 'stream_start' });+ stream.push(replay('msg-1'));+ stream.end();++ expect(sendUserMessage).toHaveBeenCalledWith('use pnpm', { uuid: 'msg-1' });+ expect(wait.mock.calls[0][0]).toEqual({ blockMs: 1, operationId: 'op-1' });+ expect(await out).toEqual([+ { data: { liveSteer: true, newStep: true }, type: 'stream_start' },+ replay('msg-1'),+ ]);+ });++ it('gives a refused message back and stops polling', async () => {+ const { client, giveBack, wait } = createClient([{ content: 'hi', messageId: 'msg-1' }]);+ const stream = createStream();++ const out = collect(+ withHeteroSteer(+ { events: stream.events, sendUserMessage: async () => false },+ { getTrpcClient: async () => client, operationId: 'op-1' },+ ),+ );+ await vi.waitFor(() => expect(giveBack).toHaveBeenCalled());+ await flush();+ stream.end();+ await out;++ expect(giveBack).toHaveBeenCalledWith({ messageId: 'msg-1', operationId: 'op-1' });+ expect(wait).toHaveBeenCalledTimes(1);+ });++ it('stops asking a server that does not know the procedure, and never marks the run', async () => {+ const wait = vi.fn(async () => {+ throw Object.assign(new Error('No procedure'), { data: { code: 'NOT_FOUND' } });+ });+ const client = {+ aiAgent: { returnHeteroSteer: { mutate: vi.fn() }, waitHeteroSteer: { mutate: wait } },+ } as unknown as HeteroSteerClient;+ const stream = createStream();++ const out = collect(+ withHeteroSteer(+ { events: stream.events, sendUserMessage: async () => true },+ { getTrpcClient: async () => client, operationId: 'op-1' },+ ),+ );+ await vi.waitFor(() => expect(wait).toHaveBeenCalled());+ stream.push({ data: {}, type: 'stream_start' });+ stream.end();++ expect(await out).toEqual([{ data: {}, type: 'stream_start' }]);+ expect(wait).toHaveBeenCalledTimes(1);+ });++ it('stops polling, and never marks the run, when the server says it is not steerable', async () => {+ const wait = vi.fn(async () => ({ message: null, steerable: false as const }));+ const client = {+ aiAgent: { returnHeteroSteer: { mutate: vi.fn() }, waitHeteroSteer: { mutate: wait } },+ } as unknown as HeteroSteerClient;+ const stream = createStream();++ const out = collect(+ withHeteroSteer(+ { events: stream.events, sendUserMessage: async () => true },+ { getTrpcClient: async () => client, operationId: 'op-child' },+ ),+ );+ await vi.waitFor(() => expect(wait).toHaveBeenCalled());+ await flush();+ stream.push({ data: {}, type: 'stream_start' });+ stream.end();++ expect(await out).toEqual([{ data: {}, type: 'stream_start' }]);+ expect(wait).toHaveBeenCalledTimes(1);+ });++ it('passes events through without a server or a live session', async () => {+ const stream = createStream();+ stream.push(replay('uuid-prompt'));+ stream.end();++ expect(await collect(withHeteroSteer({ events: stream.events }, false))).toEqual([+ replay('uuid-prompt'),+ ]);+ });+});diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsnew file mode 100644index 00000000000..ccb89b5a121--- /dev/null+++ b/apps/cli/src/utils/heteroSteer.ts@@ -0,0 +1,139 @@+import type { AgentPromptInput } from '@lobechat/heterogeneous-agents/spawn';++import { log } from './logger';++/** The part of the lambda client the steer loop calls. */+export interface HeteroSteerClient {+ aiAgent: {+ returnHeteroSteer: {+ mutate: (input: { messageId: string; operationId: string }) => Promise<unknown>;+ };+ waitHeteroSteer: {+ mutate: (+ input: { blockMs?: number; operationId: string },+ options?: { signal?: AbortSignal },+ ) => Promise<{+ message: { content: string; messageId: string } | null;+ /** `false` for a run the user does not type into (a child run): stop polling. */+ steerable?: false;+ }>;+ };+ };+}++export interface HeteroSteerContext {+ getTrpcClient: () => Promise<HeteroSteerClient>;+ operationId: string;+}++interface SteerableHandle {+ events: AsyncIterable<any>;+ sendUserMessage?: (prompt: AgentPromptInput, options?: { uuid?: string }) => Promise<boolean>;+}++const RETRY_MS = 2000;++/** The server predates steer delivery, or refuses it for this run: stop asking. */+const isPermanentRefusal = (error: unknown) => {+ const code = (error as { data?: { code?: string } } | undefined)?.data?.code;+ return code === 'NOT_FOUND' || code === 'FORBIDDEN' || code === 'BAD_REQUEST';+};++const isUserMessageReplay = (event: { data?: any; type: string }) =>+ event.type === 'step_complete' &&+ event.data?.phase === 'user_message' &&+ typeof event.data?.uuid === 'string';++const isMainStreamStart = (event: { data?: any; type: string }) =>+ event.type === 'stream_start' && !event.data?.subagent;++/**+ * Stream a Claude Code run's events while typing the follow-ups the user+ * queues behind it into the live session (steer), instead of leaving them for+ * the next turn.+ *+ * Polls `aiAgent.waitHeteroSteer` for as long as the run streams and its+ * session takes input; a message the session refuses goes back with+ * `aiAgent.returnHeteroSteer`. Claude Code replays every message it picks up:+ * the replay of a delivery is forwarded for the server to write the message+ * into the conversation; any other replay (the run's own prompt) is dropped.+ * Once the server answered, the next main `stream_start` carries `liveSteer`+ * so the client knows the run's queue no longer waits for the run to end.+ *+ * Without a server context or a live session, events pass through unchanged.+ */+export async function* withHeteroSteer<E extends { data?: any; type: string }>(+ handle: SteerableHandle & { events: AsyncIterable<E> },+ context: HeteroSteerContext | undefined | false,+): AsyncGenerator<E> {+ const send = handle.sendUserMessage;+ if (!context || !send) {+ yield* handle.events;+ return;+ }++ const { operationId } = context;+ const delivered = new Set<string>();+ const abort = new AbortController();+ // Set once the server answered a poll; the next main `stream_start` tells+ // the client, so an older server never gets its queue hint changed.+ let supported = false;+ let markedLive = false;++ const poll = async () => {+ const client = await context.getTrpcClient();+ while (!abort.signal.aborted) {+ let message: { content: string; messageId: string } | null;+ try {+ const res = await client.aiAgent.waitHeteroSteer.mutate(+ // The first poll answers at once, so the run is marked steerable early.+ supported ? { operationId } : { blockMs: 1, operationId },+ { signal: abort.signal },+ );+ if (res.steerable === false) return;+ message = res.message;+ supported = true;+ } catch (error) {+ if (abort.signal.aborted) return;+ if (isPermanentRefusal(error)) {+ log.debug('Steer delivery unavailable for this run: %s', String(error));+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, RETRY_MS));+ continue;+ }+ if (!message) continue;++ const accepted = await send(message.content, { uuid: message.messageId }).catch(() => false);+ if (accepted) {+ delivered.add(message.messageId);+ continue;+ }+ // The session stopped taking input; whatever is queued now waits for+ // the run to end, as before.+ await client.aiAgent.returnHeteroSteer+ .mutate({ messageId: message.messageId, operationId })+ .catch((error) => log.debug('Returning steer message failed: %s', String(error)));+ return;+ }+ };++ const polling = poll().catch((error) => log.debug('Steer polling stopped: %s', String(error)));+ try {+ for await (const event of handle.events) {+ if (isUserMessageReplay(event)) {+ if (delivered.delete(event.data.uuid)) yield event;+ continue;+ }+ if (supported && !markedLive && isMainStreamStart(event)) {+ markedLive = true;+ yield { ...event, data: { ...event.data, liveSteer: true } };+ continue;+ }+ yield event;+ }+ } finally {+ abort.abort();+ await polling;+ }+}diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex cff721106f9..21c19225734 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -193,6 +193,13 @@ export const RedisKeys = {* Full key: agentSteer:thread_start:v1:{threadId}*/threadStartFence: (threadId: string): string => `thread_start:v1:${threadId}`,+ /**+ * Follow-ups a heterogeneous run (Claude Code) took into its live session+ * and has not picked up yet (field = user message id). Their drained batch+ * stays leased until the agent replays the message.+ * Full key: agentSteer:hetero_deliveries:v1:{operationId}+ */+ heteroDeliveries: (operationId: string): string => `hetero_deliveries:v1:${operationId}`,},/*** Agent identity scope β see {@link RedisKeyNamespace.AGENT_IDENTITY}.diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex 9079888958c..be9a38b5fc4 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -20,6 +20,11 @@ import { signHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';import { mapAgentInterventionTRPCError } from '@/server/routers/lambda/_helpers/agentInterventionError';import { AiAgentService } from '@/server/services/aiAgent';+import {+ renewHeteroSteers,+ returnHeteroSteer,+ takeHeteroSteer,+} from '@/server/services/aiAgent/steerQueue/hetero';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import {HeteroOperationPrincipalError,@@ -128,6 +133,25 @@ const WaitInterventionResponseSchema = z.object({operationId: z.string().min(1),});+/**+ * Schema for `aiAgent.waitHeteroSteer` β the exec-side long-poll for follow-ups+ * the user queued behind a live heterogeneous run (Claude Code), delivered into+ * its session instead of waiting for the run to end.+ */+const WaitHeteroSteerSchema = z.object({+ blockMs: z.number().int().positive().max(25_000).default(20_000),+ operationId: z.string().min(1),+});++/** Schema for `aiAgent.returnHeteroSteer` β the session could not take the message. */+const ReturnHeteroSteerSchema = z.object({+ messageId: z.string().min(1),+ operationId: z.string().min(1),+});++/** How often a `waitHeteroSteer` poll re-checks the queue while it holds the request. */+const HETERO_STEER_CHECK_MS = 1500;+/*** Schema for `aiAgent.submitHeteroIntervention` β the browser leg of remote* Human-in-the-loop. The user's answer to an `agent_intervention_request` is@@ -482,6 +506,96 @@ export const heteroRouter = router({lastEventId: nextEventId,};}),+ /**+ * Exec-side long-poll for steer messages. `lh hetero exec` calls this in a+ * loop for as long as its Claude Code session takes input; each call holds+ * up to `blockMs` and returns the next follow-up to type into the session,+ * or `null`. Every call also renews the leases of messages the session holds+ * but has not picked up, so they return to the queue only if the run dies.+ */+ waitHeteroSteer: heteroAgentProcedure+ .input(WaitHeteroSteerSchema)+ .mutation(async ({ input, ctx }) => {+ const { operationId, blockMs } = input;++ await authorizeOperationCallback(ctx, operationId, 'hetero:ingest');++ const [operation] = await ctx.serverDB+ .select({+ agentId: agentOperations.agentId,+ parentOperationId: agentOperations.parentOperationId,+ threadId: agentOperations.threadId,+ topicId: agentOperations.topicId,+ userId: agentOperations.userId,+ workspaceId: agentOperations.workspaceId,+ })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);++ if (!operation || operation.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Operation not found or not owned by the caller',+ });+ }+ // A child run (group member, sub-agent) is not where the user types. Say+ // so, rather than answer an empty poll at once: the producer stops asking.+ if (operation.parentOperationId || !operation.topicId) {+ return { message: null, steerable: false as const };+ }++ const storeCtx = {+ db: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: operation.workspaceId,+ };+ const scope = {+ threadId: operation.threadId ?? null,+ topicId: operation.topicId,+ userId: ctx.userId,+ };++ await renewHeteroSteers(operationId);++ const deadline = Date.now() + blockMs;+ for (;;) {+ const message = await takeHeteroSteer(storeCtx, {+ agentId: operation.agentId,+ operationId,+ scope,+ });+ if (message) return { message };+ if (Date.now() + HETERO_STEER_CHECK_MS > deadline) return { message: null };+ await new Promise((resolve) => setTimeout(resolve, HETERO_STEER_CHECK_MS));+ }+ }),+ /**+ * The session refused a message `waitHeteroSteer` handed out (its input had+ * already closed): put the follow-up back, so it starts the next turn when+ * the run ends.+ */+ returnHeteroSteer: heteroAgentProcedure+ .input(ReturnHeteroSteerSchema)+ .mutation(async ({ input, ctx }) => {+ await authorizeOperationCallback(ctx, input.operationId, 'hetero:ingest', {+ allowTerminalOperation: true,+ });+ const [operation] = await ctx.serverDB+ .select({ userId: agentOperations.userId })+ .from(agentOperations)+ .where(eq(agentOperations.id, input.operationId))+ .limit(1);+ if (operation?.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Operation not found or not owned by the caller',+ });+ }++ await returnHeteroSteer(input.operationId, input.messageId);+ return { success: true as const };+ }),/*** Authenticated cold-start review lookup. The opaque token is the only* client-supplied locator; Cloud resolves operation/tool ownership insidediff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.tsindex ea0f9bfba10..abbc667cd88 100644--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts@@ -51,12 +51,14 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {['resolveAgentInterventionBySource', 'mutation'],['resolveHeteroIntervention', 'mutation'],['resumeClientLlmWait', 'mutation'],+ ['returnHeteroSteer', 'mutation'],['scheduleAgentRun', 'mutation'],['setQueuedMessages', 'mutation'],['startExecution', 'mutation'],['stopPendingApproval', 'mutation'],['submitHeteroIntervention', 'mutation'],['updateClientTaskThreadStatus', 'mutation'],+ ['waitHeteroSteer', 'mutation'],['waitInterventionResponse', 'query'],];}diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.test.tsnew file mode 100644index 00000000000..71770a41fb3--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts@@ -0,0 +1,233 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ canSteerHeteroRun,+ consumeHeteroSteer,+ releaseHeteroSteers,+ renewHeteroSteers,+ returnHeteroSteer,+ takeHeteroSteer,+} from './hetero';+import type { QueuedFollowUp } from './index';++const mocks = vi.hoisted(() => ({+ assertCanUseAgentRunConversation: vi.fn(),+ assertCanUseWorkspaceAgent: vi.fn(),+ boundOperations: vi.fn(),+ create: vi.fn(),+ deliveries: new Map<string, string>(),+ drain: vi.fn(),+ findById: vi.fn(),+ isRunAlive: vi.fn(),+ renew: vi.fn(),+ settle: vi.fn(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: {+ steerQueue: {+ boundOperations: mocks.boundOperations,+ drain: mocks.drain,+ listHeteroDeliveries: vi.fn(async () =>+ Object.fromEntries([...mocks.deliveries].map(([id, raw]) => [id, JSON.parse(raw)])),+ ),+ putHeteroDelivery: vi.fn(async (_op: string, id: string, value: unknown) => {+ mocks.deliveries.set(id, JSON.stringify(value));+ }),+ removeHeteroDelivery: vi.fn(async (_op: string, id: string) => {+ mocks.deliveries.delete(id);+ }),+ renew: mocks.renew,+ settle: mocks.settle,+ },+ },+}));+vi.mock('./liveRuns', () => ({ isRunAlive: mocks.isRunAlive }));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return { create: mocks.create, findById: mocks.findById };+ }),+}));+vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({+ assertCanUseWorkspaceAgent: mocks.assertCanUseWorkspaceAgent,+}));+vi.mock('@/server/routers/lambda/aiAgent/guards', () => ({+ assertCanUseAgentRunConversation: mocks.assertCanUseAgentRunConversation,+}));++const followUp = (+ id: string,+ createdAt: number,+ request: Partial<QueuedFollowUp['request']> = {},+) =>+ ({+ createdAt,+ id,+ request: {+ agentId: 'agt-1',+ appContext: { topicId: 'tpc-1' },+ clientIds: { userMessageId: `msg-${id}` },+ prompt: `prompt ${id}`,+ ...request,+ },+ userId: 'user-1',+ }) as QueuedFollowUp;++const scope = { threadId: null, topicId: 'tpc-1', userId: 'user-1' };+const ctx = { db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };+const take = () => takeHeteroSteer(ctx, { agentId: 'agt-1', operationId: 'op-1', scope });+const messageModel = { create: mocks.create, findById: mocks.findById } as any;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.deliveries.clear();+ mocks.boundOperations.mockResolvedValue({ operationIds: ['op-1'], total: 1 });+ mocks.drain.mockResolvedValue([]);+ mocks.findById.mockResolvedValue(undefined);+ mocks.settle.mockResolvedValue(undefined);+ mocks.renew.mockResolvedValue(true);+});++describe('canSteerHeteroRun', () => {+ it('takes plain text for the running agent', () => {+ expect(canSteerHeteroRun(followUp('a', 1), 'agt-1')).toBe(true);+ });++ it.each([+ ['an attachment', { fileIds: ['f1'] }],+ ['a selected tool', { selectedToolIds: ['t1'] }],+ ['an @-mention', { mentionedAgents: [{ id: 'a2', name: 'B' }] }],+ ['another agent', { agentId: 'agt-2' }],+ ['no text', { prompt: ' ' }],+ ])('leaves a follow-up with %s to the next turn', (_label, request) => {+ expect(canSteerHeteroRun(followUp('a', 1, request), 'agt-1')).toBe(false);+ });+});++describe('takeHeteroSteer', () => {+ it('hands out the first follow-up and returns the rest to the queue', async () => {+ mocks.drain.mockResolvedValue([followUp('a', 1), followUp('b', 2)]);++ await expect(take()).resolves.toEqual({ content: 'prompt a', messageId: 'msg-a' });++ // `b` goes back; `a` stays in the leased batch until Claude Code picks it up.+ const [, drained, returned] = mocks.settle.mock.calls[0];+ expect(returned).toEqual(['b']);+ expect(mocks.deliveries.get('msg-a')).toContain(`"drainId":"${drained}"`);+ });++ it('leaves the queue to the run end when the first follow-up cannot join', async () => {+ mocks.drain.mockResolvedValue([followUp('a', 1, { fileIds: ['f1'] }), followUp('b', 2)]);++ await expect(take()).resolves.toBeUndefined();++ expect(mocks.settle.mock.calls[0][2]).toEqual(['a', 'b']);+ expect(mocks.deliveries.size).toBe(0);+ });++ it('does not send a follow-up twice when its batch lapsed back', async () => {+ mocks.deliveries.set(+ 'msg-a',+ JSON.stringify({ content: 'prompt a', drainId: 'old', entryId: 'a', scope }),+ );+ mocks.drain.mockResolvedValue([followUp('a', 1)]);++ await expect(take()).resolves.toBeUndefined();++ expect(JSON.parse(mocks.deliveries.get('msg-a')!).drainId).not.toBe('old');+ });++ it('acknowledges a follow-up whose message is already written', async () => {+ mocks.drain.mockResolvedValue([followUp('a', 1)]);+ mocks.findById.mockResolvedValue({ id: 'msg-a' });++ await expect(take()).resolves.toBeUndefined();++ expect(mocks.settle).toHaveBeenLastCalledWith(scope, expect.any(String));+ expect(mocks.deliveries.size).toBe(0);+ });+});++describe('renewHeteroSteers', () => {+ it('extends the lease of every message the session still holds', async () => {+ mocks.deliveries.set('msg-a', JSON.stringify({ drainId: 'd1', entryId: 'a', scope }));++ await renewHeteroSteers('op-1');++ expect(mocks.renew).toHaveBeenCalledWith(scope, 'd1');+ });+});++describe('returnHeteroSteer / releaseHeteroSteers', () => {+ it('puts a refused message back in the queue', async () => {+ mocks.deliveries.set('msg-a', JSON.stringify({ drainId: 'd1', entryId: 'a', scope }));++ await returnHeteroSteer('op-1', 'msg-a');++ expect(mocks.settle).toHaveBeenCalledWith(scope, 'd1', ['a']);+ expect(mocks.deliveries.size).toBe(0);+ });++ it('puts back every message a finished run never picked up', async () => {+ mocks.deliveries.set('msg-a', JSON.stringify({ drainId: 'd1', entryId: 'a', scope }));+ mocks.deliveries.set('msg-b', JSON.stringify({ drainId: 'd2', entryId: 'b', scope }));++ await releaseHeteroSteers('op-1');++ expect(mocks.settle).toHaveBeenCalledWith(scope, 'd1', ['a']);+ expect(mocks.settle).toHaveBeenCalledWith(scope, 'd2', ['b']);+ });+});++describe('consumeHeteroSteer', () => {+ const consume = (messageId = 'msg-a') =>+ consumeHeteroSteer(messageModel, {+ agentId: 'agt-1',+ messageId,+ operationId: 'op-1',+ parentId: 'asst-1',+ topicId: 'tpc-1',+ });++ it('writes the picked-up message as a steer user message and acknowledges it', async () => {+ mocks.deliveries.set(+ 'msg-a',+ JSON.stringify({ content: 'use pnpm', drainId: 'd1', entryId: 'a', scope }),+ );++ const message = await consume();++ expect(mocks.create).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'use pnpm',+ metadata: expect.objectContaining({ operationId: 'op-1', steer: true }),+ parentId: 'asst-1',+ role: 'user',+ topicId: 'tpc-1',+ }),+ 'msg-a',+ );+ expect(mocks.settle).toHaveBeenCalledWith(scope, 'd1');+ expect(message).toMatchObject({ content: 'use pnpm', id: 'msg-a', parentId: 'asst-1' });+ expect(mocks.deliveries.size).toBe(0);+ });++ it('ignores a replay that is not a delivery (the run prompt)', async () => {+ await expect(consume('uuid-prompt')).resolves.toBeUndefined();+ expect(mocks.create).not.toHaveBeenCalled();+ });++ it('returns the written message on a retried batch', async () => {+ mocks.findById.mockResolvedValue({+ content: 'use pnpm',+ id: 'msg-a',+ metadata: { steer: true },+ parentId: 'asst-1',+ role: 'user',+ topicId: 'tpc-1',+ });++ await expect(consume()).resolves.toMatchObject({ id: 'msg-a', parentId: 'asst-1' });+ expect(mocks.create).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.tsnew file mode 100644index 00000000000..2a8c1bfec29--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.ts@@ -0,0 +1,244 @@+import type { AgentSenderMetadata } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';++import { MessageModel } from '@/database/models/message';+import { redisService } from '@/server/services/redis';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';++import type { ComposerRunContext } from '../composerRun';+import { buildUserTurnMetadata } from '../pipeline/userTurnMetadata';+import {+ ackFollowUps,+ checkFollowUpAccess,+ drainOwnFollowUps,+ type QueuedFollowUp,+ queuedUserMessageId,+ returnFollowUps,+} from './index';++const log = debug('lobe-server:steer-queue:hetero');++type StoreContext = Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>;++/**+ * A follow-up a heterogeneous run took into its live agent session. Its+ * drained batch stays leased (renewed while the run polls) until the agent+ * replays the message, so a run that dies holding it puts it back in the queue.+ */+export interface HeteroSteerDelivery {+ agentSender?: AgentSenderMetadata;+ content: string;+ drainId: string;+ editorData?: unknown;+ entryId: string;+ groupId?: string;+ scope: SteerQueueScope;+ trigger?: string;+}++export interface HeteroSteerMessage {+ content: string;+ messageId: string;+}++/**+ * Whether a follow-up can be typed into the running agent session: plain text+ * for the same agent. Attachments, attached selections, tool or skill+ * selections and @-mentions need a turn configured for them, and wait for the+ * run to end.+ */+export const canSteerHeteroRun = (entry: QueuedFollowUp, agentId: string | null): boolean => {+ const { request } = entry;+ if (!request.prompt.trim()) return false;+ if (request.fileIds?.length) return false;+ if (request.userMessage?.metadata) return false;+ if (request.selectedToolIds?.length || request.selectedSkillIds?.length) return false;+ if (request.mentionedAgents?.length) return false;+ return !!agentId && request.agentId === agentId;+};++/**+ * Keeps the leases of the deliveries the run still holds from lapsing. Called+ * on every poll, so they lapse back into the queue only when the run stops+ * polling (it died) for longer than a lease.+ */+export const renewHeteroSteers = async (operationId: string) => {+ const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);+ for (const delivery of Object.values(held)) {+ await redisService.steerQueue.renew(delivery.scope, delivery.drainId).catch((error) => {+ log('[%s] renewing batch %s failed: %O', operationId, delivery.drainId, error);+ });+ }+};++/**+ * Take the next follow-up queued behind a heterogeneous run for delivery into+ * its live session. One message per delivery, in queue order: the first+ * follow-up that cannot join (an attachment, a tool selectionβ¦) stops the+ * take, and it and everything behind it wait for the run to end.+ *+ * @returns the message to send, or `undefined` when nothing can go now+ */+export const takeHeteroSteer = async (+ ctx: StoreContext,+ params: { agentId: string | null; operationId: string; scope: SteerQueueScope },+): Promise<HeteroSteerMessage | undefined> => {+ const { agentId, operationId, scope } = params;++ const drained = await drainOwnFollowUps(ctx, scope, operationId);+ if (drained.entries.length === 0) return;++ const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);++ const [first, ...rest] = drained.entries;+ if (!canSteerHeteroRun(first, agentId)) {+ await returnFollowUps(scope, drained, drained.entries, 'needs a turn of its own');+ return;+ }+ await returnFollowUps(scope, drained, rest, 'delivered one at a time');++ const request = first.request;+ const messageId = queuedUserMessageId(ctx.userId, [first], request);++ try {+ if ((await checkFollowUpAccess(ctx, request, scope)) === 'denied') {+ console.error('[takeHeteroSteer] dropped follow-up %s: access revoked', first.id);+ await ackFollowUps(scope, drained);+ return;+ }++ // Lapsed back after an earlier delivery: the session already has it.+ // Keep holding it under the new batch instead of sending it twice.+ const earlier = held[messageId];+ if (earlier) {+ await redisService.steerQueue.putHeteroDelivery(operationId, messageId, {+ ...earlier,+ drainId: drained.drainId,+ } satisfies HeteroSteerDelivery);+ return;+ }++ const messageModel = new MessageModel(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);+ if (await messageModel.findById(messageId)) {+ await ackFollowUps(scope, drained);+ return;+ }++ await redisService.steerQueue.putHeteroDelivery(operationId, messageId, {+ agentSender: first.agentSender,+ content: request.prompt,+ drainId: drained.drainId,+ editorData: request.userMessage?.editorData,+ entryId: first.id,+ groupId: request.appContext?.groupId ?? undefined,+ scope,+ trigger: request.trigger,+ } satisfies HeteroSteerDelivery);+ } catch (error) {+ await returnFollowUps(scope, drained, [first], error);+ return;+ }++ log('[%s] Delivering follow-up %s as %s', operationId, first.id, messageId);+ return { content: request.prompt, messageId };+};++/**+ * The session could not take a delivered message (its input already closed):+ * put the follow-up back in the queue, where it starts the next turn when the+ * run ends.+ */+export const returnHeteroSteer = async (operationId: string, messageId: string) => {+ const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);+ const delivery = held[messageId];+ if (!delivery) return;++ await returnFollowUps(delivery.scope, delivery, [{ id: delivery.entryId } as QueuedFollowUp], {+ reason: 'the agent session no longer takes input',+ });+ await redisService.steerQueue.removeHeteroDelivery(operationId, messageId);+};++/**+ * Put back every delivery the run never picked up. Called when it finishes,+ * before its queue is drained into the next turn.+ */+export const releaseHeteroSteers = async (operationId: string) => {+ const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);+ for (const messageId of Object.keys(held)) {+ await returnHeteroSteer(operationId, messageId).catch((error) => {+ console.error('[releaseHeteroSteers] returning %s failed: %O', messageId, error);+ });+ }+};++/**+ * The agent replayed a delivered message: write it into the conversation as a+ * steer user message under `parentId`, and acknowledge its follow-up.+ * Idempotent: a retried batch finds the message already written.+ *+ * @returns the user message, or `undefined` when `messageId` is not a+ * delivery of this run (the initial prompt is replayed too)+ */+export const consumeHeteroSteer = async (+ messageModel: MessageModel,+ params: {+ agentId?: string | null;+ operationId: string;+ parentId: string;+ threadId?: string | null;+ topicId: string;+ messageId: string;+ },+): Promise<+ | { content: string; id: string; metadata: Record<string, unknown>; parentId: string | null }+ | undefined+> => {+ const { messageId, operationId } = params;+ const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);+ const delivery = held[messageId];++ if (!delivery) {+ const written = await messageModel.findById(messageId);+ if (written?.role !== 'user' || written.topicId !== params.topicId) return;+ return {+ content: written.content ?? '',+ id: written.id,+ metadata: (written.metadata ?? {}) as Record<string, unknown>,+ parentId: written.parentId ?? null,+ };+ }++ const metadata = {+ ...buildUserTurnMetadata({+ agentSender: delivery.agentSender,+ steer: true,+ trigger: delivery.trigger ?? RequestTrigger.Chat,+ }),+ // Stamped like the run's own rows, so a cold replica recovers it as the spine.+ operationId,+ };++ if (!(await messageModel.findById(messageId))) {+ await messageModel.create(+ {+ agentId: params.agentId ?? undefined,+ content: delivery.content,+ editorData: delivery.editorData,+ groupId: delivery.groupId,+ metadata,+ parentId: params.parentId,+ role: 'user',+ threadId: params.threadId ?? undefined,+ topicId: params.topicId,+ } as any,+ messageId,+ );+ }++ await ackFollowUps(delivery.scope, delivery);+ await redisService.steerQueue.removeHeteroDelivery(operationId, messageId);++ return { content: delivery.content, id: messageId, metadata, parentId: params.parentId };+};diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.tsnew file mode 100644index 00000000000..d80a26b83ee--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.ts@@ -0,0 +1,113 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { __resetOperationStatesForTesting } from '.';+import { buildEvent, createHarness } from './testUtils';++const consume = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/aiAgent/steerQueue/hetero', () => ({+ consumeHeteroSteer: consume,+}));++const OP = 'op-1';+const TOPIC = 'topic-1';++/** Writes the delivered message the way `consumeHeteroSteer` does. */+const consumeDelivery = (deliveries: Record<string, string>) =>+ consume.mockImplementation(async (messageModel, params) => {+ const content = deliveries[params.messageId];+ if (!content) return;+ await messageModel.create(+ {+ content,+ metadata: { operationId: params.operationId, steer: true },+ parentId: params.parentId,+ role: 'user',+ topicId: params.topicId,+ },+ params.messageId,+ );+ return { content, id: params.messageId, metadata: { steer: true }, parentId: params.parentId };+ });++const steerReplay = (stepIndex: number, uuid: string) =>+ buildEvent('step_complete', stepIndex, { phase: 'user_message', uuid });++describe('HeterogeneousPersistenceHandler β steer messages', () => {+ beforeEach(() => {+ __resetOperationStatesForTesting();+ consume.mockReset();+ });+ afterEach(() => __resetOperationStatesForTesting());++ it('opens the reply to a picked-up message under it, and names it on the stream_start', async () => {+ consumeDelivery({ 'msg-steer': 'look at Codex too' });+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ const tool = { apiName: 'Bash', arguments: '{}', id: 'tc-1', identifier: 'bash' };+ const reply = buildEvent('stream_start', 4, { messageId: 'cc-2', newStep: true });++ await h.handler.ingest({+ events: [+ buildEvent('stream_start', 0, { model: 'claude-opus' }),+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),+ buildEvent('tool_result', 2, { content: 'ok', toolCallId: 'tc-1' }),+ steerReplay(3, 'msg-steer'),+ reply,+ buildEvent('stream_chunk', 5, { chunkType: 'text', content: 'checking Codex' }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ expect(consume).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ messageId: 'msg-steer', operationId: OP, parentId: 'asst-1' }),+ );+ const steer = h.messages.get('msg-steer');+ expect(steer).toMatchObject({ parentId: 'asst-1', role: 'user' });++ const replyId = h.handler.publishData(OP, reply).assistantMessage?.id;+ expect(h.messages.get(replyId!)).toMatchObject({ parentId: 'msg-steer', role: 'assistant' });+ expect(h.handler.publishData(OP, reply).parentMessage).toMatchObject({+ content: 'look at Codex too',+ id: 'msg-steer',+ role: 'user',+ });+ });++ it('ignores the replay of the run prompt', async () => {+ consumeDelivery({});+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ const next = buildEvent('stream_start', 2, { messageId: 'cc-2', newStep: true });++ await h.handler.ingest({+ events: [buildEvent('stream_start', 0, {}), steerReplay(1, 'uuid-prompt'), next],+ operationId: OP,+ topicId: TOPIC,+ });++ const nextId = h.handler.publishData(OP, next).assistantMessage?.id;+ expect(h.messages.get(nextId!)).toMatchObject({ parentId: 'asst-1' });+ expect(h.handler.publishData(OP, next).parentMessage).toBeUndefined();+ });++ it('leaves a sub-agent replay to the sub-agent', async () => {+ consumeDelivery({ 'msg-steer': 'x' });+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });++ await h.handler.ingest({+ events: [+ buildEvent('stream_start', 0, {}),+ buildEvent('step_complete', 1, {+ phase: 'user_message',+ subagent: { parentToolCallId: 'tc-spawn-1' },+ uuid: 'msg-steer',+ }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ expect(consume).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.tsindex ceea14cb7b9..ff81840b30d 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts@@ -11,6 +11,7 @@ import { createNanoId } from '@lobechat/utils';import debug from 'debug';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import { consumeHeteroSteer } from '@/server/services/aiAgent/steerQueue/hetero';import { persistCodexTurnProvenance } from '../heteroProvenance';import { applyMainIntent, applySubagentIntent } from './applyIntents';@@ -36,6 +37,15 @@ const generateThreadId = () => `thd_${createNanoId(16)()}`;const opensSignalTurn = (event: AgentStreamEvent): boolean =>event.type === 'stream_start' && !!event.data?.newStep && !!event.data?.externalSignal;+/** A `user_message` replay from Claude Code (see `consumeSteer`). */+const isSteerReplay = (+ event: AgentStreamEvent,+): event is AgentStreamEvent & { data: { uuid: string } } =>+ event.type === 'step_complete' &&+ event.data?.phase === 'user_message' &&+ typeof event.data?.uuid === 'string' &&+ getEventScope(event).kind === 'main';+/** Subagent turns live in their thread; only main-agent step boundaries name a main assistant. */const isMainStreamStart = (event: AgentStreamEvent): boolean =>event.type === 'stream_start' && getEventScope(event).kind === 'main';@@ -156,9 +166,14 @@ export class HeterogeneousPersistenceHandler {// front would silently swallow event-level failures β the BatchIngester// would ack OK while DB state diverges from the renderer's view. Mark// only on success so a retry can complete the lost write.+ const spineBefore = state.main.lastSpineMessageId;await this.handleEvent(state, event);if (isMainStreamStart(event)) {state.streamStartAssistantIds.set(key, state.main.currentAssistantId);+ const steer = state.steerMessages.get(spineBefore);+ if (steer && state.main.lastSpineMessageId !== spineBefore) {+ state.streamStartParentMessages.set(key, steer);+ }}state.processedKeys.add(key);state.lastStepIndex = Math.max(state.lastStepIndex, event.stepIndex);@@ -201,12 +216,17 @@ export class HeterogeneousPersistenceHandler {* and the client falls back to its DB lookup.*/publishData(operationId: string, event: AgentStreamEvent): AgentStreamEvent['data'] {- const assistantId = operationStates- .get(operationId)- ?.streamStartAssistantIds.get(eventKey(event));+ const state = operationStates.get(operationId);+ const key = eventKey(event);+ const assistantId = state?.streamStartAssistantIds.get(key);if (!assistantId) return event.data;- return { ...event.data, assistantMessage: { id: assistantId } };+ const parentMessage = state?.streamStartParentMessages.get(key);+ return {+ ...event.data,+ assistantMessage: { id: assistantId },+ ...(parentMessage ? { parentMessage } : {}),+ };}/** Latch an event as published so a batch retry skips its XADD. */@@ -217,6 +237,7 @@ export class HeterogeneousPersistenceHandler {const key = eventKey(event);state.publishedKeys.add(key);state.streamStartAssistantIds.delete(key);+ state.streamStartParentMessages.delete(key);}/**@@ -316,9 +337,33 @@ export class HeterogeneousPersistenceHandler {// βββ Event dispatch ββββββββββββββββββββββββββββββββββββββββββββββββββββββprivate async handleEvent(state: OperationState, event: AgentStreamEvent): Promise<void> {+ if (isSteerReplay(event)) {+ await this.consumeSteer(state, event.data.uuid);+ return;+ }await this.reduceAndApply(state, event);}+ /**+ * Claude Code picked up a message the producer typed into its live session.+ * Write it as a steer user message on the run's spine; the next turn opens+ * under it. A replay that is not a delivery (the run's own prompt) is ignored.+ */+ private async consumeSteer(state: OperationState, messageId: string): Promise<void> {+ const steer = await consumeHeteroSteer(this.deps.messageModel, {+ agentId: state.agentId,+ messageId,+ operationId: state.operationId,+ parentId: state.main.lastSpineMessageId,+ threadId: state.threadId,+ topicId: state.topicId,+ });+ if (!steer) return;++ state.main = { ...state.main, lastSpineMessageId: steer.id };+ state.steerMessages.set(steer.id, { ...steer, role: 'user' });+ }+// βββ Main-agent reducer interpreter ββββββββββββββββββββββββββββββββββββββprivate mainReduceCtx(state: OperationState): MainAgentReduceCtx {diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.tsindex 77ee8bee4d8..5b27f1135ca 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts@@ -181,7 +181,9 @@ export async function loadOrCreateState(notifiedInterventionTransitions: new Set(),processedKeys: new Set(),publishedKeys: new Set(),+ steerMessages: new Map(),streamStartAssistantIds: new Map(),+ streamStartParentMessages: new Map(),toolMsgIdByCallId: new Map(),threadId: running?.threadId ?? undefined,topicId,diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.tsindex 394e697fc8d..3611f08130d 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts@@ -1,3 +1,4 @@+import type { StreamStartParentMessage } from '@lobechat/agent-gateway-client';import type { MainAgentRunState } from '@lobechat/heterogeneous-agents';import type { MessageModel } from '@/database/models/message';@@ -42,12 +43,20 @@ export interface OperationState {publishedKeys: Set<string>;/** User message answered by this operation, checked against its topic/thread before stamping. */sourceUserMessageId?: string;+ /** Steer user messages written in this run, by id (see `streamStartParentMessages`). */+ steerMessages: Map<string, StreamStartParentMessage>;/*** Assistant row each main-agent `stream_start` resolved to, keyed by* `eventKey`. Read when the event is published (stamped as* `assistantMessage.id`) and dropped once its XADD succeeds.*/streamStartAssistantIds: Map<string, string>;+ /**+ * Steer user message a main-agent `stream_start` opened its reply under,+ * keyed by `eventKey`, stamped as `parentMessage` when the event is+ * published so the client shows the message without a refetch.+ */+ streamStartParentMessages: Map<string, StreamStartParentMessage>;/** Isolation thread that owns this heterogeneous run, when applicable. */threadId: string | undefined;/**diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 0c05eea92bf..3deed7429a0 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -27,6 +27,7 @@ import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';import { createDefaultSnapshotStore } from '@/server/services/agentRuntime/snapshotStore';+import { releaseHeteroSteers } from '@/server/services/aiAgent/steerQueue/hetero';import type { SteerQueueScope } from '@/server/services/redis/steerQueue';import { instantiateVerifyPlanOnStart } from '@/server/services/verify';@@ -740,7 +741,13 @@ export class HeterogeneousAgentService {// Follow-ups the user queued behind this run start as the next turn here,// as they do when a native run ends. The completion above released the// topic, which the next turn has to claim. A failed run leaves its queue- // to the user.+ // to the user. Messages typed into the session that it never picked up go+ // back to the queue first, so they are among them.+ if (steerScope) {+ await releaseHeteroSteers(operationId).catch((err) => {+ log('heteroFinish: returning undelivered steer messages failed: %O', err);+ });+ }if (result === 'success' && steerScope) await this.startQueuedFollowUp(operationId, steerScope);}diff --git a/apps/server/src/services/redis/steerQueue.realRedis.test.ts b/apps/server/src/services/redis/steerQueue.realRedis.test.tsnew file mode 100644index 00000000000..59af54cb660--- /dev/null+++ b/apps/server/src/services/redis/steerQueue.realRedis.test.ts@@ -0,0 +1,74 @@+// @vitest-environment node+import type IORedisClient from 'ioredis';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';++import type { steerQueue as SteerQueue } from './steerQueue';++/**+ * Runs the steer queue's lease renewal and the heterogeneous delivery records+ * against a real Redis. Skipped unless `STEER_QUEUE_REAL_REDIS_URL` points at a+ * disposable instance:+ *+ * docker run -d -p 127.0.0.1:6392:6379 redis:7-alpine+ * STEER_QUEUE_REAL_REDIS_URL=redis://127.0.0.1:6392 vitest run apps/server/src/services/redis/steerQueue.realRedis.test.ts+ */+const url = process.env.STEER_QUEUE_REAL_REDIS_URL;++describe.skipIf(!url)('steerQueue lease renewal and hetero deliveries (real Redis)', () => {+ const prefix = `steer-queue-test-${Date.now()}`;+ const scope = { threadId: null, topicId: 'tpc-1', userId: 'user-1' };+ let queue: typeof SteerQueue;+ let raw: IORedisClient;++ beforeAll(async () => {+ vi.resetModules();+ process.env.REDIS_URL = url;+ process.env.REDIS_PREFIX = prefix;+ queue = (await import('./steerQueue')).steerQueue;+ const { default: IORedis } = await import('ioredis');+ raw = new IORedis(url!);+ });++ afterAll(async () => {+ const keys = await raw.keys(`${prefix}:*`);+ if (keys.length > 0) await raw.del(...keys);+ raw.disconnect();+ });++ const drainedKey = `${prefix}:agentSteer:follow_ups_drained:v1:user-1:tpc-1:main`;+ const expiryOf = async (drainId: string) => {+ const batch = await raw.hget(drainedKey, drainId);+ return Number(batch!.split(String.fromCharCode(30))[0]);+ };++ it('extends a drained batch lease without touching its entries', async () => {+ await queue.append(scope, { createdAt: 1, id: 'e1' }, 'op-1');+ const drained = await queue.drain(scope, 'op-1', [], 'drain-1');+ expect(drained.map((entry) => entry.id)).toEqual(['e1']);++ const before = await expiryOf('drain-1');+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(await queue.renew(scope, 'drain-1')).toBe(true);+ expect(await expiryOf('drain-1')).toBeGreaterThan(before);++ // Still the same batch: settling it acknowledges the entry.+ await queue.settle(scope, 'drain-1');+ expect(await raw.hget(drainedKey, 'drain-1')).toBeNull();+ expect(await queue.renew(scope, 'drain-1')).toBe(false);+ });++ it('keeps delivery records per run until they are removed', async () => {+ await queue.putHeteroDelivery('op-1', 'msg-1', { drainId: 'd1', entryId: 'e1' });+ await queue.putHeteroDelivery('op-1', 'msg-2', { drainId: 'd2', entryId: 'e2' });++ expect(await queue.listHeteroDeliveries('op-1')).toEqual({+ 'msg-1': { drainId: 'd1', entryId: 'e1' },+ 'msg-2': { drainId: 'd2', entryId: 'e2' },+ });+ expect(await raw.ttl(`${prefix}:agentSteer:hetero_deliveries:v1:op-1`)).toBeGreaterThan(0);++ await queue.removeHeteroDelivery('op-1', 'msg-1');+ expect(Object.keys(await queue.listHeteroDeliveries('op-1'))).toEqual(['msg-2']);+ expect(await queue.listHeteroDeliveries('op-other')).toEqual({});+ });+});diff --git a/apps/server/src/services/redis/steerQueue.ts b/apps/server/src/services/redis/steerQueue.tsindex ec0a2fa2747..71f2852484c 100644--- a/apps/server/src/services/redis/steerQueue.ts+++ b/apps/server/src/services/redis/steerQueue.ts@@ -309,6 +309,15 @@ endreturn #returned`;+const RENEW_SCRIPT = `${LUA_HELPERS}+local batch = redis.call('HGET', KEYS[1], ARGV[1])+if not batch then return 0 end+local _, items = splitBatch(batch)+redis.call('HSET', KEYS[1], ARGV[1], joinBatch(tonumber(ARGV[2]), items))+redis.call('EXPIRE', KEYS[1], ARGV[3])+return 1+`;+const keyOf = (scope: SteerQueueScope) =>RedisKeys.agentSteer.followUps(scope.userId, scope.topicId, scope.threadId);@@ -463,6 +472,60 @@ export const steerQueue = {);},+ /**+ * Extends a drained batch's lease, for a delivery the run is still holding+ * (a message sent into a live agent session it has not picked up yet).+ *+ * @returns false when the batch is gone (settled, or already lapsed back)+ * @throws when Redis is unavailable β the lease then lapses as usual+ */+ async renew(scope: SteerQueueScope, drainId: string): Promise<boolean> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to renew queued follow-ups');++ const renewed = await redis.eval<unknown>(+ RENEW_SCRIPT,+ 1,+ drainedKeyOf(scope),+ drainId,+ Date.now() + PROCESSING_LEASE_MS,+ QUEUE_TTL_SECONDS,+ );+ return Number(renewed) === 1;+ },++ /**+ * Records a follow-up a heterogeneous run took into its live session, until+ * the agent picks it up (see {@link RedisKeys.agentSteer.heteroDeliveries}).+ */+ async putHeteroDelivery(operationId: string, messageId: string, delivery: unknown) {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to record a delivered follow-up');++ const key = RedisKeys.agentSteer.heteroDeliveries(operationId);+ await redis.hset(key, messageId, JSON.stringify(delivery));+ await redis.expire(key, QUEUE_TTL_SECONDS);+ },++ /** The deliveries a heterogeneous run still holds, by user message id. */+ async listHeteroDeliveries<T>(operationId: string): Promise<Record<string, T>> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to read delivered follow-ups');++ const raw = (await redis.hgetall(RedisKeys.agentSteer.heteroDeliveries(operationId))) ?? {};+ return Object.fromEntries(+ Object.entries(raw).map(([id, value]) => [id, JSON.parse(String(value)) as T]),+ );+ },++ /** Drops a delivery record once it is settled. */+ async removeHeteroDelivery(operationId: string, messageId: string): Promise<void> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to settle a delivered follow-up');++ await redis.hdel(RedisKeys.agentSteer.heteroDeliveries(operationId), messageId);+ },+/*** The runs the waiting entries are bound to (unbound ones excluded), so a* caller can tell which of them ended. `total` also counts entries in draineddiff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.tsindex e43dfcd7987..2a86e56cde8 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.ts@@ -60,7 +60,12 @@ describe('ClaudeCodeAdapter live input', () => {type: 'user',uuid: 'u-2',}),- ).toEqual([]);+ ).toEqual([+ expect.objectContaining({+ data: { phase: 'user_message', uuid: 'u-2' },+ type: 'step_complete',+ }),+ ]);const reply = newStepOf(adapter.adapt(messageStart('msg_03')));expect(reply).toBeDefined();@@ -151,4 +156,48 @@ describe('ClaudeCodeAdapter live input', () => {expect(callback.data.externalSignal).toMatchObject({ sourceToolCallId: 'toolu_mon' });});+ // The host matches the uuid against the messages it delivered: the+ // initial prompt is replayed too and must not be mistaken for a steer.+ it('reports every replayed user message with the uuid it was delivered under', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(init);++ const events = adapter.adapt({+ isReplay: true,+ message: { content: [{ text: 'use pnpm instead', type: 'text' }], role: 'user' },+ type: 'user',+ uuid: 'msg_steer_1',+ });++ expect(events).toEqual([+ expect.objectContaining({+ data: { phase: 'user_message', uuid: 'msg_steer_1' },+ type: 'step_complete',+ }),+ ]);+ });++ it('does not report a replay without a uuid or one inside a sub-agent', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(init);++ expect(+ adapter.adapt({+ isReplay: true,+ message: { content: [{ text: 'hi', type: 'text' }], role: 'user' },+ type: 'user',+ }),+ ).toEqual([]);+ expect(+ adapter.adapt({+ isReplay: true,+ message: { content: [{ text: 'inner', type: 'text' }], role: 'user' },+ parent_tool_use_id: 'toolu_agent',+ type: 'user',+ uuid: 'u-sub',+ }),+ ).not.toContainEqual(+ expect.objectContaining({ data: expect.objectContaining({ phase: 'user_message' }) }),+ );+ });});diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 989420c2601..0c5b0d18dae 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -1812,12 +1812,12 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {* not main-agent-scoped).*/private handleUser(raw: any): HeterogeneousAgentEvent[] {- // A replayed user message (`--replay-user-messages`) is input the host- // delivered into a live session: the turn it opens answers the user, not a- // background task β even if a task notification lands before it opens.+ // A replayed user message (`--replay-user-messages`) is host input to the live session: its+ // turn answers the user (even after a task notification); its uuid names the delivery taken.if (raw.isReplay && !raw.parent_tool_use_id) {this.hasUnhandledUserInput = true;- return [];+ if (typeof raw.uuid !== 'string' || !raw.uuid) return [];+ return [this.makeEvent('step_complete', { phase: 'user_message', uuid: raw.uuid })];}const content = raw.message?.content;diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex 36713b9ac95..6e874c65eef 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -331,6 +331,8 @@ export interface UsageData {* Data shape for `step_complete` events. `phase` disambiguates the subtype:* - `turn_metadata`: per-turn snapshot of model + provider + usage (once per LLM call)* - `result_usage`: authoritative grand total at the end of a session+ * - `user_message`: Claude Code picked up a user message delivered into the+ * live session (`--replay-user-messages`); `uuid` is the one it was sent with*/export interface StepCompleteData {/**@@ -341,7 +343,7 @@ export interface StepCompleteData {costUsd?: number;/** Model id for this turn (only meaningful on `turn_metadata`). */model?: string;- phase: 'turn_metadata' | 'result_usage';+ phase: 'turn_metadata' | 'result_usage' | 'user_message';/*** Provider identifier for this turn β the CLI / adapter name (e.g.* `claude-code`, `codex`), not the underlying LLM vendor. CLI-wrapped agents@@ -350,6 +352,8 @@ export interface StepCompleteData {*/provider?: string;usage?: UsageData;+ /** The replayed message's uuid (only on `user_message`). */+ uuid?: string;}export interface HeterogeneousRateLimitInfo {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex d8caa4f3baf..9dbddcb27f3 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -44,7 +44,7 @@ import {resolveRuntimeEndStatus,} from './runtimeEndReason';import { applyStepMetrics } from './stepMetrics';-import { insertStreamStartSeeds } from './streamStartSeed';+import { insertStreamStartSeeds, streamStartOperationMetadata } from './streamStartSeed';// Lazy-loaded to break the import cycle:// gateway.ts β gatewayEventHandler.ts β executors/index.ts (which pulls in@@ -693,7 +693,7 @@ export const createGatewayEventHandler = (dispatchContext,);}- get().updateOperationMetadata(operationId, { visibleLoadingDone: false });+ get().updateOperationMetadata(operationId, streamStartOperationMetadata(data));// Native gateway streams carry `assistantMessage.id` directly on// stream_start and the shell-insert above guarantees a valid chunkdiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.tsindex caae4da9afe..b559f803612 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts@@ -2,6 +2,7 @@ import type { StreamStartData } from '@lobechat/agent-gateway-client';import type { ConversationContext } from '@lobechat/types';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';+import type { OperationMetadata } from '@/store/chat/slices/operation/types';import type { ChatStore } from '@/store/chat/store';/**@@ -67,3 +68,15 @@ export const insertStreamStartSeeds = (dispatchContext,);};++/**+ * Operation metadata a `stream_start` sets: the step is loading again, and a+ * heterogeneous run whose producer delivers queued follow-ups into the live+ * session (`liveSteer`, Claude Code) no longer holds its queue to the run end.+ */+export const streamStartOperationMetadata = (+ data: object | undefined,+): Partial<OperationMetadata> => ({+ visibleLoadingDone: false,+ ...(data && 'liveSteer' in data && data.liveSteer === true ? { liveSteer: true } : {}),+});diff --git a/src/store/chat/slices/operation/selectors.queueDrain.test.ts b/src/store/chat/slices/operation/selectors.queueDrain.test.tsindex 043f422b2fa..1b2d0bf26ae 100644--- a/src/store/chat/slices/operation/selectors.queueDrain.test.ts+++ b/src/store/chat/slices/operation/selectors.queueDrain.test.ts@@ -48,6 +48,14 @@ describe('isQueueDrainedAtRunEnd', () => {expect(startQueuedRun('execServerAgentRuntime', { heteroType: 'claude-code' })).toBe(true);});+ // A Claude Code producer that delivers queued follow-ups into its live+ // session (`liveSteer` on its stream_start) hands them over at the next step.+ it('hands back at the next step for a CLI run that takes steer messages', () => {+ expect(+ startQueuedRun('execServerAgentRuntime', { heteroType: 'claude-code', liveSteer: true }),+ ).toBe(false);+ });+it('hands back at the next step for the native runtime', () => {expect(startQueuedRun('execServerAgentRuntime', { heteroType: null })).toBe(false);expect(startQueuedRun('execAgentRuntime')).toBe(false);diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 0870d2931fe..5e33d78e587 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -355,6 +355,7 @@ const isQueueDrainedAtRunEnd =if (!context.agentId) return false;const hasQueuedMessages = getQueuedMessages(context)(s).length > 0;const isCliRun = (op: Operation) => {+ if (op.metadata.liveSteer) return false;if (op.type === 'execHeterogeneousAgent') return true;if (op.type !== 'execServerAgentRuntime') return false;diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 2a2e3234b0b..f65602e5af0 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -170,6 +170,11 @@ export interface OperationMetadata {// UI state (for sendMessage operation)inputEditorTempState?: any | null; // Editor state snapshot for cancel restorationinputSendErrorMsg?: string; // Error message to display in UI+ /**+ * A heterogeneous CLI run (Claude Code) whose producer types queued follow-ups+ * into its live session, so its queue drains at the next step, not the run end.+ */+ liveSteer?: boolean;/*** User-facing LLM-call total for the running operation.*@@ -178,6 +183,7 @@ export interface OperationMetadata {* scheduling/execution index.*/llmCalls?: number;+// Progress informationprogress?: {current: number;