π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent-runtime): queue steer follow-ups on the server and start them as the next turn (#21160)
Arvin Xu0e66604e4125
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 1d0e62bf252..6e284e13c8d 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -20,6 +20,11 @@ export const RedisKeyNamespace = {* stores (receipts, dedupe, policy state) already use.*/AGENT_SIGNAL: 'agent-signal',+ /**+ * Follow-ups a user queued behind a running agent turn ("steer"). The server+ * drains them into the next turn itself when the running one hands back.+ */+ AGENT_STEER: 'agentSteer',/*** AI generation related keys (agent welcome, placeholders, etc.)*/@@ -79,6 +84,40 @@ export const RedisKeys = {nightlyTopics: (userId: string, localDate: string): string =>`nightly_topics:v1:${userId}:${localDate}`,},+ /**+ * Steer queue scope β see {@link RedisKeyNamespace.AGENT_STEER}.+ */+ agentSteer: {+ /**+ * Follow-ups one user queued behind their running turn on one conversation+ * surface. Per user: workspace members can each have a run on the same topic.+ * Full key: agentSteer:follow_ups:v1:{userId}:{topicId}:{threadId|main}+ */+ followUps: (userId: string, topicId: string, threadId?: string | null): string =>+ `follow_ups:v1:${userId}:${topicId}:${threadId || 'main'}`,+ /**+ * Ids of follow-ups a drain already took from that queue, so a retried+ * append of the same id is recognized instead of queued again.+ * Full key: agentSteer:follow_ups_taken:v1:{userId}:{topicId}:{threadId|main}+ */+ takenFollowUps: (userId: string, topicId: string, threadId?: string | null): string =>+ `follow_ups_taken:v1:${userId}:${topicId}:${threadId || 'main'}`,+ /**+ * Follow-ups a run drained from that queue but has not settled yet, one+ * batch per drain (field = drain id). A batch whose lease lapses goes back+ * to the queue, so an interrupted delivery never loses an entry.+ * Full key: agentSteer:follow_ups_drained:v1:{userId}:{topicId}:{threadId|main}+ */+ drainedFollowUps: (userId: string, topicId: string, threadId?: string | null): string =>+ `follow_ups_drained:v1:${userId}:${topicId}:${threadId || 'main'}`,+ /**+ * Short fence around starting a run on an existing thread. Thread starts+ * skip the topic-start reservation, so this is what lets a queued+ * follow-up check "no run is live here" and start as one step.+ * Full key: agentSteer:thread_start:v1:{threadId}+ */+ threadStartFence: (threadId: string): string => `thread_start:v1:${threadId}`,+ },/*** AI generation scope - for AI-generated content like welcome messages*/@@ -134,6 +173,7 @@ export const RedisKeys = {*/export const RedisKeyScopeNamespace = {agentSignal: RedisKeyNamespace.AGENT_SIGNAL,+ agentSteer: RedisKeyNamespace.AGENT_STEER,aiGeneration: RedisKeyNamespace.AI_GENERATION,lobechat: RedisKeyNamespace.LOBEHUB,sendPathCache: RedisKeyNamespace.SEND_PATH_CACHE,diff --git a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.liveness.test.ts b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.liveness.test.tsnew file mode 100644index 00000000000..033bdbcfb9a--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.liveness.test.ts@@ -0,0 +1,85 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, threads, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { agentSteerQueueRouter } from '../agentSteerQueue';+import { createTestUser } from './integration/setup';++const { append } = vi.hoisted(() => ({ append: vi.fn() }));++vi.mock('@/server/services/redis', () => ({+ redisService: { steerQueue: { append, remove: vi.fn() } },+}));+vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({+ assertCanUseWorkspaceAgent: vi.fn(),+}));+vi.mock('@/server/routers/lambda/aiAgent/guards', () => ({+ assertCanUseAgentRunConversation: vi.fn(),+}));+vi.mock('@/business/server/trpc-middlewares/rbacPermission', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { withScopedPermission: () => mod.trpc.middleware(async (opts: any) => opts.next()) };+});+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { wsCompatProcedure: mod.trpc.procedure };+});+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));++let db: LobeChatDatabase;+let userId: string;+let topicId: string;+let threadId: string;++const appendTo = (scope: { threadId?: string }) =>+ agentSteerQueueRouter.createCaller({ serverDB: db, userId } as any).append({+ request: { agentId: 'agt-1', appContext: { topicId, ...scope }, prompt: 'follow-up' },+ });++const startRun = async (values: Partial<typeof agentOperations.$inferInsert>) => {+ const id = `op_${Math.random().toString(36).slice(2)}`;+ await db.insert(agentOperations).values({ id, status: 'running', topicId, userId, ...values });+ return id;+};++describe('agentSteerQueueRouter.append β live run on the requested surface', () => {+ beforeEach(async () => {+ vi.clearAllMocks();+ append.mockResolvedValue(1);+ db = await getTestDB();+ userId = await createTestUser(db);+ topicId = `tpc_${Math.random().toString(36).slice(2)}`;+ threadId = `thd_${Math.random().toString(36).slice(2)}`;+ await db.insert(topics).values({ id: topicId, userId });+ await db.insert(threads).values({ id: threadId, topicId, type: 'continuation', userId });+ });++ it('queues behind a live thread run, which never claims the topic marker', async () => {+ const threadRun = await startRun({ threadId });++ await expect(appendTo({ threadId })).resolves.toMatchObject({ queued: true });+ expect(append.mock.calls[0][0]).toEqual({ threadId, topicId, userId });+ expect(append.mock.calls[0][2]).toBe(threadRun);+ });++ it('does not queue on a thread while only the main spine is running', async () => {+ await startRun({});++ await expect(appendTo({ threadId })).resolves.toEqual({ queued: false, reason: 'idle' });+ await expect(appendTo({})).resolves.toMatchObject({ queued: true });+ });++ it('ignores child runs, finished runs and other usersβ runs', async () => {+ const otherUser = await createTestUser(db);+ await startRun({ parentOperationId: 'op_parent' });+ await startRun({ status: 'done' });+ await startRun({ userId: otherUser });++ await expect(appendTo({})).resolves.toEqual({ queued: false, reason: 'idle' });+ expect(append).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.tsnew file mode 100644index 00000000000..3fdec1a8a6f--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts@@ -0,0 +1,209 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { SteerQueueWriteUnknownError } from '@/server/services/redis/steerQueue';++import { agentSteerQueueRouter } from '../agentSteerQueue';++const mocks = vi.hoisted(() => ({+ append: vi.fn(),+ isRunningOperationAlive: vi.fn(),+ list: vi.fn(),+ liveCandidates: vi.fn(),+ remove: vi.fn(),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return { isRunningOperationAlive: mocks.isRunningOperationAlive };+ }),+}));+vi.mock('@/server/services/redis', () => ({+ redisService: {+ steerQueue: { append: mocks.append, list: mocks.list, remove: mocks.remove },+ },+}));+vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({+ assertCanUseWorkspaceAgent: vi.fn(),+}));+vi.mock('@/server/routers/lambda/aiAgent/guards', () => ({+ assertCanUseAgentRunConversation: vi.fn(),+}));+vi.mock('@/business/server/trpc-middlewares/rbacPermission', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { withScopedPermission: () => mod.trpc.middleware(async (opts: any) => opts.next()) };+});+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { wsCompatProcedure: mod.trpc.procedure };+});+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));++// The scope / owner / status filtering itself runs against a real DB in+// agentSteerQueue.liveness.test.ts; here the query only yields candidates.+const serverDB = {+ select: () => ({+ from: () => ({+ where: () => ({ orderBy: () => ({ limit: async () => mocks.liveCandidates() }) }),+ }),+ }),+};++const caller = () =>+ agentSteerQueueRouter.createCaller({+ clientIp: '1.2.3.4',+ serverDB,+ userAgent: 'test',+ userId: 'user-1',+ } as any);++const appendInput = {+ id: 'q-1',+ request: {+ agentId: 'agt-1',+ appContext: { projectWorkingDirectoryId: 'pwd-1', topicId: 'tpc-1' },+ prompt: 'also check the tests',+ streamFeatures: ['file_works'],+ },+};++describe('agentSteerQueueRouter.append', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.liveCandidates.mockReturnValue([{ id: 'op-1' }]);+ mocks.isRunningOperationAlive.mockResolvedValue(true);+ mocks.append.mockResolvedValue(1);+ mocks.remove.mockResolvedValue(true);+ });++ it('queues behind the callerβs own live run, keeping only what a later turn can use', async () => {+ await expect(caller().append(appendInput)).resolves.toEqual({+ id: 'q-1',+ length: 1,+ queued: true,+ });++ const [scope, entry, behindOperationId] = mocks.append.mock.calls[0];+ expect(behindOperationId).toBe('op-1');+ expect(scope).toEqual({ threadId: null, topicId: 'tpc-1', userId: 'user-1' });+ expect(entry).toMatchObject({+ audit: { clientIp: '1.2.3.4', userAgent: 'test' },+ id: 'q-1',+ request: {+ acceptsFileWorks: true,+ acceptsMemberRuntimeEnd: false,+ prompt: 'also check the tests',+ },+ userId: 'user-1',+ });+ expect(entry.request.appContext.projectWorkingDirectoryId).toBeUndefined();+ expect(entry.request.streamFeatures).toBeUndefined();+ });++ it('tells the client to send directly when no run is live', async () => {+ mocks.isRunningOperationAlive.mockResolvedValue(false);++ await expect(caller().append(appendInput)).resolves.toEqual({ queued: false, reason: 'idle' });+ expect(mocks.append).not.toHaveBeenCalled();+ });++ it('does not queue when no own top-level run is on the surface', async () => {+ mocks.liveCandidates.mockReturnValue([]);++ await expect(caller().append(appendInput)).resolves.toEqual({ queued: false, reason: 'idle' });+ expect(mocks.append).not.toHaveBeenCalled();+ });++ it.each(['a\tb', 'a\nb', ''])(+ 'rejects an entry id the queue header cannot carry: %j',+ async (id) => {+ await expect(caller().append({ ...appendInput, id })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mocks.append).not.toHaveBeenCalled();+ },+ );++ it('reports queued for a retry its run already took, so the client does not send it again', async () => {+ mocks.append.mockResolvedValue('taken');++ await expect(caller().append(appendInput)).resolves.toEqual({+ id: 'q-1',+ length: 0,+ queued: true,+ });+ });++ it('refuses to guess between two live runs on the same surface', async () => {+ mocks.liveCandidates.mockReturnValue([{ id: 'op-1' }, { id: 'op-2' }]);++ await expect(caller().append(appendInput)).resolves.toEqual({+ queued: false,+ reason: 'ambiguous',+ });+ expect(mocks.append).not.toHaveBeenCalled();+ });++ it('answers neither queued nor send-directly when the write outcome is unknown', async () => {+ mocks.append.mockRejectedValue(new SteerQueueWriteUnknownError(new Error('timeout')));++ await expect(caller().append(appendInput)).rejects.toMatchObject({+ code: 'SERVICE_UNAVAILABLE',+ });+ });++ it('takes the entry back when the run ended after its drain', async () => {+ mocks.isRunningOperationAlive.mockResolvedValueOnce(true).mockResolvedValueOnce(false);++ await expect(caller().append(appendInput)).resolves.toEqual({ queued: false, reason: 'idle' });+ expect(mocks.remove).toHaveBeenCalledWith(+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },+ 'q-1',+ );+ });++ it('reports queued when the drain already took the entry it tried to take back', async () => {+ mocks.isRunningOperationAlive.mockResolvedValueOnce(true).mockResolvedValueOnce(false);+ mocks.remove.mockResolvedValue(false);++ await expect(caller().append(appendInput)).resolves.toMatchObject({ queued: true });+ });++ it.each([+ [undefined, 'unavailable'],+ ['full', 'full'],+ ] as const)('falls back to a direct send when append returns %s', async (result, reason) => {+ mocks.append.mockResolvedValue(result);++ await expect(caller().append(appendInput)).resolves.toEqual({ queued: false, reason });+ });+});++describe('agentSteerQueueRouter.list / remove', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.list.mockResolvedValue([+ { createdAt: 1, id: 'mine', request: { prompt: 'a' }, userId: 'user-1' },+ { createdAt: 2, id: 'theirs', request: { prompt: 'b' }, userId: 'user-2' },+ ]);+ mocks.remove.mockResolvedValue(true);+ });++ it('lists only the callerβs own follow-ups', async () => {+ await expect(caller().list({ topicId: 'tpc-1' })).resolves.toEqual([+ { createdAt: 1, fileIds: undefined, id: 'mine', prompt: 'a' },+ ]);+ });++ it('removes only the callerβs own follow-ups', async () => {+ await expect(caller().remove({ id: 'theirs', topicId: 'tpc-1' })).resolves.toEqual({+ removed: false,+ });+ await expect(caller().remove({ id: 'mine', topicId: 'tpc-1' })).resolves.toEqual({+ removed: true,+ });+ expect(mocks.remove).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.tsnew file mode 100644index 00000000000..5e031594480--- /dev/null+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts@@ -0,0 +1,205 @@+import { randomUUID } from 'node:crypto';++import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';+import type { QueuedFollowUp } from '@/server/services/aiAgent/steerQueue';+import { findOwnLiveRuns, isRunAlive } from '@/server/services/aiAgent/steerQueue/liveRuns';+import { redisService } from '@/server/services/redis';+import {+ type SteerQueueScope,+ SteerQueueWriteUnknownError,+} from '@/server/services/redis/steerQueue';++import { ExecAgentFieldsSchema } from './aiAgent/execSchemas';+import { assertCanUseAgentRunConversation } from './aiAgent/guards';+import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './aiAgent/utils';++const log = debug('lobe-lambda-router:agent-steer-queue');++/**+ * A composer send queued behind the running turn: the fresh-send part of an+ * `aiAgent.execAgent` request. Resume / regenerate / supersede fields are not+ * accepted β a follow-up always starts a new turn of its own.+ */+const QueuedRequestSchema = ExecAgentFieldsSchema.omit({+ autoStart: true,+ clientOperations: true,+ existingMessageIds: true,+ includeFinalState: true,+ parentMessageId: true,+ replacesOperationId: true,+ resumeApproval: true,+ resumeApprovals: true,+ resumeToolResult: true,+ sourceOperationId: true,+ steer: true,+}).refine((data) => data.agentId || data.slug, {+ message: 'Either agentId or slug must be provided',+});++const ScopeSchema = z.object({+ threadId: z.string().nullish(),+ topicId: z.string(),+});++const AppendSchema = z.object({+ /** Client-minted entry id, so the client can match its optimistic tray item. */+ // Stored in a tab / newline delimited header, so only delimiter-safe ids.+ id: z+ .string()+ .regex(/^[\w-]{1,64}$/, 'Use letters, digits, `_` or `-` (at most 64)')+ .optional(),+ request: QueuedRequestSchema,+});++const steerQueueProcedure = wsCompatProcedure.use(serverDatabase);+const steerQueueWriteProcedure = steerQueueProcedure.use(withScopedPermission('message:create'));++/** The caller's own queue on the surface: each user only reads and fills theirs. */+const toScope = (scope: z.infer<typeof ScopeSchema>, userId: string): SteerQueueScope => ({+ threadId: scope.threadId ?? null,+ topicId: scope.topicId,+ userId,+});++/**+ * Follow-ups queued behind a running agent turn ("steer"), held server-side.+ * The runtime hands the turn back at its next decision point and starts the+ * queued follow-ups as the next turn itself β see `startQueuedFollowUp`.+ */+export const agentSteerQueueRouter = router({+ /**+ * Queue a follow-up behind the topic's running turn.+ *+ * `queued: false` means nothing was stored and the client should send the+ * message itself: no own run is live (`idle`), the queue is at its bound+ * (`full`), more than one own run is live on the surface (`ambiguous`), or+ * the follow-up could not be stored (`unavailable`). A `SERVICE_UNAVAILABLE`+ * error means the outcome is unknown: retry with the same `id`.+ */+ append: steerQueueWriteProcedure.input(AppendSchema).mutation(async ({ input, ctx }) => {+ const { streamFeatures, ...request } = input.request;+ const topicId = request.appContext?.topicId;+ if (!topicId) return { queued: false as const, reason: 'idle' as const };++ await assertCanUseWorkspaceAgent({+ agentId: request.agentId,+ db: ctx.serverDB,+ groupId: request.appContext?.groupId,+ slug: request.slug,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ await assertCanUseAgentRunConversation({+ db: ctx.serverDB,+ topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ const scope = toScope({ threadId: request.appContext?.threadId, topicId }, ctx.userId);+ const liveRuns = await findOwnLiveRuns(+ { db: ctx.serverDB, workspaceId: ctx.workspaceId },+ scope,+ );+ if (liveRuns.length === 0) return { queued: false as const, reason: 'idle' as const };+ // Two runs on one surface (thread starts are not serialized): there is no+ // telling which one the user is typing behind, so do not guess.+ if (liveRuns.length > 1) return { queued: false as const, reason: 'ambiguous' as const };+ const [behindOperationId] = liveRuns;++ const entry: QueuedFollowUp = {+ audit: { clientIp: ctx.clientIp ?? undefined, userAgent: ctx.userAgent ?? undefined },+ createdAt: Date.now(),+ id: input.id ?? randomUUID(),+ request: {+ ...request,+ acceptsFileWorks: acceptsFileWorksOf(streamFeatures),+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(streamFeatures),+ // A follow-up continues the conversation it was typed into; it never+ // branches or creates one.+ appContext: {+ ...request.appContext,+ initialTopicMetadata: undefined,+ newThread: undefined,+ projectWorkingDirectoryId: undefined,+ },+ },+ userId: ctx.userId,+ };++ let length: Awaited<ReturnType<typeof redisService.steerQueue.append>>;+ try {+ length = await redisService.steerQueue.append(scope, entry, behindOperationId);+ } catch (error) {+ if (!(error instanceof SteerQueueWriteUnknownError)) throw error;+ // Neither "queued" nor "send directly" is safe to answer; the client+ // retries with the same entry id, which appends at most once.+ throw new TRPCError({ cause: error, code: 'SERVICE_UNAVAILABLE', message: error.message });+ }+ if (length === undefined) return { queued: false as const, reason: 'unavailable' as const };+ if (length === 'full') return { queued: false as const, reason: 'full' as const };+ // A retry of a write that landed and was already taken by its run: it is+ // on its way, so the client must not send it again.+ if (length === 'taken') return { id: entry.id, length: 0, queued: true as const };++ // The run may have ended between the check above and the append, after its+ // drain: then nothing would ever start this entry. Take it back and let the+ // client send it. If the take-back loses, a drain already started it.+ if (+ !(await isRunAlive(+ { db: ctx.serverDB, workspaceId: ctx.workspaceId },+ ctx.userId,+ behindOperationId,+ ))+ ) {+ const removed = await redisService.steerQueue.remove(scope, entry.id);+ if (removed) return { queued: false as const, reason: 'idle' as const };+ }++ log('append: topic=%s thread=%s id=%s length=%d', topicId, scope.threadId, entry.id, length);+ return { id: entry.id, length, queued: true as const };+ }),++ /** The follow-ups waiting on a conversation, oldest first. */+ list: steerQueueProcedure.input(ScopeSchema).query(async ({ input, ctx }) => {+ await assertCanUseAgentRunConversation({+ db: ctx.serverDB,+ topicId: input.topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ const entries = await redisService.steerQueue.list<QueuedFollowUp>(toScope(input, ctx.userId));+ return entries+ .filter((entry) => entry.userId === ctx.userId)+ .map(({ createdAt, id, request }) => ({+ createdAt,+ fileIds: request.fileIds,+ id,+ prompt: request.prompt,+ }));+ }),++ /**+ * Withdraw a queued follow-up. `removed: false` means it is gone already β+ * most likely a finishing run just started it.+ */+ remove: steerQueueWriteProcedure+ .input(ScopeSchema.extend({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const scope = toScope(input, ctx.userId);+ const entries = await redisService.steerQueue.list<QueuedFollowUp>(scope);+ const entry = entries.find((item) => item.id === input.id);+ if (!entry || entry.userId !== ctx.userId) return { removed: false };++ return { removed: await redisService.steerQueue.remove(scope, input.id) };+ }),+});diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.tsindex d11a8c4d986..49d9fe48e5f 100644--- a/apps/server/src/routers/lambda/aiAgent/exec.ts+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts@@ -17,8 +17,7 @@ import { router } from '@/libs/trpc/lambda';import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';-import { createTaskRunHooks } from '@/server/services/task/runHooks';-import { type TopicRunReopenOutcome, TopicRunService } from '@/server/services/task/topicRun';+import { startComposerRun } from '@/server/services/aiAgent/composerRun';import type { ExecAgentInput } from './execSchemas';import {@@ -209,21 +208,11 @@ export const execRouter = router({slug,prompt,appContext,- autoStart = true,- deviceId,- localDeviceId,existingMessageIds = [],- fileIds,- mentionedAgents,parentMessageId,resumeApproval,resumeApprovals,resumeToolResult,- selectedSkillIds,- selectedToolIds,- steer,- trigger,- userInterventionConfig,} = input;log('execAgent: identifier=%s, prompt=%s', agentId || slug, prompt.slice(0, 50));@@ -272,123 +261,21 @@ export const execRouter = router({);if (bridged) return bridged;- // A message typed into a Task's own conversation continues that Task's- // run β and the composer dispatches it, not `runTask`. Everything the Task- // side needs for this run is attached here: the hook that settles the run- // when it ends, and the reopen that puts its run row back in flight.- // Without the pair, an answered run is invisible to the Task: the run card- // keeps the finished state of the run it replied to, `cancelTopic` refuses- // to stop the live one, and the detail page stops polling for it.- const topicRunService = new TopicRunService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );- const topicRun = appContext?.topicId- ? await topicRunService.resolveOwnableRun(appContext.topicId)- : undefined;- // Recorded on the operation-created boundary and acted on once the- // dispatch has returned.- let reopenOutcome: TopicRunReopenOutcome | undefined;-- const result = await ctx.aiAgentService.execAgent({- acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),- acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),- agentId,- appContext,- autoStart,- clientIds: input.clientIds,- clientRunSnapshot: {- operations: input.clientOperations ?? [],- replacesOperationId: input.replacesOperationId,+ const result = await startComposerRun(+ {+ aiAgentService: ctx.aiAgentService,+ clientIp: ctx.clientIp ?? undefined,+ db: ctx.serverDB,+ userAgent: ctx.userAgent ?? undefined,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,},- clientProtocol: input.clientProtocol,- includeFinalState: input.includeFinalState,- llmExecutor: input.llmExecutor,- // This procedure serves the composer (`aiAgentService.execAgentTask`).- // The client already queues follow-ups behind a live run and shows the- // user a tray; refusing here would only make the message disappear.- interactiveStart: true,- // Propagate the originating request's client IP / user agent into the run- // so downstream LLM-call metadata can carry them for auditing and spend- // attribution. These are server-derived from the tRPC context and are- // intentionally not part of the client-passable input schema.- clientIp: ctx.clientIp ?? undefined,- deviceId,- localDeviceId,- existingMessageIds,- ...(topicRun && {- hooks: createTaskRunHooks({- db: ctx.serverDB,- taskId: topicRun.taskId,- taskIdentifier: topicRun.taskIdentifier,- trigger: 'manual',- // The Task's creator, not the caller: the completion callback- // resolves the workspace from `tasks.createdByUserId`, so passing a- // workspace member would make that lookup miss and strand the run.- userId: topicRun.ownerUserId,- workspaceId: ctx.workspaceId ?? undefined,- }),- // Before the run's first step, so a short run can never finish β and- // have its own completion hook settle the row β ahead of the reopen.- onOperationCreated: async (operationId) => {- reopenOutcome = await topicRunService- .reopen({ link: topicRun, operationId })- .catch((error) => {- console.error('[aiAgent.execAgent] failed to reopen the task run: %O', error);- return 'refused' as const;- });- },- }),- fileIds,- mentionedAgents,- parentMessageId,- prompt,- replacesOperationId: input.replacesOperationId,- // When parentMessageId is provided, this is a regeneration/continue or a- // human-approval resume β either way, skip user message creation.- resume: !!parentMessageId,- resumeApproval,- resumeApprovals,- resumeToolResult,- selectedSkillIds,- selectedToolIds,- slug,- sourceOperationId: input.sourceOperationId,- steer,- trigger: trigger ?? RequestTrigger.Chat,- userAgent: ctx.userAgent ?? undefined,- userInterventionConfig,- });- // The run was dispatched but it did not take the Task's run row over. Two- // ways that happens: the Task was retired while the run was starting (the- // write failed or there is no row to keep honest), or a concurrent send on- // the same topic won the reopen and already owns the row. In both cases- // the run's hooks are already attached for the whole run, and- // `onTopicComplete` settles the topic row by id without checking which- // operation owns it β so letting this run continue would let the loser- // settle a row it does not own, finishing the winner's run ahead of it and- // overwriting its handoff/result. Stop it, exactly as the runner stops the- // run it dispatched under the same race.- if (reopenOutcome === 'refused' || reopenOutcome === 'already-running') {- const lostTheRow = reopenOutcome === 'already-running';- const stop = await ctx.aiAgentService- .interruptTask({ operationId: result.operationId })- .catch((error) => {- console.error('[aiAgent.execAgent] failed to stop the orphaned task run: %O', error);- return undefined;- });- // Same confirmation gate as `TaskService.interruptTaskOperation`.- const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;- throw new TRPCError({- code: stopped ? 'CONFLICT' : 'INTERNAL_SERVER_ERROR',- message: stopped- ? lostTheRow- ? 'Another run is already live on this task; this duplicate send was stopped.'- : 'This task run could not be recorded while it was starting; the run was stopped.'- : `This task run could not be recorded while it was starting, and stopping it (operation ${result.operationId}) could not be confirmed.`,- });- }+ {+ ...input,+ acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),+ },+ );return toClientExecAgentResult(result);} catch (error: any) {diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.tsindex 9446b9275f3..ec9a349d5c9 100644--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts@@ -123,195 +123,198 @@ export const validateResumePayload = (}};-export const ExecAgentSchema = z- .object({- includeFinalState: z.boolean().optional(),- /**- * Gateway stream features the calling client handles. `member_runtime_end`:- * a group member's terminal arrives on the supervisor's channel under that- * name instead of `agent_runtime_end`. `file_works`: pushed snapshots may- * carry `file` Work summaries. Free-form strings so an older server- * ignores features it does not know rather than rejecting the run.- */- streamFeatures: z.array(z.string()).optional(),- /**- * Wire protocol the calling client speaks. `2` declares it reconciles its- * message list from `message_patch` revisions, so the run may stop pushing- * whole `uiMessages` snapshots. Absent β 1 (an older bundle, the CLI, or a- * server-initiated run), which keeps the pushed snapshots.- */- clientProtocol: z.union([z.literal(1), z.literal(2)]).optional(),- /**- * The calling client can execute single LLM attempts the server relays to- * it (`llm_execute`) for providers only this device can reach. Sent only- * when the client is inside the `agent_llm_relay` rollout.- */- llmExecutor: LlmExecutorSchema.optional(),- /** The agent ID to run (either agentId or slug is required) */- agentId: z.string().optional(),- /** Application context for message storage */- appContext: z- .object({- conversationAgentId: z.string().optional(),- defaultTaskAssigneeAgentId: z.string().optional(),- documentId: z.string().nullish(),- /** The agent being edited when scope is 'agent_builder' (not the builder builtin itself). */- editingAgentId: z.string().optional(),- /** The group being edited when scope is 'group_agent_builder' (not a group chat turn). */- editingGroupId: z.string().optional(),- groupId: z.string().nullish(),- // The shared declaration, not a copy of it: a local `z.object()` here- // silently strips whatever the type gained and the call still answers- // 200, so the two must be one thing.- initialTopicMetadata: initialTopicMetadataSchema.optional(),- /**- * Branch this run into a new thread (subtopic) under the resolved topic.- * The gateway path never calls `aiChat.sendMessageInServer`, so this is- * the only way the composer's "start a new subtopic" intent reaches the- * server β without it the turn lands on the topic's main spine.- */- newThread: CreateThreadWithMessageSchema.optional(),- /**- * Group orchestration role of the run, stamped onto the assistant- * message's `metadata.orchestrationRole` so the supervisor/member- * identity survives the gateway step_start snapshot / refetch.- */- orchestrationRole: z.enum(['supervisor', 'member']).optional(),- /** Bind a NEW topic to this project working directory (ignored with topicId). */- projectWorkingDirectoryId: z.string().optional(),- scope: z.string().nullish(),- sessionId: z.string().optional(),- taskId: z.string().nullish(),- threadId: z.string().nullish(),- topicId: z.string().nullish(),- })- .optional(),- /** Whether to auto-start execution after creating operation */- autoStart: z.boolean().optional().default(true),- /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */- clientIds: execAgentClientIdsSchema,- /** Explicit device ID to bind to the topic and activate for this run */- deviceId: z.string().optional(),- /** Current desktop device hint, honored only for an effective local target */- localDeviceId: z.string().optional(),- /** Optional existing message IDs to include in context */- existingMessageIds: z.array(z.string()).optional().default([]),- /** File IDs of already-uploaded attachments to attach to the new user message */- fileIds: z.array(z.string()).optional(),- /** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */- parentMessageId: z.string().optional(),- /** Existing gateway operation this fresh turn atomically supersedes. */- replacesOperationId: z.string().optional(),- /**- * The server runs the composer tracked on this conversation at send time.- * Diagnostic only: recorded when this send has to supersede a live run.- */- clientOperations: z- .array(- z.object({- isAborting: z.boolean().optional(),- operationId: z.string(),- status: z.string(),- visibleLoadingDone: z.boolean().optional(),- }),- )- .max(MAX_CLIENT_OPERATION_SNAPSHOT)- .optional(),- /** The user input/prompt */- prompt: z.string(),- /**- * Resume a previous op paused on `human_approve_required`. When set, the- * new op writes the decision to the target tool message and either runs- * the approved tool (`approved`), halts with reason=`human_rejected`- * (`rejected`), or surfaces the rejection as user feedback so the LLM- * can continue (`rejected_continue`).- */- resumeApproval: ResumeApprovalDecisionSchema.optional(),- /**- * Batch form of `resumeApproval` β one entry per pending tool the user- * resolved in a single action ("approve all" on a parallel tool batch).- * The op applies every decision, then runs all approved tools in ONE- * `call_tools_batch` and continues the LLM once with the full result set.- *- * Prefer this over firing N `resumeApproval` ops for a parallel batch: each- * of those continues the LLM while the not-yet-approved tools are still- * empty rows, which forks the parent chain and shows the model blank- * results. Mutually exclusive with `resumeApproval`.- */- resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),- /**- * Resume a previous op paused on a `humanIntervention: 'always'` tool (e.g.- * lobe-agent `askUserQuestion`). When set, the new op writes the- * human-provided answer as the target tool message's result and resumes from- * `phase: 'tool_result'` β the tool is NOT re-executed, so the runtime never- * overwrites the answer with a fresh "pending" placeholder. Mutually- * exclusive with `resumeApproval`.- */- resumeToolResult: ResumeToolResultSchema.optional(),- /**- * Tool identifiers the user @-mentioned in this message. Enabled for this- * run in addition to the agent's pinned plugins, so a mentioned tool that- * isn't pinned to the agent (e.g. a custom MCP connector picked from the @- * list) is callable. Scoped to the caller's own installed tools/connectors- * by the user-scoped lookups downstream, so it can't enable others' tools.- */- selectedToolIds: z.array(z.string()).optional(),- /**- * Skill identifiers the user selected for this message. Their bodies are- * injected directly for this turn and every later turn of the topic, the- * same way a pinned skill is, instead of waiting for `activateSkill`.- * Persisted on the user message as `metadata.selectedSkillIds`.- */- selectedSkillIds: z.array(z.string()).optional(),- /**- * Agents the user @-mentioned in this message (multi-mention). When present- * (and non-group), the run enables the callAgent tool and injects the- * mentioned-agents delegation context so the supervisor delegates to them- * instead of answering itself. Mirrors the client runtime's- * `initialContext.mentionedAgents` + injected callAgent manifest.- */- mentionedAgents: z.array(z.object({ id: z.string(), name: z.string() })).optional(),- /** The agent slug to run (either agentId or slug is required) */- slug: z.string().optional(),- /**- * What initiated this operation, persisted to `agent_operations.trigger`.- * Defaults to `'chat'` when omitted β first-party SPA / desktop user- * messages are the dominant caller. Pass a more specific value (`'cli'`,- * `'openapi'`, `'eval'`, β¦) to override.- */- /**- * The prompt was queued while the previous turn was still running. The- * persisted user message carries `metadata.steer` so it renders as a- * continuation of that turn instead of a new one.- */- steer: z.boolean().optional(),- trigger: z- .string()- .refine((value) => value !== RequestTrigger.Bot, {- message: 'The bot trigger is reserved for authenticated server-side bot ingress',- })- .optional(),- /**- * The operation the launching agent's run belongs to, when another agent- * started this run (agent β agent: a sibling agent calling `lh agent run`).- * The launcher's own agent id is deliberately not sent β device-dispatched- * runs strip it β and neither is its topic: the server reads both from this- * operation row (ownership-scoped, the caller's own) and stamps- * `metadata.agentSender` on the created user message. An unknown, foreign,- * or topic-less operation simply resolves to nothing.- */- sourceOperationId: z.string().optional(),- /**- * User intervention configuration for tool approvals.- * Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)- * so tool calls auto-execute without waiting for human approval.- */- userInterventionConfig: UserInterventionConfigSchema.optional(),- })- .refine((data) => data.agentId || data.slug, {- message: 'Either agentId or slug must be provided',- })- .superRefine(validateResumePayload);+/**+ * Fields of an execAgent request. Exported without the refinements so a queued+ * follow-up (`agentSteerQueue.append`) can carry the fresh-send subset of it.+ */+export const ExecAgentFieldsSchema = z.object({+ includeFinalState: z.boolean().optional(),+ /**+ * Gateway stream features the calling client handles. `member_runtime_end`:+ * a group member's terminal arrives on the supervisor's channel under that+ * name instead of `agent_runtime_end`. `file_works`: pushed snapshots may+ * carry `file` Work summaries. Free-form strings so an older server+ * ignores features it does not know rather than rejecting the run.+ */+ streamFeatures: z.array(z.string()).optional(),+ /**+ * Wire protocol the calling client speaks. `2` declares it reconciles its+ * message list from `message_patch` revisions, so the run may stop pushing+ * whole `uiMessages` snapshots. Absent β 1 (an older bundle, the CLI, or a+ * server-initiated run), which keeps the pushed snapshots.+ */+ clientProtocol: z.union([z.literal(1), z.literal(2)]).optional(),+ /**+ * The calling client can execute single LLM attempts the server relays to+ * it (`llm_execute`) for providers only this device can reach. Sent only+ * when the client is inside the `agent_llm_relay` rollout.+ */+ llmExecutor: LlmExecutorSchema.optional(),+ /** The agent ID to run (either agentId or slug is required) */+ agentId: z.string().optional(),+ /** Application context for message storage */+ appContext: z+ .object({+ conversationAgentId: z.string().optional(),+ defaultTaskAssigneeAgentId: z.string().optional(),+ documentId: z.string().nullish(),+ /** The agent being edited when scope is 'agent_builder' (not the builder builtin itself). */+ editingAgentId: z.string().optional(),+ /** The group being edited when scope is 'group_agent_builder' (not a group chat turn). */+ editingGroupId: z.string().optional(),+ groupId: z.string().nullish(),+ // The shared declaration, not a copy of it: a local `z.object()` here+ // silently strips whatever the type gained and the call still answers+ // 200, so the two must be one thing.+ initialTopicMetadata: initialTopicMetadataSchema.optional(),+ /**+ * Branch this run into a new thread (subtopic) under the resolved topic.+ * The gateway path never calls `aiChat.sendMessageInServer`, so this is+ * the only way the composer's "start a new subtopic" intent reaches the+ * server β without it the turn lands on the topic's main spine.+ */+ newThread: CreateThreadWithMessageSchema.optional(),+ /**+ * Group orchestration role of the run, stamped onto the assistant+ * message's `metadata.orchestrationRole` so the supervisor/member+ * identity survives the gateway step_start snapshot / refetch.+ */+ orchestrationRole: z.enum(['supervisor', 'member']).optional(),+ /** Bind a NEW topic to this project working directory (ignored with topicId). */+ projectWorkingDirectoryId: z.string().optional(),+ scope: z.string().nullish(),+ sessionId: z.string().optional(),+ taskId: z.string().nullish(),+ threadId: z.string().nullish(),+ topicId: z.string().nullish(),+ })+ .optional(),+ /** Whether to auto-start execution after creating operation */+ autoStart: z.boolean().optional().default(true),+ /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */+ clientIds: execAgentClientIdsSchema,+ /** Explicit device ID to bind to the topic and activate for this run */+ deviceId: z.string().optional(),+ /** Current desktop device hint, honored only for an effective local target */+ localDeviceId: z.string().optional(),+ /** Optional existing message IDs to include in context */+ existingMessageIds: z.array(z.string()).optional().default([]),+ /** File IDs of already-uploaded attachments to attach to the new user message */+ fileIds: z.array(z.string()).optional(),+ /** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */+ parentMessageId: z.string().optional(),+ /** Existing gateway operation this fresh turn atomically supersedes. */+ replacesOperationId: z.string().optional(),+ /**+ * The server runs the composer tracked on this conversation at send time.+ * Diagnostic only: recorded when this send has to supersede a live run.+ */+ clientOperations: z+ .array(+ z.object({+ isAborting: z.boolean().optional(),+ operationId: z.string(),+ status: z.string(),+ visibleLoadingDone: z.boolean().optional(),+ }),+ )+ .max(MAX_CLIENT_OPERATION_SNAPSHOT)+ .optional(),+ /** The user input/prompt */+ prompt: z.string(),+ /**+ * Resume a previous op paused on `human_approve_required`. When set, the+ * new op writes the decision to the target tool message and either runs+ * the approved tool (`approved`), halts with reason=`human_rejected`+ * (`rejected`), or surfaces the rejection as user feedback so the LLM+ * can continue (`rejected_continue`).+ */+ resumeApproval: ResumeApprovalDecisionSchema.optional(),+ /**+ * Batch form of `resumeApproval` β one entry per pending tool the user+ * resolved in a single action ("approve all" on a parallel tool batch).+ * The op applies every decision, then runs all approved tools in ONE+ * `call_tools_batch` and continues the LLM once with the full result set.+ *+ * Prefer this over firing N `resumeApproval` ops for a parallel batch: each+ * of those continues the LLM while the not-yet-approved tools are still+ * empty rows, which forks the parent chain and shows the model blank+ * results. Mutually exclusive with `resumeApproval`.+ */+ resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),+ /**+ * Resume a previous op paused on a `humanIntervention: 'always'` tool (e.g.+ * lobe-agent `askUserQuestion`). When set, the new op writes the+ * human-provided answer as the target tool message's result and resumes from+ * `phase: 'tool_result'` β the tool is NOT re-executed, so the runtime never+ * overwrites the answer with a fresh "pending" placeholder. Mutually+ * exclusive with `resumeApproval`.+ */+ resumeToolResult: ResumeToolResultSchema.optional(),+ /**+ * Tool identifiers the user @-mentioned in this message. Enabled for this+ * run in addition to the agent's pinned plugins, so a mentioned tool that+ * isn't pinned to the agent (e.g. a custom MCP connector picked from the @+ * list) is callable. Scoped to the caller's own installed tools/connectors+ * by the user-scoped lookups downstream, so it can't enable others' tools.+ */+ selectedToolIds: z.array(z.string()).optional(),+ /**+ * Skill identifiers the user selected for this message. Their bodies are+ * injected directly for this turn and every later turn of the topic, the+ * same way a pinned skill is, instead of waiting for `activateSkill`.+ * Persisted on the user message as `metadata.selectedSkillIds`.+ */+ selectedSkillIds: z.array(z.string()).optional(),+ /**+ * Agents the user @-mentioned in this message (multi-mention). When present+ * (and non-group), the run enables the callAgent tool and injects the+ * mentioned-agents delegation context so the supervisor delegates to them+ * instead of answering itself. Mirrors the client runtime's+ * `initialContext.mentionedAgents` + injected callAgent manifest.+ */+ mentionedAgents: z.array(z.object({ id: z.string(), name: z.string() })).optional(),+ /** The agent slug to run (either agentId or slug is required) */+ slug: z.string().optional(),+ /**+ * What initiated this operation, persisted to `agent_operations.trigger`.+ * Defaults to `'chat'` when omitted β first-party SPA / desktop user+ * messages are the dominant caller. Pass a more specific value (`'cli'`,+ * `'openapi'`, `'eval'`, β¦) to override.+ */+ /**+ * The prompt was queued while the previous turn was still running. The+ * persisted user message carries `metadata.steer` so it renders as a+ * continuation of that turn instead of a new one.+ */+ steer: z.boolean().optional(),+ trigger: z+ .string()+ .refine((value) => value !== RequestTrigger.Bot, {+ message: 'The bot trigger is reserved for authenticated server-side bot ingress',+ })+ .optional(),+ /**+ * The operation the launching agent's run belongs to, when another agent+ * started this run (agent β agent: a sibling agent calling `lh agent run`).+ * The launcher's own agent id is deliberately not sent β device-dispatched+ * runs strip it β and neither is its topic: the server reads both from this+ * operation row (ownership-scoped, the caller's own) and stamps+ * `metadata.agentSender` on the created user message. An unknown, foreign,+ * or topic-less operation simply resolves to nothing.+ */+ sourceOperationId: z.string().optional(),+ /**+ * User intervention configuration for tool approvals.+ * Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)+ * so tool calls auto-execute without waiting for human approval.+ */+ userInterventionConfig: UserInterventionConfigSchema.optional(),+});++export const ExecAgentSchema = ExecAgentFieldsSchema.refine((data) => data.agentId || data.slug, {+ message: 'Either agentId or slug must be provided',+}).superRefine(validateResumePayload);export type ExecAgentInput = z.infer<typeof ExecAgentSchema>;diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex a6f1d45bac0..9079888958c 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -19,6 +19,7 @@ import { router } from '@/libs/trpc/lambda';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 { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import {HeteroOperationPrincipalError,@@ -390,6 +391,12 @@ export const heteroRouter = router({userId: ctx.userId,});const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {+ // Follow-ups queued behind the run start as its next turn through the+ // composer pipeline, under the run owner and its workspace.+ startQueuedFollowUp: (params) =>+ new AiAgentService(ctx.serverDB, ctx.userId, { workspaceId: wsId }).startQueuedFollowUp(+ params,+ ),workspaceId: wsId,});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex ca2ba243879..b72fa323a9d 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -35,6 +35,7 @@ import { agentQuotaRouter } from './agentQuota';import { agentShareRouter } from './agentShare';import { agentSignalRouter } from './agentSignal';import { agentSkillsRouter } from './agentSkills';+import { agentSteerQueueRouter } from './agentSteerQueue';import { agentTraceRouter } from './agentTrace';import { aiAgentRouter } from './aiAgent';import { aiChatRouter } from './aiChat';@@ -129,6 +130,7 @@ export const lambdaRouter = router({agentTrace: agentTraceRouter,expertise: expertiseRouter,agentSignal: agentSignalRouter,+ agentSteerQueue: agentSteerQueueRouter,changelog: changelogRouter,brief: briefRouter,aiAgent: aiAgentRouter,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.tsnew file mode 100644index 00000000000..28646cf119b--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts@@ -0,0 +1,231 @@+/**+ * @vitest-environment node+ */+import type { AgentState } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { finishOperation } from '../executeStep/completion';+import { prepareStepInput } from '../executeStep/prepare';+import { readQueuedMessagesFlag } from '../operationControl';++const { steerQueueLength } = vi.hoisted(() => ({ steerQueueLength: vi.fn() }));+vi.mock('@/server/services/redis', () => ({+ redisService: { steerQueue: { length: steerQueueLength } },+}));++const stateOf = (overrides: Partial<AgentState> = {}) =>+ ({+ origin: { topicId: 'tpc-1' },+ status: 'done',+ stepCount: 3,+ ...overrides,+ }) as AgentState;++describe('server-side steer queue in the step loop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ steerQueueLength.mockResolvedValue(0);+ });++ describe('readQueuedMessagesFlag', () => {+ const depsWithFlag = (flag: boolean) =>+ ({+ coordinator: { hasQueuedMessages: vi.fn().mockResolvedValue(flag) },+ userId: 'user-1',+ }) as any;++ it('hands the turn back when follow-ups wait in the server queue', async () => {+ steerQueueLength.mockResolvedValue(2);++ await expect(+ readQueuedMessagesFlag(+ depsWithFlag(false),+ 'op-1',+ 1,+ stateOf({ origin: { threadId: 'thd-1', topicId: 'tpc-1' } }),+ ),+ ).resolves.toBe(true);+ expect(steerQueueLength).toHaveBeenCalledWith(+ { threadId: 'thd-1', topicId: 'tpc-1', userId: 'user-1' },+ 'op-1',+ );+ });++ it('keeps honouring the client flag without reading the queue', async () => {+ await expect(readQueuedMessagesFlag(depsWithFlag(true), 'op-1', 1, stateOf())).resolves.toBe(+ true,+ );+ expect(steerQueueLength).not.toHaveBeenCalled();+ });++ it('never hands a child run back for its parent conversation queue', async () => {+ steerQueueLength.mockResolvedValue(1);+ const child = stateOf({+ origin: { lineage: { isSubAgent: true, parentOperationId: 'op-0' }, topicId: 'tpc-1' },+ });++ await expect(readQueuedMessagesFlag(depsWithFlag(false), 'op-1', 1, child)).resolves.toBe(+ false,+ );+ expect(steerQueueLength).not.toHaveBeenCalled();+ });++ it('keeps the run going when the queue cannot be read', async () => {+ steerQueueLength.mockRejectedValue(new Error('redis down'));++ await expect(readQueuedMessagesFlag(depsWithFlag(false), 'op-1', 1, stateOf())).resolves.toBe(+ false,+ );+ });+ });++ describe('finishOperation', () => {+ const createDeps = (startQueuedFollowUp = vi.fn().mockResolvedValue(undefined)) => {+ const order: string[] = [];+ const deps = {+ completionLifecycle: {+ dispatchHooks: vi.fn(async () => {+ order.push('hooks');+ }),+ emitSignalEvents: vi.fn().mockResolvedValue([]),+ extractErrorMessage: vi.fn(),+ },+ delegate: {+ startQueuedFollowUp: vi.fn(async (params) => {+ order.push('followUp');+ return startQueuedFollowUp(params);+ }),+ },+ determineCompletionReason: (state: AgentState) =>+ state.status === 'done' ? 'done' : state.status,+ recordInterventionLifecycleCompletion: vi.fn(),+ traceRecorder: { finalize: vi.fn(), flushPartial: vi.fn() },+ tryResumeParentFromAsyncTool: vi.fn(),+ userId: 'user-1',+ } as any;+ return { deps, order };+ };++ const finish = (deps: any, state: AgentState) =>+ finishOperation(deps, {+ invokeAgentSpan: { setAttributes: vi.fn() } as any,+ operationId: 'op-1',+ stepIndex: 3,+ stepResult: { events: [], newState: state } as any,+ });++ it('starts the queued follow-ups once the finished run released the topic', async () => {+ const { deps, order } = createDeps();+ const state = stateOf();++ await finish(deps, state);++ expect(deps.delegate.startQueuedFollowUp).toHaveBeenCalledWith({+ operationId: 'op-1',+ scope: { threadId: null, topicId: 'tpc-1', userId: 'user-1' },+ });+ expect(order).toEqual(['hooks', 'followUp']);+ });++ it.each(['error', 'interrupted', 'waiting_for_human'] as const)(+ 'leaves the queue alone when the run ends as %s',+ async (status) => {+ const { deps } = createDeps();++ await finish(deps, stateOf({ status }));++ expect(deps.delegate.startQueuedFollowUp).not.toHaveBeenCalled();+ },+ );++ it('leaves the parent conversation queue to the parent run', async () => {+ const { deps } = createDeps();++ await finish(deps, stateOf({ origin: { lineage: { isSubAgent: true }, topicId: 'tpc-1' } }));+ await finish(deps, stateOf({ origin: {} }));++ expect(deps.delegate.startQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('does not fail the finishing step when the follow-up cannot start', async () => {+ const { deps } = createDeps(vi.fn().mockRejectedValue(new Error('boom')));++ await expect(finish(deps, stateOf())).resolves.toBeUndefined();+ });+ });++ describe('prepareStepInput β joining follow-ups before the next LLM call', () => {+ const toolMessages = [+ { content: '', id: 'msg-assistant', role: 'assistant', tools: [{ id: 'call-1' }] },+ { content: '391', id: 'msg-tool', parentId: 'msg-assistant', role: 'tool' },+ ];+ const refreshed = [...toolMessages, { content: 'follow-up', id: 'msg-steer', role: 'user' }];++ const createDeps = (injected?: { messageId: string }) =>+ ({+ computeDeviceContext: vi.fn().mockResolvedValue(undefined),+ humanIntervention: { process: vi.fn() },+ injectQueuedFollowUp: vi.fn().mockResolvedValue(injected),+ readQueuedMessagesFlag: vi.fn().mockResolvedValue(false),+ refreshMessagesFromDB: vi.fn().mockResolvedValue(refreshed),+ resolveAsyncToolResumeParentMessageId: vi.fn(),+ }) as any;++ const prepare = (deps: any, phase: string, messages: any[] = toolMessages) =>+ prepareStepInput(deps, {+ agentState: stateOf({ messages, status: 'running' } as any),+ params: {+ context: { payload: { parentMessageId: 'msg-tool' }, phase },+ operationId: 'op-1',+ stepIndex: 2,+ } as any,+ stepEntryMessages: undefined as any,+ });++ it.each(['tool_result', 'tools_batch_result', 'sub_agent_result', 'sub_agents_batch_result'])(+ 're-enters the LLM on the joined steer message after %s',+ async (phase) => {+ const deps = createDeps({ messageId: 'msg-steer' });++ const { currentContext, currentState } = await prepare(deps, phase);++ expect(deps.injectQueuedFollowUp).toHaveBeenCalledWith('op-1', 2, expect.anything());+ expect(currentContext).toMatchObject({+ payload: { parentMessageId: 'msg-steer' },+ phase: 'user_input',+ });+ expect(currentState.messages).toEqual(refreshed);+ },+ );++ it('keeps the decision point when nothing joined', async () => {+ const deps = createDeps(undefined);++ const { currentContext } = await prepare(deps, 'tool_result');++ expect(currentContext).toMatchObject({ phase: 'tool_result' });+ expect(deps.refreshMessagesFromDB).not.toHaveBeenCalled();+ });++ it('never splits an assistantβs tool calls from their results', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });++ await prepare(deps, 'llm_result');+ await prepare(deps, 'user_input');++ expect(deps.injectQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('lets the agent park for a tool still waiting for approval first', async () => {+ const deps = createDeps({ messageId: 'msg-steer' });+ const pending = [+ toolMessages[0],+ { ...toolMessages[1], pluginIntervention: { status: 'pending' } },+ ];++ await prepare(deps, 'tool_result', pending);++ expect(deps.injectQueuedFollowUp).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.tsindex 8efacab50b7..88d407d02aa 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts@@ -3,6 +3,7 @@ import { buildInvokeAgentResultAttributes } from '@lobechat/observability-otel/mimport debug from 'debug';import { logToolCallPc } from '../../formalObservation';+import { steerQueueScopeOf } from '../../steerQueueScope';import type { AgentRuntimeServiceContext } from '../types';import type { StepRunResult } from './runStep';@@ -12,15 +13,17 @@ const log = debug('lobe-server:agent-runtime-service');export type StepCompletionDeps = Pick<AgentRuntimeServiceContext,| 'completionLifecycle'+ | 'delegate'| 'determineCompletionReason'| 'recordInterventionLifecycleCompletion'| 'traceRecorder'| 'tryResumeParentFromAsyncTool'+ | 'userId'>;/*** The run stops here: emit the completion signals, dispatch the completion* hooks, record a parked intervention, re-check a just-parked async-tool- * barrier and finalize the trace.+ * barrier, finalize the trace and start the follow-ups queued behind it.*/export async function finishOperation(deps: StepCompletionDeps,@@ -105,4 +108,24 @@ export async function finishOperation(state: stepResult.newState,});logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason }));++ // Follow-ups the user queued behind this run start as the next turn right+ // here, instead of after the client hears the run ended and sends them+ // itself. Only after the hooks above: they persist the terminal row and+ // release the topic, which the next turn has to claim. A parked run keeps+ // its queue until it really ends; a failed or stopped one leaves it to the+ // user.+ const steerScope = steerQueueScopeOf(stepResult.newState, deps.userId);+ if (stepResult.newState.status === 'done' && steerScope && deps.delegate.startQueuedFollowUp) {+ try {+ await deps.delegate.startQueuedFollowUp({ operationId, scope: steerScope });+ } catch (error) {+ log(+ '[%s][%d] Starting queued follow-ups failed (non-fatal): %O',+ operationId,+ stepIndex,+ error,+ );+ }+ }}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.tsindex 1c9e2cac1c4..4dcf1ae8f43 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts@@ -48,6 +48,7 @@ export type ExecuteStepDeps = Pick<| 'expireClientLlmWait'| 'handleGroupMemberTimeout'| 'humanIntervention'+ | 'injectQueuedFollowUp'| 'parkForClientLlm'| 'publishSubAgentProgress'| 'queryStepEntryMessages'diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.tsindex a28150bb1a3..2d69bd41d68 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts@@ -1,7 +1,8 @@-import type {- AgentRunClientLlmWait,- AgentRuntimeContext,- AgentState,+import {+ type AgentRunClientLlmWait,+ type AgentRuntimeContext,+ type AgentState,+ findCurrentTurnPendingToolMessages,} from '@lobechat/agent-runtime';import { type ChatToolPayload } from '@lobechat/types';import debug from 'debug';@@ -15,11 +16,24 @@ import type { AgentRuntimeServiceContext } from '../types';const log = debug('lobe-server:agent-runtime-service');+/**+ * Decision points after which the agent calls the LLM again: the tool (or+ * sub-agent) results of the turn are all in, so a user message can join here+ * without splitting an assistant's tool calls from their results.+ */+const LLM_NEXT_PHASES = new Set([+ 'tool_result',+ 'tools_batch_result',+ 'sub_agent_result',+ 'sub_agents_batch_result',+]);+/** What this module reads off the service. */export type StepPrepareDeps = Pick<AgentRuntimeServiceContext,| 'computeDeviceContext'| 'humanIntervention'+ | 'injectQueuedFollowUp'| 'readQueuedMessagesFlag'| 'refreshMessagesFromDB'| 'resolveAsyncToolResumeParentMessageId'@@ -222,14 +236,45 @@ export async function prepareStepInput(}}- // Queued follow-ups live in the client's composer, not in this state.- // The client mirrors them into a flag; the agent reads it from the step- // context and hands the turn back at its next decision point, so the- // follow-up starts as the next turn instead of after the whole run.+ // A follow-up the user queued behind this run joins it here, right before+ // the next LLM call, so the model reads it on its next step instead of after+ // the whole run. Re-entered like an async-tool resume: messages refreshed+ // from the DB (which now hold the steer message) and a `user_input` phase+ // anchored on it. Not while a tool of this turn still waits for approval β+ // the agent has to park for that first.+ if (+ currentContext &&+ !forcedFinishState &&+ LLM_NEXT_PHASES.has(currentContext.phase) &&+ findCurrentTurnPendingToolMessages(currentState.messages).length === 0+ ) {+ const injected = await deps.injectQueuedFollowUp(operationId, stepIndex, currentState);+ if (injected) {+ currentState = structuredClone(currentState);+ currentState.messages = await deps.refreshMessagesFromDB(currentState);+ currentState.lastModified = new Date().toISOString();+ currentContext = {+ ...currentContext,+ payload: { parentMessageId: injected.messageId },+ phase: 'user_input',+ } as AgentRuntimeContext;+ }+ }++ // Queued follow-ups that could not join (or arrived too late for this+ // decision point) live outside this state: in the client's composer,+ // which mirrors them into a flag, or in the server-side steer queue. The+ // agent reads either from the step context and hands the turn back at its+ // next decision point, so the follow-up starts as the next turn instead of+ // after the whole run.// This read is authoritative for the step: a value carried in on the// incoming context must not keep a hand-back the user has withdrawn.if (currentContext && !forcedFinishState) {- const hasQueuedMessages = await deps.readQueuedMessagesFlag(operationId, stepIndex);+ const hasQueuedMessages = await deps.readQueuedMessagesFlag(+ operationId,+ stepIndex,+ currentState,+ );if (hasQueuedMessages !== Boolean(currentContext.stepContext?.hasQueuedMessages)) {const stepContext = { ...currentContext.stepContext };if (hasQueuedMessages) stepContext.hasQueuedMessages = true;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.tsindex 926adabfd0a..9b8588ab160 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts@@ -70,6 +70,7 @@ import {acceptsMemberRuntimeEnd,controlCompletedToolResult,getOperationStatus,+ injectQueuedFollowUp,interruptOperation,isOperationInterrupted,readQueuedMessagesFlag,@@ -327,6 +328,7 @@ export class AgentRuntimeService {queryMessagesFromDB: (...args) => self.queryMessagesFromDB(...args),queryStepEntryMessages: (...args) => self.queryStepEntryMessages(...args),queryUiMessages: (...args) => self.queryUiMessages(...args),+ injectQueuedFollowUp: (...args) => self.injectQueuedFollowUp(...args),readQueuedMessagesFlag: (...args) => self.readQueuedMessagesFlag(...args),recordInterventionLifecycleCompletion: (...args) =>self.recordInterventionLifecycleCompletion(...args),@@ -383,6 +385,10 @@ export class AgentRuntimeService {return setQueuedMessages(this.context, ...args);}+ private injectQueuedFollowUp(...args: MethodArgs<typeof injectQueuedFollowUp>) {+ return injectQueuedFollowUp(this.context, ...args);+ }+private readQueuedMessagesFlag(...args: MethodArgs<typeof readQueuedMessagesFlag>) {return readQueuedMessagesFlag(this.context, ...args);}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex f74103830cd..d2b4cbb023d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -2,12 +2,15 @@ import type { AgentState } from '@lobechat/agent-runtime';import { isParkedStatus } from '@lobechat/agent-runtime';import debug from 'debug';+import { redisService } from '@/server/services/redis';+import { hookDispatcher } from '../hooks';import {controlDeferredToolResult,type DeferredToolResultControlInput,loadDurableToolResultHooks,} from '../hooks/deferredToolResultControl';+import { steerQueueScopeOf } from '../steerQueueScope';import {type AgentStepContinuation,type OperationStatusResult,@@ -31,6 +34,7 @@ export type OperationControlDeps = Pick<| 'baseURL'| 'completionLifecycle'| 'coordinator'+ | 'delegate'| 'endExpiredClientLlmWait'| 'messageModel'| 'queueService'@@ -240,23 +244,69 @@ export async function setQueuedMessages(}/**- * Read the queued-messages flag for a step. A failed read keeps the run- * going: the follow-up still starts once the run ends, exactly as it did- * before the flag existed, instead of failing the step.+ * Whether follow-ups wait behind this run: the client's flag, or the+ * follow-ups queued server-side on the run's conversation (a top-level run+ * only β see `steerQueueScopeOf`). A failed read keeps the run going: the+ * follow-up still starts once the run ends, exactly as it did before the flag+ * existed, instead of failing the step.*/export async function readQueuedMessagesFlag(deps: OperationControlDeps,operationId: string,stepIndex: number,+ state?: AgentState,): Promise<boolean> {try {- return await deps.coordinator.hasQueuedMessages(operationId);+ if (await deps.coordinator.hasQueuedMessages(operationId)) return true;++ const scope = state && steerQueueScopeOf(state, deps.userId);+ return scope ? (await redisService.steerQueue.length(scope, operationId)) > 0 : false;} catch (error) {log('[%s][%d] Queued messages flag read failed: %O', operationId, stepIndex, error);return false;}}+/**+ * Join the follow-ups queued behind this run into it, right before its next+ * LLM call, instead of ending the run and starting another for them. Hands off+ * to the owning layer (merge, access check, persisting the user message); the+ * caller re-enters the LLM on top of that message.+ *+ * Best-effort: any failure leaves the follow-ups queued, and the run hands its+ * turn back for them at this decision point as it did before.+ *+ * @returns the user message the follow-ups became, or `undefined` when none+ * were taken in+ */+export async function injectQueuedFollowUp(+ deps: OperationControlDeps,+ operationId: string,+ stepIndex: number,+ state: AgentState,+): Promise<{ messageId: string } | undefined> {+ const scope = steerQueueScopeOf(state, deps.userId);+ if (!scope || !deps.delegate.injectQueuedFollowUp) return;++ try {+ if ((await redisService.steerQueue.length(scope, operationId)) === 0) return;++ const injected = await deps.delegate.injectQueuedFollowUp({ operationId, scope, state });+ if (injected) {+ log(+ '[%s][%d] Joined queued follow-ups into the run as %s',+ operationId,+ stepIndex,+ injected.messageId,+ );+ }+ return injected;+ } catch (error) {+ log('[%s][%d] Joining queued follow-ups failed: %O', operationId, stepIndex, error);+ return;+ }+}+/** Review out-of-band results before any subsequent history read can expose them. */export async function controlCompletedToolResult(deps: OperationControlDeps,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.tsindex c7a8cfb4b42..238c36d72fe 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts@@ -1,4 +1,4 @@-import type { Agent, GeneralAgentConfig } from '@lobechat/agent-runtime';+import type { Agent, AgentState, GeneralAgentConfig } from '@lobechat/agent-runtime';import type { ISnapshotStore } from '@lobechat/agent-tracing';import {type ExecSubAgentParams,@@ -16,6 +16,7 @@ import type {import type { IStreamEventManager } from '@/server/modules/AgentRuntime/types';import type { MessageService } from '@/server/services/message';import type { QueueService } from '@/server/services/queue';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';import type { ToolExecutionService } from '@/server/services/toolExecution';import type { CompletionLifecycle } from '../CompletionLifecycle';@@ -74,6 +75,7 @@ import type {acceptsMemberRuntimeEnd,controlCompletedToolResult,getOperationStatus,+ injectQueuedFollowUp,interruptOperation,isOperationInterrupted,readQueuedMessagesFlag,@@ -143,6 +145,29 @@ export interface AgentRuntimeDelegate {* placeholder before resuming the parked parent operation.*/execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;+ /**+ * The run reached a decision point right before its next LLM call: take the+ * follow-ups the user queued behind it into the run as a steer user message+ * (merged, access re-checked, persisted where a composer send would anchor+ * it). Follow-ups that cannot join a running turn (attachments, a different+ * agent, tool / skill selections) stay queued for the hand-back. Resolves to+ * `undefined` when nothing was taken in.+ */+ injectQueuedFollowUp?: (params: {+ operationId: string;+ scope: SteerQueueScope;+ state: AgentState;+ }) => Promise<{ messageId: string } | undefined>;+ /**+ * A top-level run just finished: start the follow-ups the user queued behind+ * it as the next turn (the composer pipeline, with `steer`). Resolves to+ * `undefined` when nothing was queued or the start failed β the follow-ups+ * then stay queued; it never throws into the finishing step.+ */+ startQueuedFollowUp?: (params: {+ operationId: string;+ scope: SteerQueueScope;+ }) => Promise<{ operationId: string } | undefined>;/*** Re-check that an Agent Share visitor run is STILL authorized to continue,* called on EVERY step. Without it, a revocation that lands mid-run (link β@@ -276,6 +301,7 @@ export interface AgentRuntimeServiceContext {getPendingInterventions: Bound<typeof getPendingInterventions>;handleGroupMemberTimeout: Bound<typeof handleGroupMemberTimeout>;readonly humanIntervention: HumanInterventionHandler;+ injectQueuedFollowUp: Bound<typeof injectQueuedFollowUp>;interruptOperation: Bound<typeof interruptOperation>;isCallSubAgentToolMessage: Bound<typeof isCallSubAgentToolMessage>;isOperationInterrupted: Bound<typeof isOperationInterrupted>;diff --git a/apps/server/src/services/agentRuntime/steerQueueScope.ts b/apps/server/src/services/agentRuntime/steerQueueScope.tsnew file mode 100644index 00000000000..fdd9cf52a43--- /dev/null+++ b/apps/server/src/services/agentRuntime/steerQueueScope.ts@@ -0,0 +1,19 @@+import type { AgentState } from '@lobechat/agent-runtime';++import type { SteerQueueScope } from '@/server/services/redis/steerQueue';++/**+ * The queue a run's owner fills behind it: that user's follow-ups on the run's+ * conversation surface, or `undefined` for a run nobody types behind β a child+ * run (sub-agent, group member) or one with no topic.+ */+export const steerQueueScopeOf = (+ state: AgentState,+ userId: string,+): SteerQueueScope | undefined => {+ const origin = state.origin;+ if (!origin?.topicId) return;+ if (origin.lineage?.isSubAgent || origin.lineage?.parentOperationId) return;++ return { threadId: origin.threadId ?? null, topicId: origin.topicId, userId };+};diff --git a/apps/server/src/services/aiAgent/composerRun.test.ts b/apps/server/src/services/aiAgent/composerRun.test.tsnew file mode 100644index 00000000000..13fd0c98ca1--- /dev/null+++ b/apps/server/src/services/aiAgent/composerRun.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it, vi } from 'vitest';++import { startComposerRun } from './composerRun';++vi.mock('@/server/services/task/topicRun', () => ({+ TopicRunService: vi.fn().mockImplementation(function () {+ return { resolveOwnableRun: vi.fn().mockResolvedValue(undefined) };+ }),+}));+vi.mock('@/server/services/task/runHooks', () => ({ createTaskRunHooks: vi.fn() }));++const run = (supersedeLiveRun?: boolean) => {+ const execAgent = vi.fn().mockResolvedValue({ operationId: 'op-2' });+ return startComposerRun(+ {+ aiAgentService: { execAgent, interruptTask: vi.fn() } as any,+ db: {} as any,+ supersedeLiveRun,+ userId: 'user-1',+ },+ { agentId: 'agt-1', appContext: { topicId: 'tpc-1' }, prompt: 'hi' },+ ).then(() => execAgent.mock.calls[0][0]);+};++describe('startComposerRun', () => {+ it('starts like a person at the composer by default, taking the topic over', async () => {+ await expect(run()).resolves.toMatchObject({ interactiveStart: true });+ });++ it('waits on the topic instead of interrupting its run when told not to supersede', async () => {+ await expect(run(false)).resolves.toMatchObject({ interactiveStart: false });+ });+});diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.tsnew file mode 100644index 00000000000..ce216729b25--- /dev/null+++ b/apps/server/src/services/aiAgent/composerRun.ts@@ -0,0 +1,192 @@+import { RequestTrigger } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import type { LobeChatDatabase } from '@/database/type';+import { createTaskRunHooks } from '@/server/services/task/runHooks';+import { type TopicRunReopenOutcome, TopicRunService } from '@/server/services/task/topicRun';++import type { AiAgentService } from './index';+import type { InternalExecAgentParams } from './types';++/**+ * The request fields a composer send carries into {@link startComposerRun}.+ * Mirrors the fresh-send part of the `aiAgent.execAgent` input; the resume+ * fields are passed through untouched for the router's own resume-shaped sends.+ */+export type ComposerRunRequest = Pick<+ InternalExecAgentParams,+ | 'acceptsFileWorks'+ | 'acceptsMemberRuntimeEnd'+ | 'agentId'+ | 'appContext'+ | 'autoStart'+ | 'clientIds'+ | 'clientProtocol'+ | 'deviceId'+ | 'existingMessageIds'+ | 'fileIds'+ | 'includeFinalState'+ | 'llmExecutor'+ | 'localDeviceId'+ | 'mentionedAgents'+ | 'parentMessageId'+ | 'prompt'+ | 'replacesOperationId'+ | 'resumeApproval'+ | 'resumeApprovals'+ | 'resumeToolResult'+ | 'selectedSkillIds'+ | 'selectedToolIds'+ | 'slug'+ | 'sourceOperationId'+ | 'steer'+ | 'trigger'+ | 'userInterventionConfig'+> & {+ clientOperations?: NonNullable<InternalExecAgentParams['clientRunSnapshot']>['operations'];+};++export interface ComposerRunContext {+ aiAgentService: Pick<AiAgentService, 'execAgent' | 'interruptTask'>;+ /** Server-derived request provenance; never client-passable. */+ clientIp?: string;+ db: LobeChatDatabase;+ /**+ * Whether the start may take the topic over from a run that still owns it,+ * as a person at the composer does (default). A server-started follow-up+ * passes `false`: it waits on the topic instead, and fails when another run+ * owns it, rather than interrupting that run.+ */+ supersedeLiveRun?: boolean;+ userAgent?: string;+ userId: string;+ workspaceId?: string | null;+}++/**+ * Start a run the way the composer does: a message typed into a conversation.+ *+ * Shared by `aiAgent.execAgent` and the server-side drain of queued follow-ups,+ * so a follow-up the server starts on the user's behalf gets exactly what the+ * same send from the composer would β including the Task run hand-over below.+ * Callers authorize the request before calling this.+ */+export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerRunRequest) => {+ const { appContext, parentMessageId } = input;++ // A message typed into a Task's own conversation continues that Task's+ // run β and the composer dispatches it, not `runTask`. Everything the Task+ // side needs for this run is attached here: the hook that settles the run+ // when it ends, and the reopen that puts its run row back in flight.+ // Without the pair, an answered run is invisible to the Task: the run card+ // keeps the finished state of the run it replied to, `cancelTopic` refuses+ // to stop the live one, and the detail page stops polling for it.+ const topicRunService = new TopicRunService(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);+ const topicRun = appContext?.topicId+ ? await topicRunService.resolveOwnableRun(appContext.topicId)+ : undefined;+ // Recorded on the operation-created boundary and acted on once the+ // dispatch has returned.+ let reopenOutcome: TopicRunReopenOutcome | undefined;++ const result = await ctx.aiAgentService.execAgent({+ acceptsFileWorks: input.acceptsFileWorks,+ acceptsMemberRuntimeEnd: input.acceptsMemberRuntimeEnd,+ agentId: input.agentId,+ appContext,+ autoStart: input.autoStart,+ clientIds: input.clientIds,+ clientRunSnapshot: {+ operations: input.clientOperations ?? [],+ replacesOperationId: input.replacesOperationId,+ },+ clientProtocol: input.clientProtocol,+ includeFinalState: input.includeFinalState,+ llmExecutor: input.llmExecutor,+ // This path serves the composer (`aiAgentService.execAgentTask`).+ // The client already queues follow-ups behind a live run and shows the+ // user a tray; refusing here would only make the message disappear.+ interactiveStart: ctx.supersedeLiveRun ?? true,+ // Propagate the originating request's client IP / user agent into the run+ // so downstream LLM-call metadata can carry them for auditing and spend+ // attribution. These are server-derived from the tRPC context and are+ // intentionally not part of the client-passable input schema.+ clientIp: ctx.clientIp,+ deviceId: input.deviceId,+ localDeviceId: input.localDeviceId,+ existingMessageIds: input.existingMessageIds,+ ...(topicRun && {+ hooks: createTaskRunHooks({+ db: ctx.db,+ taskId: topicRun.taskId,+ taskIdentifier: topicRun.taskIdentifier,+ trigger: 'manual',+ // The Task's creator, not the caller: the completion callback+ // resolves the workspace from `tasks.createdByUserId`, so passing a+ // workspace member would make that lookup miss and strand the run.+ userId: topicRun.ownerUserId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),+ // Before the run's first step, so a short run can never finish β and+ // have its own completion hook settle the row β ahead of the reopen.+ onOperationCreated: async (operationId) => {+ reopenOutcome = await topicRunService+ .reopen({ link: topicRun, operationId })+ .catch((error) => {+ console.error('[startComposerRun] failed to reopen the task run: %O', error);+ return 'refused' as const;+ });+ },+ }),+ fileIds: input.fileIds,+ mentionedAgents: input.mentionedAgents,+ parentMessageId,+ prompt: input.prompt,+ replacesOperationId: input.replacesOperationId,+ // When parentMessageId is provided, this is a regeneration/continue or a+ // human-approval resume β either way, skip user message creation.+ resume: !!parentMessageId,+ resumeApproval: input.resumeApproval,+ resumeApprovals: input.resumeApprovals,+ resumeToolResult: input.resumeToolResult,+ selectedSkillIds: input.selectedSkillIds,+ selectedToolIds: input.selectedToolIds,+ slug: input.slug,+ sourceOperationId: input.sourceOperationId,+ steer: input.steer,+ trigger: input.trigger ?? RequestTrigger.Chat,+ userAgent: ctx.userAgent,+ userInterventionConfig: input.userInterventionConfig,+ });+ // The run was dispatched but it did not take the Task's run row over. Two+ // ways that happens: the Task was retired while the run was starting (the+ // write failed or there is no row to keep honest), or a concurrent send on+ // the same topic won the reopen and already owns the row. In both cases+ // the run's hooks are already attached for the whole run, and+ // `onTopicComplete` settles the topic row by id without checking which+ // operation owns it β so letting this run continue would let the loser+ // settle a row it does not own, finishing the winner's run ahead of it and+ // overwriting its handoff/result. Stop it, exactly as the runner stops the+ // run it dispatched under the same race.+ if (reopenOutcome === 'refused' || reopenOutcome === 'already-running') {+ const lostTheRow = reopenOutcome === 'already-running';+ const stop = await ctx.aiAgentService+ .interruptTask({ operationId: result.operationId })+ .catch((error) => {+ console.error('[startComposerRun] failed to stop the orphaned task run: %O', error);+ return undefined;+ });+ // Same confirmation gate as `TaskService.interruptTaskOperation`.+ const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;+ throw new TRPCError({+ code: stopped ? 'CONFLICT' : 'INTERNAL_SERVER_ERROR',+ message: stopped+ ? lostTheRow+ ? 'Another run is already live on this task; this duplicate send was stopped.'+ : 'This task run could not be recorded while it was starting; the run was stopped.'+ : `This task run could not be recorded while it was starting, and stopping it (operation ${result.operationId}) could not be confirmed.`,+ });+ }++ return result;+};diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex de515af2067..b059ae1e77f 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -49,6 +49,7 @@ import type {} from '@/server/services/agentRuntime/types';import { ComposioService } from '@/server/services/composio';import { MarketService } from '@/server/services/market';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';import { createGraphAwareAgentFactory } from './helpers/agentFactory';import { InterventionController } from './intervention/InterventionController';@@ -65,6 +66,9 @@ import { scheduleAgentRun } from './pipeline/scheduleAgentRun';import { runWithTopicStart, type TopicStartDeps } from './pipeline/topicStart';import type { RunFacts } from './runFacts';import { resolveAgentSenderFromOperation } from './sourceAttribution';+import { startQueuedFollowUp } from './steerQueue';+import { injectQueuedFollowUp } from './steerQueue/inject';+import { findOwnLiveRuns } from './steerQueue/liveRuns';import type { SubAgentLlmRelayRequest } from './subAgentLlmRelay';import { closeSubAgentLlmRelay, openSubAgentLlmRelay } from './subAgentLlmRelay';import type { SubAgentRunDeps } from './subAgentRuns';@@ -162,6 +166,8 @@ export class AiAgentService {execSubAgent: this.execSubAgent,execVirtualSubAgent: this.execVirtualSubAgent,execGroupMember: this.execGroupMember,+ injectQueuedFollowUp: this.injectQueuedFollowUp,+ startQueuedFollowUp: this.startQueuedFollowUp,verifyShareRunStillAuthorized: this.verifyShareRunStillAuthorized,},workspaceId: wsId,@@ -232,6 +238,8 @@ export class AiAgentService {return {agentOperationModel: this.agentOperationModel,agentRuntimeService: this.agentRuntimeService,+ findOwnLiveRuns: (scope) =>+ findOwnLiveRuns({ db: this.db, workspaceId: this.workspaceId }, scope),interruptTask: (p) => this.interruptTask(p),topicModel: this.topicModel,userId: this.userId,@@ -623,6 +631,36 @@ export class AiAgentService {shareId: string;}): Promise<boolean> => AgentShareModel.isRunStillAuthorized(this.db, params);+ /**+ * `AgentRuntimeDelegate.startQueuedFollowUp` implementation β see+ * `startQueuedFollowUp` in `./steerQueue`.+ *+ * Arrow field (not a method) so it stays bound when handed to+ * AgentRuntimeService.+ */+ /**+ * `AgentRuntimeDelegate.injectQueuedFollowUp` implementation β see+ * `injectQueuedFollowUp` in `./steerQueue/inject`.+ *+ * Arrow field (not a method) so it stays bound when handed to+ * AgentRuntimeService.+ */+ injectQueuedFollowUp = async (params: {+ operationId: string;+ scope: SteerQueueScope;+ state: AgentState;+ }) =>+ injectQueuedFollowUp(+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ params,+ );++ startQueuedFollowUp = async (params: { operationId: string; scope: SteerQueueScope }) =>+ startQueuedFollowUp(+ { aiAgentService: this, db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ params,+ );+/*** Execute an agent in an isolated Thread context.*diff --git a/apps/server/src/services/aiAgent/pipeline/topicStart.test.ts b/apps/server/src/services/aiAgent/pipeline/topicStart.test.tsnew file mode 100644index 00000000000..e9df880aaa6--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/topicStart.test.ts@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TopicStartReservationError } from '../topicStartReservation';+import { runWithTopicStart, type TopicStartDeps } from './topicStart';++const fence = vi.hoisted(() => ({ acquire: vi.fn(), release: vi.fn() }));+vi.mock('@/server/services/redis', () => ({ redisService: { threadStartFence: fence } }));++const onThread = (extra: Record<string, unknown> = {}) =>+ ({+ agentId: 'agt-1',+ appContext: { threadId: 'thd-1', topicId: 'tpc-1' },+ prompt: 'hi',+ ...extra,+ }) as any;++const queuedSuccessor = onThread({ interactiveStart: false, steer: true });+const composerSend = onThread({ interactiveStart: true });++const createDeps = (liveRuns: string[] = []) =>+ ({+ findOwnLiveRuns: vi.fn().mockResolvedValue(liveRuns),+ userId: 'user-1',+ }) as unknown as TopicStartDeps;++describe('runWithTopicStart β existing threads', () => {+ const run = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ fence.acquire.mockResolvedValue('held');+ fence.release.mockResolvedValue(undefined);+ run.mockResolvedValue({ operationId: 'op-new' });+ });++ it('starts a queued follow-up inside the thread fence once no run is live there', async () => {+ const deps = createDeps();++ await expect(runWithTopicStart(deps, queuedSuccessor, run)).resolves.toEqual({+ operationId: 'op-new',+ });+ expect(deps.findOwnLiveRuns).toHaveBeenCalledWith({+ threadId: 'thd-1',+ topicId: 'tpc-1',+ userId: 'user-1',+ });+ expect(fence.release).toHaveBeenCalledWith('thd-1', expect.any(String));+ });++ it('refuses a queued follow-up when the user already started a run on the thread', async () => {+ await expect(+ runWithTopicStart(createDeps(['op-user']), queuedSuccessor, run),+ ).rejects.toBeInstanceOf(TopicStartReservationError);+ expect(run).not.toHaveBeenCalled();+ expect(fence.release).toHaveBeenCalled();+ });++ it.each(['busy', 'unavailable'] as const)(+ 'refuses a queued follow-up when the fence is %s, never starting next to another start',+ async (state) => {+ fence.acquire.mockResolvedValue(state);++ await expect(runWithTopicStart(createDeps(), queuedSuccessor, run)).rejects.toBeInstanceOf(+ TopicStartReservationError,+ );+ expect(run).not.toHaveBeenCalled();+ expect(fence.release).not.toHaveBeenCalled();+ },+ );++ it('never refuses a person at the composer, even when the fence stays busy', async () => {+ fence.acquire.mockResolvedValue('busy');+ const deps = createDeps(['op-other']);++ await expect(runWithTopicStart(deps, composerSend, run)).resolves.toEqual({+ operationId: 'op-new',+ });+ expect(deps.findOwnLiveRuns).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/topicStart.ts b/apps/server/src/services/aiAgent/pipeline/topicStart.tsindex 2d9f82a64fa..dbbe1a5915b 100644--- a/apps/server/src/services/aiAgent/pipeline/topicStart.ts+++ b/apps/server/src/services/aiAgent/pipeline/topicStart.ts@@ -12,6 +12,8 @@ import {type SupersedeKind,type SupersedeRecord,} from '@/server/services/agentRuntime/foregroundOperation';+import { redisService } from '@/server/services/redis';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';import { acquireTopicStartReservation, TopicStartReservationError } from '../topicStartReservation';import type { InternalExecAgentParams } from '../types';@@ -21,6 +23,8 @@ const log = debug('lobe-server:ai-agent-service');export interface TopicStartDeps {agentOperationModel: AgentOperationModel;agentRuntimeService: AgentRuntimeService;+ /** The caller's live top-level runs on one surface (see `steerQueue/liveRuns`). */+ findOwnLiveRuns?: (scope: SteerQueueScope) => Promise<string[]>;interruptTask: (params: {operationId?: string;topicId?: string;@@ -157,6 +161,52 @@ export const recordSupersede = async (}};+/** How long a start waits for another start on the same thread to finish. */+const THREAD_START_WAIT_MS = 3000;++/**+ * Start a run on an existing thread inside the thread's start fence.+ *+ * A server-started queued follow-up (`steer`, not interactive) must hold the+ * fence and finds no other live run of the user's on the thread, as one step β+ * otherwise it fails and its follow-ups go back to the queue, instead of+ * starting next to a run the user just sent. A person at the composer only+ * waits briefly for the fence and is never refused.+ */+const startOnThread = async (+ deps: TopicStartDeps,+ params: InternalExecAgentParams,+ surface: { threadId: string; topicId: string },+ run: (params: InternalExecAgentParams) => Promise<ExecAgentResult>,+): Promise<ExecAgentResult> => {+ const queuedSuccessor = !!params.steer && !params.interactiveStart;+ const owner = `thread-start-${nanoid()}`;+ const fence = await redisService.threadStartFence.acquire(+ surface.threadId,+ owner,+ THREAD_START_WAIT_MS,+ );++ try {+ if (queuedSuccessor) {+ if (fence !== 'held') {+ throw new TopicStartReservationError(+ `Thread ${surface.threadId} is busy starting another run`,+ );+ }+ const live = (await deps.findOwnLiveRuns?.({ ...surface, userId: deps.userId })) ?? [];+ if (live.length > 0) {+ throw new TopicStartReservationError(+ `Thread ${surface.threadId} already has a live run (${live[0]})`,+ );+ }+ }+ return await run(params);+ } finally {+ if (fence === 'held') await redisService.threadStartFence.release(surface.threadId, owner);+ }+};+/*** Claim the topic for a new run, then start it through `run`.*@@ -197,8 +247,9 @@ export const runWithTopicStart = async (// advance the topic's main spine. They may start while their parent// operation owns `runningOperation` (for example callAgent/callSubAgent),// so making them wait for the topic-start claim deadlocks the child start.- if (!topicId || (params.appContext?.threadId && !isInterventionThreadStart)) {- return run(params);+ if (!topicId) return run(params);+ if (params.appContext?.threadId && !isInterventionThreadStart) {+ return startOnThread(deps, params, { threadId: params.appContext.threadId, topicId }, run);}const replacesOperationId = isInterventionThreadStartdiff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.tsnew file mode 100644index 00000000000..e26b0cdbe19--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts@@ -0,0 +1,235 @@+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mergeQueuedFollowUps, type QueuedFollowUp, startQueuedFollowUp } from './index';++const {+ assertCanUseAgentRunConversation,+ assertCanUseWorkspaceAgent,+ drain,+ restore,+ startComposerRun,+} = vi.hoisted(() => ({+ assertCanUseAgentRunConversation: vi.fn(),+ assertCanUseWorkspaceAgent: vi.fn(),+ drain: vi.fn(),+ restore: vi.fn(),+ startComposerRun: vi.fn(),+}));++const { boundOperations, findOwnLiveRuns, isRunAlive, settle } = vi.hoisted(() => ({+ boundOperations: vi.fn(),+ settle: vi.fn(),+ findOwnLiveRuns: vi.fn(),+ isRunAlive: vi.fn(),+}));+vi.mock('@/server/services/redis', () => ({+ redisService: { steerQueue: { boundOperations, drain, restore, settle } },+}));+vi.mock('./liveRuns', () => ({ findOwnLiveRuns, isRunAlive }));+vi.mock('../composerRun', () => ({ startComposerRun }));+vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({+ assertCanUseWorkspaceAgent,+}));+vi.mock('@/server/routers/lambda/aiAgent/guards', () => ({+ assertCanUseAgentRunConversation,+}));++const followUp = (id: string, createdAt: number, request: Partial<QueuedFollowUp['request']>) =>+ ({+ audit: { clientIp: `ip-${id}` },+ createdAt,+ id,+ request: { agentId: 'agt-1', appContext: { topicId: 'tpc-1' }, prompt: id, ...request },+ userId: 'user-1',+ }) as QueuedFollowUp;++const ctx = { aiAgentService: {} as any, db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };+const finished = (scope: { threadId?: string | null; topicId: string }) => ({+ operationId: 'op-1',+ scope: { threadId: null, userId: 'user-1', ...scope },+});++describe('mergeQueuedFollowUps', () => {+ it('joins the texts in queue order and keeps every attachment and selection', () => {+ const merged = mergeQueuedFollowUps([+ followUp('second', 2, { fileIds: ['f2'], selectedSkillIds: ['s1'] }),+ followUp('first', 1, {+ fileIds: ['f1'],+ mentionedAgents: [{ id: 'a1', name: 'A' }],+ selectedSkillIds: ['s1'],+ }),+ ]);++ expect(merged.prompt).toBe('first\n\nsecond');+ expect(merged.fileIds).toEqual(['f1', 'f2']);+ expect(merged.selectedSkillIds).toEqual(['s1']);+ expect(merged.mentionedAgents).toEqual([{ id: 'a1', name: 'A' }]);+ });++ it('runs with the newest settings and drops per-send client ids once merged', () => {+ const merged = mergeQueuedFollowUps([+ followUp('a', 1, { clientIds: { userMessageId: 'u-a' } as any, deviceId: 'old' }),+ followUp('b', 2, { clientIds: { userMessageId: 'u-b' } as any, deviceId: 'new' }),+ ]);++ expect(merged.deviceId).toBe('new');+ expect(merged.clientIds).toBeUndefined();+ expect(+ mergeQueuedFollowUps([followUp('a', 1, { clientIds: { x: 1 } as any })]).clientIds,+ ).toEqual({ x: 1 });+ });+});++describe('startQueuedFollowUp', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ drain.mockResolvedValue([]);+ restore.mockResolvedValue(undefined);+ settle.mockResolvedValue(undefined);+ boundOperations.mockResolvedValue({ operationIds: ['op-1', 'op-ended', 'op-live'], total: 3 });+ findOwnLiveRuns.mockResolvedValue(['op-1']);+ isRunAlive.mockImplementation(+ async (_ctx: unknown, _user: string, id: string) => id !== 'op-ended',+ );+ assertCanUseWorkspaceAgent.mockResolvedValue(undefined);+ assertCanUseAgentRunConversation.mockResolvedValue(undefined);+ startComposerRun.mockResolvedValue({ operationId: 'op-2' });+ });++ it('starts the drained follow-ups as one steered turn on the same surface', async () => {+ drain.mockResolvedValue([followUp('a', 1, {}), followUp('b', 2, {})]);++ await expect(+ startQueuedFollowUp(ctx, finished({ threadId: 'thd-1', topicId: 'tpc-1' })),+ ).resolves.toEqual({ operationId: 'op-2' });++ expect(drain).toHaveBeenCalledWith(+ { threadId: 'thd-1', topicId: 'tpc-1', userId: 'user-1' },+ 'op-1',+ // Only the run confirmed ended; the live one and the finishing run itself are not orphans.+ ['op-ended'],+ expect.any(String),+ );+ expect(isRunAlive).not.toHaveBeenCalledWith(expect.anything(), 'user-1', 'op-1');+ expect(startComposerRun).toHaveBeenCalledWith(+ expect.objectContaining({ clientIp: 'ip-b', supersedeLiveRun: false, userId: 'user-1' }),+ expect.objectContaining({+ appContext: { threadId: 'thd-1', topicId: 'tpc-1' },+ prompt: 'a\n\nb',+ steer: true,+ }),+ );+ // Delivered: the slots the drain reserved are free again.+ expect(settle).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'tpc-1' }),+ expect.any(String),+ );+ });++ it('puts the follow-ups back when the next turn cannot start', async () => {+ const entries = [followUp('a', 1, {})];+ drain.mockResolvedValue(entries);+ startComposerRun.mockRejectedValue(new Error('topic busy'));++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();++ expect(settle).toHaveBeenCalledWith(+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },+ expect.any(String),+ entries.map((e) => e.id),+ );+ });++ it('never starts a follow-up someone else queued under the run owner', async () => {+ drain.mockResolvedValue([{ ...followUp('a', 1, {}), userId: 'intruder' }]);++ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));++ expect(startComposerRun).not.toHaveBeenCalled();+ });++ it('re-checks access before the queued turn starts, and drops it when access was revoked', async () => {+ drain.mockResolvedValue([+ followUp('a', 1, { appContext: { groupId: 'grp-1', topicId: 'tpc-1' } }),+ ]);+ assertCanUseWorkspaceAgent.mockRejectedValue(new TRPCError({ code: 'FORBIDDEN' }));++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();++ expect(assertCanUseWorkspaceAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt-1',+ groupId: 'grp-1',+ userId: 'user-1',+ workspaceId: 'ws-1',+ }),+ );+ expect(startComposerRun).not.toHaveBeenCalled();+ expect(settle).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ );+ });++ it('keeps the follow-ups when the access check itself fails', async () => {+ const entries = [followUp('a', 1, {})];+ drain.mockResolvedValue(entries);+ assertCanUseAgentRunConversation.mockRejectedValue(new Error('connection reset'));++ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));++ expect(startComposerRun).not.toHaveBeenCalled();+ expect(settle).toHaveBeenCalledWith(+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },+ expect.any(String),+ entries.map((e) => e.id),+ );+ });++ it('skips the live-run lookup when nothing is queued', async () => {+ boundOperations.mockResolvedValue({ operationIds: [], total: 0 });++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();++ expect(isRunAlive).not.toHaveBeenCalled();+ expect(drain).not.toHaveBeenCalled();+ });++ it('never interrupts a run the user started while the topic was free; leaves the follow-ups to it', async () => {+ const entries = [followUp('a', 1, {})];+ drain.mockResolvedValue(entries);+ findOwnLiveRuns.mockResolvedValue(['op-1', 'op-newer']);++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();++ expect(startComposerRun).not.toHaveBeenCalled();+ expect(settle).toHaveBeenCalledWith(+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },+ expect.any(String),+ entries.map((e) => e.id),+ );+ });++ it('reads a drain back once with the same id when its response was lost', async () => {+ drain+ .mockRejectedValueOnce(new Error('command timed out'))+ .mockResolvedValueOnce([followUp('a', 1, {})]);++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toEqual({+ operationId: 'op-2',+ });++ const [first, second] = drain.mock.calls;+ expect(second[3]).toBe(first[3]);+ });++ it('does not fail when returning follow-ups fails β their batch lapses back on its own', async () => {+ drain.mockResolvedValue([followUp('a', 1, {})]);+ startComposerRun.mockRejectedValue(new Error('topic busy'));+ settle.mockRejectedValue(new Error('redis down'));++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.tsnew file mode 100644index 00000000000..bbe9602a967--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts@@ -0,0 +1,293 @@+import { randomUUID } from 'node:crypto';++import { TRPCError } from '@trpc/server';+import debug from 'debug';++import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';+import { assertCanUseAgentRunConversation } from '@/server/routers/lambda/aiAgent/guards';+import { redisService } from '@/server/services/redis';+import type { SteerQueueEntry, SteerQueueScope } from '@/server/services/redis/steerQueue';++import { type ComposerRunContext, type ComposerRunRequest, startComposerRun } from '../composerRun';+import { findOwnLiveRuns, isRunAlive } from './liveRuns';++const log = debug('lobe-server:steer-queue');++/**+ * The part of a composer send a queued follow-up keeps: a fresh message typed+ * into a running conversation. Resume, regenerate and supersede fields have no+ * meaning for a turn that starts later, so they are never stored.+ */+export type QueuedFollowUpRequest = Omit<+ ComposerRunRequest,+ | 'autoStart'+ | 'clientOperations'+ | 'existingMessageIds'+ | 'includeFinalState'+ | 'parentMessageId'+ | 'replacesOperationId'+ | 'resumeApproval'+ | 'resumeApprovals'+ | 'resumeToolResult'+ | 'sourceOperationId'+ | 'steer'+>;++export interface QueuedFollowUp extends SteerQueueEntry {+ /** Server-derived provenance of the request that queued it. */+ audit?: { clientIp?: string; userAgent?: string };+ request: QueuedFollowUpRequest;+ /** Who queued it; only the run owner's own follow-ups are started for them. */+ userId: string;+}++const uniq = <T>(items: T[]) => [...new Set(items)];++/**+ * Fold every waiting follow-up into one request, the way the client merges its+ * own queue: the texts in queue order, every attachment and selection kept.+ * The newest entry decides the run settings (model, device, approvals), since+ * that is what the user last had selected when they queued.+ */+export const mergeQueuedFollowUps = (entries: QueuedFollowUp[]): QueuedFollowUpRequest => {+ const sorted = [...entries].sort((a, b) => a.createdAt - b.createdAt);+ const latest = sorted.at(-1)!.request;++ const fileIds = uniq(sorted.flatMap((entry) => entry.request.fileIds ?? []));+ const selectedSkillIds = uniq(sorted.flatMap((entry) => entry.request.selectedSkillIds ?? []));+ const selectedToolIds = uniq(sorted.flatMap((entry) => entry.request.selectedToolIds ?? []));+ const mentionedAgents = [+ ...new Map(+ sorted.flatMap((entry) => entry.request.mentionedAgents ?? []).map((a) => [a.id, a]),+ ).values(),+ ];++ return {+ ...latest,+ // Client-minted row ids belong to one optimistic send; a merged send+ // creates rows none of the queued sends announced.+ clientIds: sorted.length === 1 ? latest.clientIds : undefined,+ fileIds: fileIds.length ? fileIds : undefined,+ mentionedAgents: mentionedAgents.length ? mentionedAgents : undefined,+ prompt: sorted.map((entry) => entry.request.prompt).join('\n\n'),+ selectedSkillIds: selectedSkillIds.length ? selectedSkillIds : undefined,+ selectedToolIds: selectedToolIds.length ? selectedToolIds : undefined,+ };+};++/** Guard outcomes that mean the user may no longer start this turn. */+const DENIED_CODES = new Set<TRPCError['code']>(['FORBIDDEN', 'NOT_FOUND']);++/**+ * A drained batch: the follow-ups a run took, held in Redis under `drainId`+ * until the run acknowledges or returns them (see `steerQueue.settle`).+ */+export interface DrainedFollowUps {+ drainId: string;+ entries: QueuedFollowUp[];+}++/**+ * Some or all drained follow-ups did not go anywhere: put them back at the+ * head of the queue, unbound. Never throws β if Redis cannot be reached the+ * batch goes back on its own once its lease lapses.+ */+export const returnFollowUps = async (+ scope: SteerQueueScope,+ drained: Pick<DrainedFollowUps, 'drainId'>,+ entries: QueuedFollowUp[],+ reason: unknown,+) => {+ if (entries.length === 0) return;+ console.error(+ '[steerQueue] %d queued follow-ups go back to the queue: %O',+ entries.length,+ reason,+ );+ await redisService.steerQueue+ .settle(+ scope,+ drained.drainId,+ entries.map((entry) => entry.id),+ )+ .catch((error) => {+ console.error(+ '[steerQueue] returning %d follow-ups for topic %s failed; they return when batch %s lapses: %O',+ entries.length,+ scope.topicId,+ drained.drainId,+ error,+ );+ });+};++/**+ * The drained batch reached its destination (or was dropped): acknowledge it.+ * Never throws β an unacknowledged batch lapses back into the queue, which+ * would only redeliver it.+ */+export const ackFollowUps = async (+ scope: SteerQueueScope,+ drained: Pick<DrainedFollowUps, 'drainId'>,+) => {+ await redisService.steerQueue.settle(scope, drained.drainId).catch((error) => {+ console.error('[steerQueue] acknowledging batch %s failed: %O', drained.drainId, error);+ });+};++/**+ * Take the follow-ups `operationId` owns β queued behind it, returned unbound+ * after a failed delivery, or orphaned by a run that ended while Redis was out+ * of reach β into a drained batch. Another live run on the surface keeps its+ * own. The queue is the run owner's (the scope carries their user id); a+ * foreign entry is never acted on under this user's authority if one got here.+ *+ * A drain whose response was lost is read back once with the same id; if that+ * fails too, the batch (if it was taken) goes back when its lease lapses.+ *+ * @throws when Redis is unavailable: the entries stay queued+ */+export const drainOwnFollowUps = async (+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,+ scope: SteerQueueScope,+ operationId: string,+): Promise<DrainedFollowUps> => {+ const drainId = randomUUID();+ const { operationIds, total } = await redisService.steerQueue.boundOperations(scope);+ if (total === 0) return { drainId, entries: [] };++ // Entries behind another run are left to it unless that run is confirmed+ // ended β checked one by one, so a run that starts meanwhile (and the+ // follow-ups queued behind it) is never mistaken for an orphan.+ const ended: string[] = [];+ for (const id of operationIds) {+ if (id !== operationId && !(await isRunAlive(ctx, ctx.userId, id))) ended.push(id);+ }+ const drain = () =>+ redisService.steerQueue.drain<QueuedFollowUp>(scope, operationId, ended, drainId);+ const drained = await drain().catch((error) => {+ log('[%s] Drain %s failed, reading it back once: %O', operationId, drainId, error);+ return drain();+ });++ const entries = drained.filter((entry) => entry.userId === ctx.userId);+ if (entries.length < drained.length) {+ // Acknowledged along with the rest of the batch; never sent.+ log('[%s] Dropped %d foreign queued follow-ups', operationId, drained.length - entries.length);+ }+ if (entries.length === 0 && drained.length > 0) await ackFollowUps(scope, { drainId });+ return { drainId, entries };+};++/**+ * `append` authorized a follow-up when it was queued; access can be revoked+ * while the run is still going. Re-check it the way `aiAgent.execAgent` checks+ * every run. `denied` means the follow-ups are no longer this user's to send β+ * putting them back would only retry a refused send; any other failure of the+ * check says nothing about access and is thrown.+ */+export const checkFollowUpAccess = async (+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,+ request: QueuedFollowUpRequest,+ scope: SteerQueueScope,+): Promise<'allowed' | 'denied'> => {+ try {+ await assertCanUseWorkspaceAgent({+ agentId: request.agentId,+ db: ctx.db,+ groupId: request.appContext?.groupId,+ slug: request.slug,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ await assertCanUseAgentRunConversation({+ db: ctx.db,+ topicId: scope.topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return 'allowed';+ } catch (error) {+ if (error instanceof TRPCError && DENIED_CODES.has(error.code)) return 'denied';+ throw error;+ }+};++/**+ * A top-level run just finished on `scope`: start the follow-ups still queued+ * behind it as the next turn, here on the server, instead of waiting for a+ * client to drain them. A native run takes most follow-ups into itself before+ * its next LLM call (`injectQueuedFollowUp`); this picks up the rest β those+ * that arrived after its last decision point or could not join a running turn β+ * and serves heterogeneous agents (Claude Code, Codex) when they finish.+ *+ * Drain is atomic, so exactly one finishing run takes a given follow-up. When+ * the next turn cannot start, the follow-ups go back to the head of the queue β+ * the next run that ends picks them up, and the client can still list them.+ * When the user lost access to the agent or conversation meanwhile, they are+ * dropped instead.+ *+ * @returns the started operation, or `undefined` when nothing was queued or the+ * start failed+ */+export const startQueuedFollowUp = async (+ ctx: ComposerRunContext,+ params: { operationId: string; scope: SteerQueueScope },+): Promise<{ operationId: string } | undefined> => {+ const { scope } = params;++ const drained = await drainOwnFollowUps(ctx, scope, params.operationId);+ const { entries } = drained;+ if (entries.length === 0) return;++ const request = mergeQueuedFollowUps(entries);+ const audit = entries.at(-1)!.audit;++ try {+ if ((await checkFollowUpAccess(ctx, request, scope)) === 'denied') {+ console.error(+ '[startQueuedFollowUp] dropped %d queued follow-ups after %s: access revoked',+ entries.length,+ params.operationId,+ );+ await ackFollowUps(scope, drained);+ return;+ }++ // The topic was free for a moment between the finished run and this+ // start; a send the user made in that gap now owns the surface. Never+ // interrupt it: the follow-ups go back, unbound, and that run takes them.+ const others = (await findOwnLiveRuns(ctx, scope)).filter((id) => id !== params.operationId);+ if (others.length > 0) {+ await returnFollowUps(scope, drained, entries, `left to live run ${others[0]}`);+ return;+ }+ } catch (error) {+ await returnFollowUps(scope, drained, entries, error);+ return;+ }++ try {+ const result = await startComposerRun(+ // Not superseding: should a send still win the surface before this start+ // claims it, the start fails and the follow-ups go back to the queue.+ { ...ctx, clientIp: audit?.clientIp, supersedeLiveRun: false, userAgent: audit?.userAgent },+ {+ ...request,+ appContext: { ...request.appContext, threadId: scope.threadId, topicId: scope.topicId },+ steer: true,+ },+ );+ log(+ '[%s] Started queued follow-up as %s (%d merged)',+ params.operationId,+ result.operationId,+ entries.length,+ );+ await ackFollowUps(scope, drained);+ return { operationId: result.operationId };+ } catch (error) {+ await returnFollowUps(scope, drained, entries, error);+ return;+ }+};diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.tsnew file mode 100644index 00000000000..dd3c5fc6e2f--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts@@ -0,0 +1,216 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { QueuedFollowUp } from './index';+import { canJoinRunningTurn, injectQueuedFollowUp } from './inject';++const mocks = vi.hoisted(() => ({+ assertCanUseAgentRunConversation: vi.fn(),+ assertCanUseWorkspaceAgent: vi.fn(),+ boundOperations: vi.fn(),+ create: vi.fn(),+ drain: vi.fn(),+ isRunAlive: vi.fn(),+ resolveParentId: vi.fn(),+ restore: vi.fn(),+ settle: vi.fn(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: {+ steerQueue: {+ boundOperations: mocks.boundOperations,+ drain: mocks.drain,+ restore: mocks.restore,+ settle: mocks.settle,+ },+ },+}));+vi.mock('./liveRuns', () => ({ isRunAlive: mocks.isRunAlive }));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return { create: mocks.create };+ }),+}));+vi.mock('../pipeline/resolveUserMessageParentId', () => ({+ createUserTurnAnchor: () => ({ resolveParentId: mocks.resolveParentId }),+}));+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' }, prompt: id, ...request },+ userId: 'user-1',+ }) as QueuedFollowUp;++const state = { origin: { agentId: 'agt-1', topicId: 'tpc-1' }, status: 'running' } as AgentState;+const scope = { threadId: null, topicId: 'tpc-1', userId: 'user-1' };+const ctx = { db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };+const inject = () => injectQueuedFollowUp(ctx, { operationId: 'op-1', scope, state });++describe('canJoinRunningTurn', () => {+ it('takes plain text for the agent that is running', () => {+ expect(canJoinRunningTurn(followUp('a', 1), state)).toBe(true);+ });++ it.each([+ ['an attachment', { fileIds: ['f1'] }],+ ['a selected tool', { selectedToolIds: ['t1'] }],+ ['a selected skill', { selectedSkillIds: ['s1'] }],+ ['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(canJoinRunningTurn(followUp('a', 1, request), state)).toBe(false);+ });+});++describe('canJoinRunningTurn β per-turn settings', () => {+ const configured = {+ binding: { device: { id: 'dev-1' } },+ host: {+ acceptsFileWorks: true,+ clientProtocol: 2,+ llmExecutor: {+ capabilities: ['llm_relay@1'],+ channelOperationId: 'op-0',+ clientId: 'tab-1',+ providers: ['ollama'],+ },+ },+ origin: { agentId: 'agt-1', topicId: 'tpc-1' },+ principal: { policy: { userIntervention: { allowList: ['a'], approvalMode: 'manual' } } },+ status: 'running',+ } as unknown as AgentState;+ const same = {+ acceptsFileWorks: true,+ clientProtocol: 2 as const,+ deviceId: 'dev-1',+ llmExecutor: { clientId: 'tab-1', providers: ['ollama'], capabilities: ['llm_relay@1'] },+ userInterventionConfig: { approvalMode: 'manual' as const, allowList: ['a'] },+ };++ it('joins when every stated setting is the running turnβs, in any key order', () => {+ expect(canJoinRunningTurn(followUp('a', 1, same), configured)).toBe(true);+ expect(canJoinRunningTurn(followUp('a', 1, { acceptsFileWorks: true }), configured)).toBe(true);+ });++ it.each([+ ['another device', { deviceId: 'dev-2' }],+ ['another local device hint', { localDeviceId: 'dev-2' }],+ ['another LLM executor', { llmExecutor: { ...same.llmExecutor, clientId: 'tab-2' } }],+ ['another wire protocol', { clientProtocol: 1 as const }],+ ['another approval mode', { userInterventionConfig: { approvalMode: 'auto-run' as const } }],+ ['other stream features', { acceptsFileWorks: false }],+ ])('holds a follow-up sent with %s for the next turn', (_label, change) => {+ expect(canJoinRunningTurn(followUp('a', 1, { ...same, ...change }), configured)).toBe(false);+ });+});++describe('injectQueuedFollowUp', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.drain.mockResolvedValue([]);+ mocks.restore.mockResolvedValue(undefined);+ mocks.settle.mockResolvedValue(undefined);+ mocks.boundOperations.mockResolvedValue({ operationIds: ['op-1'], total: 1 });+ mocks.isRunAlive.mockResolvedValue(true);+ mocks.resolveParentId.mockResolvedValue('msg-assistant');+ mocks.create.mockResolvedValue({ id: 'msg-steer' });+ mocks.assertCanUseWorkspaceAgent.mockResolvedValue(undefined);+ mocks.assertCanUseAgentRunConversation.mockResolvedValue(undefined);+ });++ it('joins the queued follow-ups into the run as one steer user message', async () => {+ mocks.drain.mockResolvedValue([followUp('first', 1), followUp('second', 2)]);++ await expect(inject()).resolves.toEqual({ messageId: 'msg-steer' });++ expect(mocks.drain).toHaveBeenCalledWith(scope, 'op-1', [], expect.any(String));+ expect(mocks.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt-1',+ content: 'first\n\nsecond',+ metadata: expect.objectContaining({ steer: true }),+ parentId: 'msg-assistant',+ role: 'user',+ topicId: 'tpc-1',+ }),+ );+ expect(mocks.settle).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ );+ // Delivered into the run: the reserved slots are free again.+ expect(mocks.settle).toHaveBeenCalledWith(scope, expect.any(String));+ });++ it('keeps queue order: joins the leading follow-ups and puts the rest back', async () => {+ const held = [followUp('with-file', 2, { fileIds: ['f1'] }), followUp('after', 3)];+ mocks.drain.mockResolvedValue([followUp('plain', 1), ...held]);++ await expect(inject()).resolves.toEqual({ messageId: 'msg-steer' });++ expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ content: 'plain' }));+ expect(mocks.settle).toHaveBeenCalledWith(+ scope,+ expect.any(String),+ held.map((e) => e.id),+ );+ });++ it('joins nothing when the first follow-up needs a turn of its own', async () => {+ const entries = [followUp('with-file', 1, { fileIds: ['f1'] })];+ mocks.drain.mockResolvedValue(entries);++ await expect(inject()).resolves.toBeUndefined();++ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.settle).toHaveBeenCalledWith(+ scope,+ expect.any(String),+ entries.map((e) => e.id),+ );+ });++ it('puts the follow-ups back when the message cannot be persisted', async () => {+ const entries = [followUp('a', 1)];+ mocks.drain.mockResolvedValue(entries);+ mocks.create.mockRejectedValue(new Error('db down'));++ await expect(inject()).resolves.toBeUndefined();++ expect(mocks.settle).toHaveBeenCalledWith(+ scope,+ expect.any(String),+ entries.map((e) => e.id),+ );+ });++ it('drops follow-ups whose sender lost access while the run went on', async () => {+ const { TRPCError } = await import('@trpc/server');+ mocks.drain.mockResolvedValue([followUp('a', 1)]);+ mocks.assertCanUseWorkspaceAgent.mockRejectedValue(new TRPCError({ code: 'FORBIDDEN' }));++ await expect(inject()).resolves.toBeUndefined();++ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.settle).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.tsnew file mode 100644index 00000000000..ca3965bbaea--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts@@ -0,0 +1,156 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';++import { MessageModel } from '@/database/models/message';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';++import type { ComposerRunContext } from '../composerRun';+import { createUserTurnAnchor } from '../pipeline/resolveUserMessageParentId';+import { buildUserTurnMetadata } from '../pipeline/userTurnMetadata';+import {+ ackFollowUps,+ checkFollowUpAccess,+ drainOwnFollowUps,+ mergeQueuedFollowUps,+ type QueuedFollowUp,+ returnFollowUps,+} from './index';++const log = debug('lobe-server:steer-queue');++/** Key-order-independent form of a settings value, for comparing two of them. */+const canonical = (value: unknown): string =>+ JSON.stringify(value, (_key, v) =>+ v && typeof v === 'object' && !Array.isArray(v)+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b)))+ : v,+ );++/**+ * Whether the per-turn settings a follow-up was sent with are the ones the+ * running turn already uses. A joined follow-up only adds a message β it runs+ * on the run's device, executor, protocol and approval settings β so any+ * setting it states must match them; one it leaves out is inherited either+ * way.+ */+const matchesRunningTurnSettings = (+ request: QueuedFollowUp['request'],+ state: AgentState,+): boolean => {+ const runDeviceId = state.binding?.device?.id;+ if (request.deviceId && request.deviceId !== runDeviceId) return false;+ if (request.localDeviceId && request.localDeviceId !== runDeviceId) return false;++ if (request.clientProtocol && request.clientProtocol !== (state.host?.clientProtocol ?? 1)) {+ return false;+ }+ if (!!request.acceptsFileWorks !== !!state.host?.acceptsFileWorks) return false;++ if (request.llmExecutor) {+ // `channelOperationId` is server-set on the run's executor, never sent by a client.+ const { channelOperationId: _channel, ...runExecutor } = (state.host?.llmExecutor ??+ {}) as Record<string, unknown>;+ if (canonical(request.llmExecutor) !== canonical(runExecutor)) return false;+ }++ if (request.userInterventionConfig) {+ const runIntervention =+ state.principal?.policy?.userIntervention ?? state.userInterventionConfig;+ if (canonical(request.userInterventionConfig) !== canonical(runIntervention)) return false;+ }++ return true;+};++/**+ * Whether a follow-up can join the run that is already going: plain text for+ * the same agent, sent with the turn settings the run already has. Anything+ * that needs a turn configured for it β attachments, tool or skill selections,+ * @-mentions, another agent, a different device, executor, protocol or approval+ * setting β waits for the hand-back and starts as the next turn instead.+ */+export const canJoinRunningTurn = (entry: QueuedFollowUp, state: AgentState): boolean => {+ const { request } = entry;+ if (!request.prompt.trim()) return false;+ if (request.fileIds?.length) return false;+ if (request.selectedToolIds?.length || request.selectedSkillIds?.length) return false;+ if (request.mentionedAgents?.length) return false;++ const runAgentId = state.origin?.agentId;+ if (!request.agentId || !runAgentId || request.agentId !== runAgentId) return false;++ return matchesRunningTurnSettings(request, state);+};++/**+ * The run is at a decision point right before its next LLM call: take the+ * follow-ups queued behind it into the run as one steer user message, anchored+ * where a composer send would anchor it, so the model reads them on this very+ * step. The leading follow-ups that can join are taken (queue order is kept);+ * the rest go back to the head of the queue for the hand-back.+ *+ * @returns the persisted user message, or `undefined` when nothing joined+ */+export const injectQueuedFollowUp = async (+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,+ params: { operationId: string; scope: SteerQueueScope; state: AgentState },+): Promise<{ messageId: string } | undefined> => {+ const { operationId, scope, state } = params;++ const drained = await drainOwnFollowUps(ctx, scope, operationId);+ const { entries } = drained;+ if (entries.length === 0) return;++ const firstHeld = entries.findIndex((entry) => !canJoinRunningTurn(entry, state));+ const joining = firstHeld === -1 ? entries : entries.slice(0, firstHeld);+ const held = entries.slice(joining.length);+ // Back at the head, for the hand-back at the next decision point. Should+ // that fail, they stay in the batch and return when it lapses.+ await returnFollowUps(scope, drained, held, 'needs a turn of its own');+ if (joining.length === 0) return;++ const request = mergeQueuedFollowUps(joining);++ try {+ if ((await checkFollowUpAccess(ctx, request, scope)) === 'denied') {+ console.error(+ '[injectQueuedFollowUp] dropped %d queued follow-ups for %s: access revoked',+ joining.length,+ operationId,+ );+ await ackFollowUps(scope, drained);+ return;+ }++ const messageModel = new MessageModel(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);+ const groupId = request.appContext?.groupId ?? undefined;+ const parentId = await createUserTurnAnchor(messageModel, {+ allowShareVisitor: false,+ groupId,+ threadId: scope.threadId ?? null,+ topicId: scope.topicId,+ }).resolveParentId();++ const message = await messageModel.create({+ agentId: state.origin?.agentId,+ content: request.prompt,+ groupId,+ metadata: buildUserTurnMetadata({+ steer: true,+ trigger: request.trigger ?? RequestTrigger.Chat,+ }),+ parentId,+ role: 'user',+ threadId: scope.threadId ?? undefined,+ topicId: scope.topicId,+ });++ log('[%s] Joined %d queued follow-ups as %s', operationId, joining.length, message.id);+ await ackFollowUps(scope, drained);+ return { messageId: message.id };+ } catch (error) {+ await returnFollowUps(scope, drained, joining, error);+ return;+ }+};diff --git a/apps/server/src/services/aiAgent/steerQueue/liveRuns.ts b/apps/server/src/services/aiAgent/steerQueue/liveRuns.tsnew file mode 100644index 00000000000..2923591de86--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/liveRuns.ts@@ -0,0 +1,61 @@+import type { AgentOperationStatus } from '@lobechat/types';+import { and, desc, eq, inArray, isNull } from 'drizzle-orm';++import { TopicModel } from '@/database/models/topic';+import { agentOperations } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import type { SteerQueueScope } from '@/server/services/redis/steerQueue';++/** Statuses of a run that still owns its conversation, parked ones included. */+const LIVE_STATUSES: AgentOperationStatus[] = [+ 'idle',+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ 'waiting_for_client',+];++export interface LiveRunContext {+ db: LobeChatDatabase;+ workspaceId?: string | null;+}++/** The topic model's liveness rule; it only reads the operation id off the marker. */+export const isRunAlive = (ctx: LiveRunContext, userId: string, operationId: string) =>+ new TopicModel(ctx.db, userId, ctx.workspaceId ?? undefined).isRunningOperationAlive(ctx.db, {+ assistantMessageId: '',+ operationId,+ });++/**+ * The scope owner's live top-level runs on exactly this surface β the topic's+ * main spine or one thread. A follow-up queues behind one of them and that run+ * drains it; an entry bound to a run outside this set is an orphan any run on+ * the surface may take. Thread runs never claim the topic marker, so the+ * operation rows decide, with the topic model's liveness rule on top.+ */+export const findOwnLiveRuns = async (+ ctx: LiveRunContext,+ scope: SteerQueueScope,+): Promise<string[]> => {+ const candidates = await ctx.db+ .select({ id: agentOperations.id })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.topicId, scope.topicId),+ scope.threadId+ ? eq(agentOperations.threadId, scope.threadId)+ : isNull(agentOperations.threadId),+ isNull(agentOperations.parentOperationId),+ eq(agentOperations.userId, scope.userId),+ inArray(agentOperations.status, LIVE_STATUSES),+ ),+ )+ .orderBy(desc(agentOperations.createdAt))+ .limit(3);++ const live: string[] = [];+ for (const { id } of candidates) if (await isRunAlive(ctx, scope.userId, id)) live.push(id);+ return live;+};diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/steerQueue.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/steerQueue.test.tsnew file mode 100644index 00000000000..d723e5a789d--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/steerQueue.test.ts@@ -0,0 +1,94 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';++import { HeterogeneousAgentService } from '..';++const startQueuedFollowUp = vi.fn();++const createService = (+ operation: Record<string, unknown> | null,+ { withStarter = true }: { withStarter?: boolean } = {},+) => {+ const order: string[] = [];+ vi.spyOn(CompletionLifecycle.prototype, 'completeOperation').mockImplementation(async () => {+ order.push('complete');+ });+ startQueuedFollowUp.mockImplementation(async () => {+ order.push('followUp');+ });++ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ agentOperationModel: { findById: vi.fn(async () => operation) } as any,+ persistenceHandler: { finish: vi.fn(async () => undefined) } as any,+ snapshotStore: null,+ ...(withStarter && { startQueuedFollowUp }),+ streamEventManager: { publishStreamEvent: vi.fn(async () => 'ok') } as any,+ topicModel: {+ settleRunningOperation: vi.fn(async () => ({ status: 'settled' })),+ updateMetadata: vi.fn(async () => undefined),+ } as any,+ workspaceId: 'ws-1',+ });+ return { order, service };+};++const finish = (service: HeterogeneousAgentService, result: 'cancelled' | 'error' | 'success') =>+ service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-1',+ result,+ topicId: 'tpc-1',+ });++describe('HeterogeneousAgentService.heteroFinish β queued follow-ups', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('starts the follow-ups queued behind a finished run once its completion settled', async () => {+ const { order, service } = createService({ metadata: {}, threadId: 'thd-1' });++ await finish(service, 'success');++ expect(startQueuedFollowUp).toHaveBeenCalledWith({+ operationId: 'op-1',+ scope: { threadId: 'thd-1', topicId: 'tpc-1', userId: 'user-1' },+ });+ expect(order).toEqual(['complete', 'followUp']);+ });++ it.each(['error', 'cancelled'] as const)('leaves the queue alone on %s', async (result) => {+ const { service } = createService({ metadata: {} });++ await finish(service, result);++ expect(startQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('leaves the parent conversation queue to the parent run', async () => {+ const { service } = createService({ metadata: {}, parentOperationId: 'op-0' });++ await finish(service, 'success');++ expect(startQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('keeps the finish acknowledged when the follow-up cannot start', async () => {+ const { service } = createService({ metadata: {} });+ startQueuedFollowUp.mockRejectedValue(new Error('boom'));++ await expect(finish(service, 'success')).resolves.toBeUndefined();+ });++ it('leaves the queue alone when its caller supplied no way to start a turn', async () => {+ const { service } = createService({ metadata: {} }, { withStarter: false });++ await expect(finish(service, 'success')).resolves.toBeUndefined();+ expect(startQueuedFollowUp).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 2486bf56e20..efa5f8ea514 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -26,6 +26,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 type { SteerQueueScope } from '@/server/services/redis/steerQueue';import { instantiateVerifyPlanOnStart } from '@/server/services/verify';import {@@ -163,6 +164,16 @@ export interface HeterogeneousAgentServiceOptions {persistenceHandler?: HeterogeneousPersistenceHandler;/** Inject a snapshot store (used by tests); defaults to the env-resolved store. */snapshotStore?: ISnapshotStore | null;+ /**+ * Start the follow-ups queued behind a finished top-level run as its next+ * turn. Supplied by the caller: that start is the composer pipeline of+ * AiAgentService, which itself dispatches heterogeneous runs through this+ * service. Without it a finished run leaves its queue alone.+ */+ startQueuedFollowUp?: (params: {+ operationId: string;+ scope: SteerQueueScope;+ }) => Promise<unknown>;/** Inject a pre-built manager (used by tests). */streamEventManager?: IStreamEventManager;/** Inject a pre-built TopicModel (used by tests for the resume helper). */@@ -191,6 +202,7 @@ export class HeterogeneousAgentService {private readonly db: LobeChatDatabase;private readonly messageModel: MessageModel;private readonly persistenceHandler: HeterogeneousPersistenceHandler;+ private readonly queuedFollowUpStarter?: HeterogeneousAgentServiceOptions['startQueuedFollowUp'];private readonly streamEventManager: IStreamEventManager;private readonly topicModel: TopicModel;private readonly traceRecorder: HeteroTraceRecorder;@@ -206,6 +218,7 @@ export class HeterogeneousAgentService {this.userId = userId;const workspaceId = options.workspaceId;this.workspaceId = workspaceId;+ this.queuedFollowUpStarter = options.startQueuedFollowUp;this.agentOperationModel =options.agentOperationModel ?? new AgentOperationModel(db, userId, workspaceId);this.messageModel = new MessageModel(db, userId, workspaceId);@@ -432,6 +445,9 @@ export class HeterogeneousAgentService {let isolationThreadId: string | undefined;let orchestrationRole: 'member' | 'supervisor' | undefined;let staleActiveOperationId: string | undefined;+ // Where the user's follow-ups queue: unknown (and never drained) until the+ // operation row says this is a top-level run.+ let steerScope: SteerQueueScope | undefined;// The operation row is the durable lifecycle owner. The frontend may have// already consumed the in-stream terminal event and cleared the topic's@@ -445,6 +461,10 @@ export class HeterogeneousAgentService {assistantMessageId = metadata.assistantMessageId;}isolationThreadId = operation?.threadId ?? undefined;+ // A child run (group member, sub-agent) is not where the user types.+ if (operation && !operation.parentOperationId) {+ steerScope = { threadId: operation.threadId ?? null, topicId, userId: this.userId };+ }} catch (err) {log('heteroFinish: failed to load operation lifecycle metadata (non-fatal): %O', err);}@@ -705,6 +725,26 @@ export class HeterogeneousAgentService {completionReason,);log('heteroFinish: dispatched completion lifecycle for op=%s result=%s', operationId, result);++ // 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.+ if (result === 'success' && steerScope) await this.startQueuedFollowUp(operationId, steerScope);+ }++ /**+ * Start the follow-ups queued behind a finished top-level run. Never throws:+ * the run's own completion is already settled, and the follow-ups stay+ * queued when they cannot start.+ */+ private async startQueuedFollowUp(operationId: string, scope: SteerQueueScope): Promise<void> {+ if (!this.queuedFollowUpStarter) return;+ try {+ await this.queuedFollowUpStarter({ operationId, scope });+ } catch (err) {+ log('heteroFinish: starting queued follow-ups failed (non-fatal): %O', err);+ }}/**diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.mdindex 2a1365e6c66..bd1e629a094 100644--- a/apps/server/src/services/redis/README.md+++ b/apps/server/src/services/redis/README.md@@ -7,6 +7,9 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.callers may request a freshness bound through the existing gateway API.- `skillTools.remember`: connection scoped tool lists, ten minutes; empty/failed results are not cached.- `workspaceRescan.claim`: one background scan per principal/device/directory for 45 seconds.+- `steerQueue`: follow-ups a user queued behind a running agent turn, per topic/thread, held for+ a day. Atomic append (bounded), drain and restore; the runtime drains it into the next turn.+ Writes return `undefined` without Redis, and the caller tells the client to send directly.- `agentSignal`: spend bounds for background self-iteration β classifier calls per user per UTCday, self-feedback declaration slots per topic, manual triggers per user per hour, and thedistinct topics one nightly review may cover. Its keys live in the `agent-signal` namespacediff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex b47e3163d53..0678f13632a 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -1,7 +1,16 @@import { agentSignal } from './agentSignal';import { deviceSystemInfo } from './deviceSystemInfo';import { skillTools } from './skillTools';+import { steerQueue } from './steerQueue';+import { threadStartFence } from './threadStartFence';import { workspaceRescan } from './workspaceRescan';/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */-export const redisService = { agentSignal, deviceSystemInfo, skillTools, workspaceRescan };+export const redisService = {+ agentSignal,+ deviceSystemInfo,+ skillTools,+ steerQueue,+ threadStartFence,+ workspaceRescan,+};diff --git a/apps/server/src/services/redis/steerQueue.test.ts b/apps/server/src/services/redis/steerQueue.test.tsnew file mode 100644index 00000000000..4bf2e8822be--- /dev/null+++ b/apps/server/src/services/redis/steerQueue.test.ts@@ -0,0 +1,292 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { redisService } from './index';+import { STEER_QUEUE_MAX_ENTRIES, SteerQueueWriteUnknownError } from './steerQueue';++const getRedisServiceClient = vi.hoisted(() => vi.fn());+vi.mock('./client', () => ({ getRedisServiceClient }));++/**+ * Emulates the queue's Lua scripts over in-memory state β the list, the taken+ * ids and the drained batches β reading each item's `<id>\t<behind>\n<json>`+ * header the way the scripts do. The scripts themselves run against a real+ * Redis in the PR's verification.+ */+const createFakeRedis = () => {+ const lists = new Map<string, string[]>();+ const ttls = new Map<string, number>();+ const taken = new Map<string, Set<string>>();+ const batches = new Map<string, Map<string, { expiry: number; items: string[] }>>();+ const listOf = (key: string) => lists.get(key) ?? [];+ const setOf = (key: string) => taken.get(key) ?? taken.set(key, new Set()).get(key)!;+ const batchesOf = (key: string) => batches.get(key) ?? batches.set(key, new Map()).get(key)!;+ const header = (item: string) => {+ const [id, behind] = item.slice(0, item.indexOf('\n')).split('\t');+ return { behind, id };+ };+ const takes = (item: string, op: string) => ['*', op].includes(header(item).behind);+ const unbind = (item: string) => `${header(item).id}\t*${item.slice(item.indexOf('\n'))}`;+ const inFlight = (key: string) =>+ [...batchesOf(key).values()].reduce((n, batch) => n + batch.items.length, 0);+ const reclaim = (qkey: string, pkey: string, now: number) => {+ for (const [id, batch] of batchesOf(pkey)) {+ if (batch.expiry <= now) {+ lists.set(qkey, [...batch.items.map(unbind), ...listOf(qkey)]);+ batchesOf(pkey).delete(id);+ }+ }+ };++ const evalScript = vi.fn(async (script: string, numKeys: number, ...rest: any[]) => {+ const keys = rest.slice(0, numKeys);+ const args = rest.slice(numKeys);+ const [key] = keys;+ const list = listOf(key);++ if (script.includes('reclaimLapsed(KEYS[1], KEYS[3]')) {+ const [, , pkey] = keys;+ const [op, drainId, now, lease, , ...ended] = args;+ reclaim(key, pkey, Number(now));+ const existing = batchesOf(pkey).get(drainId);+ if (existing) return existing.items;+ const current = listOf(key);+ const owned = (item: string) => takes(item, op) || ended.includes(header(item).behind);+ const out = current.filter(owned);+ if (out.length === 0) return [];+ for (const item of out) setOf(keys[1]).add(header(item).id);+ batchesOf(pkey).set(drainId, { expiry: Number(now) + Number(lease), items: out });+ lists.set(+ key,+ current.filter((item) => !owned(item)),+ );+ return out;+ }+ if (script.includes('local back = {}')) {+ const [, pkey] = keys;+ const [drainId, , ...ids] = args;+ const batch = batchesOf(pkey).get(drainId);+ if (!batch) return 0;+ const returned = batch.items.filter((item) => ids.includes(header(item).id));+ const kept = batch.items.filter((item) => !ids.includes(header(item).id));+ lists.set(key, [...returned.map(unbind), ...list]);+ if (ids.length === 0 || kept.length === 0) batchesOf(pkey).delete(drainId);+ else batch.items = kept;+ return returned.length;+ }+ if (script.includes('local count = 0')) {+ const [op, now] = args;+ const lapsed = [...batchesOf(keys[1]).values()]+ .filter((batch) => batch.expiry <= Number(now))+ .reduce((n, batch) => n + batch.items.length, 0);+ return list.filter((item) => takes(item, op)).length + lapsed;+ }+ if (script.includes('return inFlight(KEYS[1])')) return inFlight(key);+ if (script.includes('SISMEMBER')) {+ const [id, item, ttl, max] = args;+ if (setOf(keys[1]).has(id)) return -2;+ if (list.some((existing) => header(existing).id === id)) return list.length;+ if (list.length + inFlight(keys[2]) >= Number(max)) return -1;+ lists.set(key, [...list, item]);+ ttls.set(key, Number(ttl));+ return list.length + 1;+ }+ if (script.includes("redis.call('LREM'")) {+ const index = list.findIndex((item) => header(item).id === args[0]);+ if (index < 0) return 0;+ lists.set(key, list.toSpliced(index, 1));+ return 1;+ }+ if (script.includes('LRANGE')) return list;+ throw new Error(`unexpected script: ${script}`);+ });++ return { batches, client: { eval: evalScript }, lists, ttls };+};++const scope = { topicId: 'tpc-1', userId: 'u1' };+const entry = (id: string, createdAt = 1) => ({ createdAt, id, prompt: id });+const ids = async (s = scope) => (await redisService.steerQueue.list(s)).map((item) => item.id);+const q = redisService.steerQueue;++describe('redisService.steerQueue', () => {+ let redis: ReturnType<typeof createFakeRedis>;++ beforeEach(() => {+ redis = createFakeRedis();+ getRedisServiceClient.mockReset();+ getRedisServiceClient.mockImplementation(async () => redis.client);+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps one queue per user and conversation surface under the agentSteer scope', async () => {+ await q.append(scope, entry('a'), 'op-1');+ await q.append({ ...scope, threadId: 'thd-1' }, entry('b'), 'op-2');+ await q.append({ ...scope, userId: 'u2' }, entry('c'), 'op-3');++ expect(getRedisServiceClient).toHaveBeenCalledWith('agentSteer');+ expect([...redis.lists.keys()]).toEqual([+ 'follow_ups:v1:u1:tpc-1:main',+ 'follow_ups:v1:u1:tpc-1:thd-1',+ 'follow_ups:v1:u2:tpc-1:main',+ ]);+ expect(redis.ttls.get('follow_ups:v1:u1:tpc-1:main')).toBe(24 * 60 * 60);+ });++ it('drains what was queued behind the finishing run into a batch, once, in order', async () => {+ await q.append(scope, entry('a'), 'op-1');+ await q.append(scope, entry('b'), 'op-1');++ await expect(q.drain(scope, 'op-1', [], 'd1')).resolves.toEqual([entry('a'), entry('b')]);+ await expect(q.drain(scope, 'op-1', [], 'd2')).resolves.toEqual([]);+ expect(await ids()).toEqual([]);+ // Still held until acknowledged β it counts against the queue.+ await expect(q.boundOperations(scope)).resolves.toMatchObject({ total: 2 });++ await q.settle(scope, 'd1');+ await expect(q.boundOperations(scope)).resolves.toMatchObject({ total: 0 });+ });++ it('reads a drained batch back when its response was lost', async () => {+ await q.append(scope, entry('a'), 'op-1');+ await q.drain(scope, 'op-1', [], 'd1');++ await expect(q.drain(scope, 'op-1', [], 'd1')).resolves.toEqual([entry('a')]);+ });++ it('leaves follow-ups queued behind another live run on the surface to that run', async () => {+ await q.append(scope, entry('behind-1'), 'op-1');+ await q.append(scope, entry('behind-2'), 'op-2');++ await expect(q.length(scope, 'op-1')).resolves.toBe(1);+ await expect(q.drain(scope, 'op-1', [], 'd1')).resolves.toEqual([entry('behind-1')]);+ expect(await ids()).toEqual(['behind-2']);+ });++ it('lets the next run take follow-ups behind a run confirmed ended, and only those', async () => {+ await q.append(scope, entry('orphan'), 'op-ended');+ await q.append(scope, entry('behind-live'), 'op-live');++ await expect(q.boundOperations(scope)).resolves.toEqual({+ operationIds: ['op-ended', 'op-live'],+ total: 2,+ });+ await expect(q.drain(scope, 'op-next', ['op-ended'], 'd1')).resolves.toEqual([entry('orphan')]);+ expect(await ids()).toEqual(['behind-live']);+ });++ it('returns part of a batch to the head of the queue, unbound, and keeps the rest', async () => {+ await q.append(scope, entry('a'), 'op-1');+ await q.append(scope, entry('b'), 'op-1');+ await q.drain(scope, 'op-1', [], 'd1');+ await q.append(scope, entry('c'), 'op-2');++ await q.settle(scope, 'd1', ['b']);++ expect(await ids()).toEqual(['b', 'c']);+ // Unbound: any run on the surface takes it.+ await expect(q.length(scope, 'op-9')).resolves.toBe(1);+ await expect(q.boundOperations(scope)).resolves.toMatchObject({ total: 3 });+ await q.settle(scope, 'd1');+ await expect(q.boundOperations(scope)).resolves.toMatchObject({ total: 2 });+ });++ it('puts a batch nobody settled back into the queue once its lease lapses', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000_000);+ await q.append(scope, entry('a'), 'op-1');+ await q.drain(scope, 'op-1', [], 'd1');++ vi.setSystemTime(1_000_000 + 5 * 60 * 1000);+ // Counted for any run already, and drained back on the next drain.+ await expect(q.length(scope, 'op-9')).resolves.toBe(1);+ await expect(q.drain(scope, 'op-9', [], 'd2')).resolves.toEqual([entry('a')]);+ });++ it('counts drained batches against the bound, so a return never drops what was accepted', async () => {+ await q.append(scope, entry('old-1'), 'op-1');+ await q.append(scope, entry('old-2'), 'op-1');+ const drained = await q.drain(scope, 'op-1', [], 'd1');+ for (let i = 0; i < STEER_QUEUE_MAX_ENTRIES - 2; i++) {+ await expect(q.append(scope, entry(`new-${i}`), 'op-2')).resolves.toBe(i + 1);+ }+ await expect(q.append(scope, entry('over'), 'op-2')).resolves.toBe('full');++ await q.settle(+ scope,+ 'd1',+ drained.map((item) => item.id),+ );++ const queued = await ids();+ expect(queued).toHaveLength(STEER_QUEUE_MAX_ENTRIES);+ expect(queued.slice(0, 3)).toEqual(['old-1', 'old-2', 'new-0']);+ expect(queued.at(-1)).toBe(`new-${STEER_QUEUE_MAX_ENTRIES - 3}`);+ });++ it('appends an entry id at most once, also after a drain took it', async () => {+ await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBe(1);+ await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBe(1);+ await q.drain(scope, 'op-1', [], 'd1');++ await expect(q.append(scope, entry('a'), 'op-2')).resolves.toBe('taken');+ expect(await ids()).toEqual([]);+ });++ it('removes one entry by id and reports a miss once it is gone', async () => {+ await q.append(scope, entry('a'), 'op-1');+ await q.append(scope, entry('b'), 'op-1');++ await expect(q.remove(scope, 'a')).resolves.toBe(true);+ await expect(q.remove(scope, 'a')).resolves.toBe(false);+ expect(await ids()).toEqual(['b']);+ });++ it('refuses entries past the bound', async () => {+ for (let i = 0; i < STEER_QUEUE_MAX_ENTRIES; i++) {+ await q.append(scope, entry(`m${i}`), 'op-1');+ }++ await expect(q.append(scope, entry('over'), 'op-1')).resolves.toBe('full');+ });++ it('reports no Redis instead of an empty queue', async () => {+ getRedisServiceClient.mockResolvedValue(null);++ await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBeUndefined();+ await expect(q.length(scope, 'op-1')).resolves.toBe(0);+ await expect(q.drain(scope, 'op-1', [], 'd1')).rejects.toThrow('Redis is unavailable');+ await expect(q.settle(scope, 'd1')).rejects.toThrow('Redis is unavailable');+ await expect(q.boundOperations(scope)).rejects.toThrow('Redis is unavailable');+ });++ it('takes back an append that committed before its command failed, then falls back', async () => {+ const run = redis.client.eval.getMockImplementation()!;+ redis.client.eval.mockImplementationOnce(async (...args: any[]) => {+ await run(...(args as [string, number, string]));+ throw new Error('command timed out');+ });++ await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBeUndefined();+ expect(await ids()).toEqual([]);+ });++ it('reports an unknown outcome when the take-back finds nothing to remove', async () => {+ redis.client.eval.mockRejectedValueOnce(new Error('command timed out'));++ await expect(q.append(scope, entry('a'), 'op-1')).rejects.toBeInstanceOf(+ SteerQueueWriteUnknownError,+ );+ });++ it('reports an unknown outcome when the take-back fails too', async () => {+ redis.client.eval+ .mockRejectedValueOnce(new Error('command timed out'))+ .mockRejectedValueOnce(new Error('connection lost'));++ await expect(q.append(scope, entry('a'), 'op-1')).rejects.toBeInstanceOf(+ SteerQueueWriteUnknownError,+ );+ });+});diff --git a/apps/server/src/services/redis/steerQueue.ts b/apps/server/src/services/redis/steerQueue.tsnew file mode 100644index 00000000000..d5b63c3aa7c--- /dev/null+++ b/apps/server/src/services/redis/steerQueue.ts@@ -0,0 +1,475 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('agentSteer');++// A queue outlives a long run with room to spare; one abandoned by a run that+// never ended expires instead of being replayed into a later, unrelated turn.+const QUEUE_TTL_SECONDS = 24 * 60 * 60;++/**+ * How long a drained batch belongs to the run that took it. Delivery (joining+ * the run, or starting the next turn) finishes well within it; a batch its run+ * never settled β a crash, a timed-out drain, Redis gone between drain and+ * settle β goes back to the queue once it lapses, so nothing is lost.+ */+const PROCESSING_LEASE_MS = 5 * 60 * 1000;++/**+ * Upper bound on follow-ups waiting behind one turn, counting the ones a run+ * has taken but not yet delivered (they may still come back).+ */+export const STEER_QUEUE_MAX_ENTRIES = 20;++/**+ * One user's queue on one conversation surface: the topic's main spine, or one+ * of its threads. Keyed by the user too β workspace members can each have a run+ * on the same surface, and each run drains only its own owner's follow-ups.+ */+export interface SteerQueueScope {+ threadId?: string | null;+ topicId: string;+ userId: string;+}++export interface SteerQueueEntry {+ createdAt: number;+ id: string;+}++/**+ * The append outcome is unknown: the command failed, and so did taking the+ * entry back. The caller must not tell the client to send directly (the stored+ * copy could still start); retrying the append with the same entry id settles it.+ */+export class SteerQueueWriteUnknownError extends Error {+ constructor(cause: unknown) {+ super('The follow-up may or may not have been queued; retry with the same id', { cause });+ this.name = 'SteerQueueWriteUnknownError';+ }+}++/**+ * Entries waiting on the surface but bound to no run β returned after a failed+ * delivery or reclaimed from a lapsed batch. The next run that drains the+ * surface takes them.+ */+const UNBOUND = '*';++// Each item is `<entry id>\t<operation it waits behind>\n<entry JSON>`, so the+// scripts can match ids and operations without parsing JSON. A drained batch is+// `<lease expiry ms>` followed by its items, each after a 0x1E separator β+// a character neither an entry id nor `JSON.stringify` output ever contains.+const encode = (entry: SteerQueueEntry, behind: string) =>+ `${entry.id}\t${behind}\n${JSON.stringify(entry)}`;++/** Lua helpers shared by the scripts below. */+const LUA_HELPERS = `+local SEP = string.char(30)+local function header(item)+ local nl = string.find(item, '\\n', 1, true)+ if not nl then return nil, nil end+ local head = string.sub(item, 1, nl - 1)+ local tab = string.find(head, '\\t', 1, true)+ if not tab then return nil, nil end+ return string.sub(head, 1, tab - 1), string.sub(head, tab + 1)+end+local function takes(item, op)+ local _, behind = header(item)+ return behind == op or behind == '${UNBOUND}'+end+local function unbind(item)+ local id = header(item)+ local nl = string.find(item, '\\n', 1, true)+ return id .. '\\t${UNBOUND}' .. string.sub(item, nl)+end+local function splitBatch(batch)+ local parts = {}+ local from = 1+ while true do+ local at = string.find(batch, SEP, from, true)+ if not at then+ table.insert(parts, string.sub(batch, from))+ break+ end+ table.insert(parts, string.sub(batch, from, at - 1))+ from = at + 1+ end+ local expiry = tonumber(table.remove(parts, 1))+ return expiry, parts+end+local function joinBatch(expiry, items)+ return tostring(expiry) .. SEP .. table.concat(items, SEP)+end+local function pushFront(qkey, items)+ for i = #items, 1, -1 do redis.call('LPUSH', qkey, unbind(items[i])) end+end+local function reclaimLapsed(qkey, pkey, now)+ local all = redis.call('HGETALL', pkey)+ for i = 1, #all, 2 do+ local expiry, items = splitBatch(all[i + 1])+ if expiry <= now then+ pushFront(qkey, items)+ redis.call('HDEL', pkey, all[i])+ end+ end+end+local function inFlight(pkey)+ local n = 0+ for _, batch in ipairs(redis.call('HVALS', pkey)) do+ local _, items = splitBatch(batch)+ n = n + #items+ end+ return n+end+`;++/**+ * Idempotent by entry id: a retried append of an id still queued answers the+ * current length, and of an id a drain already took answers -2, instead of+ * adding a copy. The bound counts entries in drained batches too.+ *+ * KEYS[1] = queue; KEYS[2] = taken ids; KEYS[3] = drained batches;+ * ARGV[1] = entry id; ARGV[2] = item; ARGV[3] = ttl; ARGV[4] = max+ */+const APPEND_SCRIPT = `${LUA_HELPERS}+if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return -2 end+local items = redis.call('LRANGE', KEYS[1], 0, -1)+for _, item in ipairs(items) do+ local id = header(item)+ if id == ARGV[1] then return #items end+end+if #items + inFlight(KEYS[3]) >= tonumber(ARGV[4]) then return -1 end+local length = redis.call('RPUSH', KEYS[1], ARGV[2])+redis.call('EXPIRE', KEYS[1], ARGV[3])+return length+`;++/** KEYS[1] = queue */+const LIST_SCRIPT = `return redis.call('LRANGE', KEYS[1], 0, -1)`;++/**+ * Entries a run would take: queued ones it owns, plus any in a lapsed batch+ * (they go back unbound on the next drain).+ *+ * KEYS[1] = queue; KEYS[2] = drained batches; ARGV[1] = operation id; ARGV[2] = now ms+ */+const LENGTH_SCRIPT = `${LUA_HELPERS}+local count = 0+for _, item in ipairs(redis.call('LRANGE', KEYS[1], 0, -1)) do+ if takes(item, ARGV[1]) then count = count + 1 end+end+for _, batch in ipairs(redis.call('HVALS', KEYS[2])) do+ local expiry, items = splitBatch(batch)+ if expiry <= tonumber(ARGV[2]) then count = count + #items end+end+return count+`;++/** KEYS[1] = queue; ARGV[1] = entry id. Returns 1 when this call removed it. */+const REMOVE_SCRIPT = `${LUA_HELPERS}+for _, item in ipairs(redis.call('LRANGE', KEYS[1], 0, -1)) do+ local id = header(item)+ if id == ARGV[1] then return redis.call('LREM', KEYS[1], 1, item) end+end+return 0+`;++/**+ * Moves the entries a run owns into a drained batch under `drainId`, in one+ * step: those queued behind it, unbound ones, and those behind a run confirmed+ * ended. Entries behind any other run stay. Lapsed batches go back to the queue+ * first. Retrying with the same `drainId` returns the same batch, so a drain+ * whose response was lost can be read back. Taken ids are recorded so a retried+ * append of one is recognized.+ *+ * KEYS[1] = queue; KEYS[2] = taken ids; KEYS[3] = drained batches;+ * ARGV[1] = operation id; ARGV[2] = drain id; ARGV[3] = now ms; ARGV[4] = lease ms;+ * ARGV[5] = ttl; ARGV[6..] = runs confirmed ended+ */+const DRAIN_SCRIPT = `${LUA_HELPERS}+local now = tonumber(ARGV[3])+reclaimLapsed(KEYS[1], KEYS[3], now)+local existing = redis.call('HGET', KEYS[3], ARGV[2])+if existing then+ local _, items = splitBatch(existing)+ return items+end+local ended = {}+for i = 6, #ARGV do ended[ARGV[i]] = true end+local taken = {}+local kept = {}+for _, item in ipairs(redis.call('LRANGE', KEYS[1], 0, -1)) do+ local id, behind = header(item)+ if takes(item, ARGV[1]) or (behind and ended[behind]) then+ table.insert(taken, item)+ if id then redis.call('SADD', KEYS[2], id) end+ else+ table.insert(kept, item)+ end+end+if #taken == 0 then return taken end+redis.call('HSET', KEYS[3], ARGV[2], joinBatch(now + tonumber(ARGV[4]), taken))+redis.call('EXPIRE', KEYS[3], ARGV[5])+redis.call('EXPIRE', KEYS[2], ARGV[5])+local ttl = redis.call('TTL', KEYS[1])+redis.call('DEL', KEYS[1])+if #kept > 0 then+ redis.call('RPUSH', KEYS[1], unpack(kept))+ redis.call('EXPIRE', KEYS[1], ttl > 0 and ttl or ARGV[5])+end+return taken+`;++/**+ * Settles part or all of a drained batch: the listed entries go back to the+ * head of the queue, unbound, in order; the batch keeps the rest, or is gone+ * once nothing is left. An empty list acknowledges the whole batch (delivered).+ *+ * KEYS[1] = queue; KEYS[2] = drained batches; ARGV[1] = drain id; ARGV[2] = ttl;+ * ARGV[3..] = entry ids to return+ */+const SETTLE_SCRIPT = `${LUA_HELPERS}+local batch = redis.call('HGET', KEYS[2], ARGV[1])+if not batch then return 0 end+local back = {}+for i = 3, #ARGV do back[ARGV[i]] = true end+local expiry, items = splitBatch(batch)+local returned = {}+local kept = {}+for _, item in ipairs(items) do+ local id = header(item)+ if #ARGV >= 3 and back[id] then table.insert(returned, item) else table.insert(kept, item) end+end+if #returned > 0 then+ pushFront(KEYS[1], returned)+ redis.call('EXPIRE', KEYS[1], ARGV[2])+end+if #ARGV < 3 or #kept == 0 then+ redis.call('HDEL', KEYS[2], ARGV[1])+else+ redis.call('HSET', KEYS[2], ARGV[1], joinBatch(expiry, kept))+end+return #returned+`;++const keyOf = (scope: SteerQueueScope) =>+ RedisKeys.agentSteer.followUps(scope.userId, scope.topicId, scope.threadId);++const takenKeyOf = (scope: SteerQueueScope) =>+ RedisKeys.agentSteer.takenFollowUps(scope.userId, scope.topicId, scope.threadId);++const drainedKeyOf = (scope: SteerQueueScope) =>+ RedisKeys.agentSteer.drainedFollowUps(scope.userId, scope.topicId, scope.threadId);++/** The operation an item waits behind, from its header. */+const behindOf = (item: string) => {+ const head = item.slice(0, Math.max(item.indexOf('\n'), 0));+ const tab = head.indexOf('\t');+ return tab < 0 ? undefined : head.slice(tab + 1);+};++const parseEntries = <T extends SteerQueueEntry>(raw: unknown): T[] => {+ if (!Array.isArray(raw)) return [];++ return raw.flatMap((item) => {+ if (typeof item !== 'string') return [];+ const nl = item.indexOf('\n');+ if (nl < 0) return [];+ try {+ return [JSON.parse(item.slice(nl + 1)) as T];+ } catch {+ return [];+ }+ });+};++/**+ * Follow-ups a user queued behind a running turn, held server-side so the+ * runtime can start the next turn without a round trip through the client.+ * Each entry is bound to the run it was queued behind, and only that run (or,+ * once returned unbound, the next run on the surface) takes it.+ *+ * Draining is two-phase: `drain` moves entries into a batch that stays in Redis+ * until `settle` acknowledges it or returns entries from it. A batch nobody+ * settles goes back to the queue when its lease lapses, so a crash, a lost+ * response or an outage between the two never loses an accepted follow-up.+ *+ * `append` returns `undefined` when the follow-up was definitely not stored: the+ * caller then tells the client to send the message itself, as it did before+ * this queue.+ */+export const steerQueue = {+ /**+ * Adds an entry at the tail, waiting behind `operationId`. Retrying with an+ * entry id that is already queued is a no-op.+ *+ * @returns the queue length, `'full'` at {@link STEER_QUEUE_MAX_ENTRIES},+ * `'taken'` when a drain already took this entry id (a retry of a write that+ * landed), or `undefined` when it was not stored (no Redis, or a failed+ * command that was taken back)+ * @throws {SteerQueueWriteUnknownError} when the command failed and taking+ * the entry back did not prove it absent (the take-back failed, or found+ * nothing because a drain may already have taken it)+ */+ async append(scope: SteerQueueScope, entry: SteerQueueEntry, operationId: string) {+ const redis = await getClient();+ if (!redis) return;++ const key = keyOf(scope);+ try {+ const length = await redis.eval<number>(+ APPEND_SCRIPT,+ 3,+ key,+ takenKeyOf(scope),+ drainedKeyOf(scope),+ entry.id,+ encode(entry, operationId),+ QUEUE_TTL_SECONDS,+ STEER_QUEUE_MAX_ENTRIES,+ );+ if (Number(length) === -2) return 'taken' as const;+ return Number(length) < 0 ? ('full' as const) : Number(length);+ } catch (error) {+ // A timed-out command may still have committed. Take the entry back+ // through the same client (a fresh one is behind the open circuit) so+ // "not stored" holds before the client is told to send directly.+ let removed: number;+ try {+ removed = Number(await redis.eval<number>(REMOVE_SCRIPT, 1, key, entry.id));+ } catch {+ throw new SteerQueueWriteUnknownError(error);+ }+ // Nothing to take back: the write never landed, or a drain already took+ // it and may be starting it. Only a removal proves "not stored".+ if (removed === 0) throw new SteerQueueWriteUnknownError(error);+ return;+ }+ },++ /**+ * Moves the entries `operationId` owns β queued behind it, unbound, or+ * behind one of `endedOperationIds` (runs the caller confirmed ended) β into+ * a drained batch under `drainId`, and returns them oldest first. Entries+ * behind any other run stay queued. The caller must `settle` the batch; a+ * retry with the same `drainId` reads the same batch back.+ *+ * @throws when Redis is unavailable β an outage is not an empty queue; the+ * entries stay, and a later run on the surface takes them+ */+ async drain<T extends SteerQueueEntry>(+ scope: SteerQueueScope,+ operationId: string,+ endedOperationIds: string[],+ drainId: string,+ ): Promise<T[]> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to drain queued follow-ups');++ return parseEntries<T>(+ await redis.eval<unknown>(+ DRAIN_SCRIPT,+ 3,+ keyOf(scope),+ takenKeyOf(scope),+ drainedKeyOf(scope),+ operationId,+ drainId,+ Date.now(),+ PROCESSING_LEASE_MS,+ QUEUE_TTL_SECONDS,+ ...endedOperationIds,+ ),+ );+ },++ /**+ * Settles a drained batch: `returnIds` go back to the head of the queue,+ * unbound; with none, the whole batch is acknowledged as delivered.+ *+ * @throws when Redis is unavailable β the batch then stays and goes back to+ * the queue on its own once its lease lapses+ */+ async settle(scope: SteerQueueScope, drainId: string, returnIds: string[] = []): Promise<void> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to settle queued follow-ups');++ await redis.eval(+ SETTLE_SCRIPT,+ 2,+ keyOf(scope),+ drainedKeyOf(scope),+ drainId,+ QUEUE_TTL_SECONDS,+ ...returnIds,+ );+ },++ /**+ * 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 drained+ * batches, so a lapsed one is still drained back. Zero when nothing waits.+ *+ * @throws when Redis is unavailable, like {@link steerQueue.drain}+ */+ async boundOperations(+ scope: SteerQueueScope,+ ): Promise<{ operationIds: string[]; total: number }> {+ const redis = await getClient();+ if (!redis) throw new Error('Redis is unavailable to read queued follow-ups');++ const raw = await redis.eval<unknown>(LIST_SCRIPT, 1, keyOf(scope));+ const items = Array.isArray(raw)+ ? raw.filter((item): item is string => typeof item === 'string')+ : [];+ const operationIds = new Set<string>();+ for (const item of items) {+ const behind = behindOf(item);+ if (behind && behind !== UNBOUND) operationIds.add(behind);+ }+ const drained = Number(+ await redis.eval<number>(`${LUA_HELPERS}\nreturn inFlight(KEYS[1])`, 1, drainedKeyOf(scope)),+ );+ return { operationIds: [...operationIds], total: items.length + drained };+ },++ /** Number of entries `operationId` would take; `0` without Redis. */+ async length(scope: SteerQueueScope, operationId: string): Promise<number> {+ const redis = await getClient();+ if (!redis) return 0;++ return Number(+ await redis.eval<number>(+ LENGTH_SCRIPT,+ 2,+ keyOf(scope),+ drainedKeyOf(scope),+ operationId,+ Date.now(),+ ),+ );+ },++ /** Every waiting entry on the surface, oldest first. */+ async list<T extends SteerQueueEntry>(scope: SteerQueueScope): Promise<T[]> {+ const redis = await getClient();+ if (!redis) return [];++ return parseEntries<T>(await redis.eval<unknown>(LIST_SCRIPT, 1, keyOf(scope)));+ },++ /**+ * Removes one entry by id.+ *+ * @returns `true` when this call removed it β `false` when it was never+ * there or a drain already took it+ */+ async remove(scope: SteerQueueScope, id: string): Promise<boolean> {+ const redis = await getClient();+ if (!redis) return false;++ return Number(await redis.eval<number>(REMOVE_SCRIPT, 1, keyOf(scope), id)) > 0;+ },+};diff --git a/apps/server/src/services/redis/threadStartFence.ts b/apps/server/src/services/redis/threadStartFence.tsnew file mode 100644index 00000000000..9d5c745406a--- /dev/null+++ b/apps/server/src/services/redis/threadStartFence.ts@@ -0,0 +1,63 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('agentSteer');++// Covers one start (operation row created, first step dispatched); a fence its+// holder never released lapses after this.+const FENCE_TTL_MS = 30 * 1000;+const RETRY_DELAY_MS = 100;++/** KEYS[1] = fence; ARGV[1] = owner. Releases only the caller's own fence. */+const RELEASE_SCRIPT = `+if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end+return 0+`;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/**+ * A short mutual-exclusion fence around starting a run on an existing thread.+ * Thread starts deliberately skip the topic-start reservation, so without it a+ * queued follow-up's "is a run live here?" check and its start could interleave+ * with a foreground send on the same thread.+ */+export const threadStartFence = {+ /**+ * Waits up to `waitMs` for the fence.+ *+ * @returns `held` when this caller owns it, `busy` when another start kept it+ * for the whole wait, `unavailable` without Redis+ */+ async acquire(+ threadId: string,+ owner: string,+ waitMs: number,+ ): Promise<'busy' | 'held' | 'unavailable'> {+ const redis = await getClient();+ if (!redis) return 'unavailable';++ const key = RedisKeys.agentSteer.threadStartFence(threadId);+ const deadline = Date.now() + waitMs;+ try {+ for (;;) {+ if ((await redis.set(key, owner, { nx: true, px: FENCE_TTL_MS })) === 'OK') return 'held';+ if (Date.now() >= deadline) return 'busy';+ await sleep(RETRY_DELAY_MS);+ }+ } catch {+ return 'unavailable';+ }+ },++ /** Best effort: a fence that cannot be released lapses on its own. */+ async release(threadId: string, owner: string): Promise<void> {+ const redis = await getClient();+ if (!redis) return;++ await redis+ .eval(RELEASE_SCRIPT, 1, RedisKeys.agentSteer.threadStartFence(threadId), owner)+ .catch(() => undefined);+ },+};diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 9f152ebce2f..02fe58a70d3 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -34,6 +34,11 @@ import {import { selectEffectiveToolManifestMap, selectRunTools } from '../utils/operationToolSet';import { selectSecurityBlacklist, selectUserInterventionConfig } from '../utils/stateSlots';import { shouldCompress } from '../utils/tokenCounter';+import {+ findCurrentTurnPendingToolMessages,+ isFoldedAssistantGroup,+ pendingToolMessagesFromGroup,+} from './pendingToolMessages';const TOOL_NOT_ALLOWED_CONTENT ='Tool execution blocked because the tool is not allowed in the current execution scope.';@@ -368,65 +373,9 @@ export class GeneralChatAgent implements Agent {return { existingToolMessageIds, hasToolsCalling, parentMessageId, toolsCalling };}- /**- * Pending-tool scope guard for the main loop.- *- * The pending-approval check must only count tool messages produced by the- * **current** assistant turn. Stale `pluginIntervention.status === 'pending'`- * rows from a previous turn (e.g. an abandoned approval flow whose user- * never clicked approve/reject) get loaded back into `state.messages` via- * `historyMessages` and would otherwise hijack every subsequent- * `tool_result` / `tools_batch_result` phase, parking the loop in- * `waiting_for_human` forever.- *- * "Current turn" = the most recent assistant message that emitted tool calls,- * stored as either model-native `tool_calls` or persisted `tools`. All pending- * tool messages legitimately belonging to this turn have- * `parentId === currentAssistantId`.- *- * Two message shapes reach this method and BOTH must be handled:- *- * 1. **Raw shape** (client runtime, and any step that never round-tripped- * through the DB): a `role: 'assistant'` row carrying `tools` /- * `tool_calls`, followed by sibling `role: 'tool'` rows whose- * `pluginIntervention.status` is the approval state.- * 2. **Parsed shape** (server runtime): `AgentRuntimeService` rebuilds- * `state.messages` from the DB through `conversation-flow`'s `parse()` on- * every step entry, and `FlatListBuilder` folds an assistant plus its tool- * rows into ONE `role: 'assistantGroup'` virtual message. In that shape- * there is no `role: 'assistant'` row carrying tools and no top-level- * `role: 'tool'` row at all β the tool calls live in- * `children[].tools[]`, each carrying `intervention` and `result_msg_id`.- *- * Matching only shape 1 made this guard a no-op on the entire server runtime:- * approving one tool of a parallel batch resumed the LLM immediately while the- * other N-1 tool rows were still `pending` with empty content, so the model- * saw blank tool results and (visibly, in reproduction) re-issued the whole- * batch. Every parallel-approval defect downstream of that β forked parent- * chains, duplicate batches β starts here.- */+ /** See {@link findCurrentTurnPendingToolMessages}. */private getCurrentTurnPendingToolMessages(state: AgentState): any[] {- const messages = (state.messages ?? []) as any[];-- for (let i = messages.length - 1; i >= 0; i--) {- const m = messages[i];-- // Shape 2 β parsed `assistantGroup`. Read the folded tool entries; their- // `result_msg_id` is the tool message id the approval flow addresses.- if (this.isFoldedAssistantGroup(m)) {- return this.pendingToolMessagesFromGroup(m);- }-- // Shape 1 β raw assistant + sibling tool rows.- if (m.role === 'assistant' && (m.tool_calls?.length > 0 || m.tools?.length > 0)) {- return messages.filter(- (t: any) =>- t.role === 'tool' && t.pluginIntervention?.status === 'pending' && t.parentId === m.id,- );- }- }-- return [];+ return findCurrentTurnPendingToolMessages(state.messages);}/**@@ -513,35 +462,11 @@ export class GeneralChatAgent implements Agent {}private isFoldedAssistantGroup(message: any): boolean {- return (- (message?.role === 'assistantGroup' || message?.role === 'supervisor') &&- (message.children ?? []).some((child: any) => child.tools?.length > 0)- );+ return isFoldedAssistantGroup(message);}- /**- * Normalize an `assistantGroup`'s folded tool entries back into the tool-row- * shape the rest of the runner expects (`plugin`, `pluginIntervention`,- * `parentId`), keeping only the pending ones.- */private pendingToolMessagesFromGroup(group: any): any[] {- return (group.children ?? [])- .flatMap((child: any) => child.tools ?? [])- .filter((tool: any) => tool.intervention?.status === 'pending')- .map((tool: any) => {- // Drop the display-only fields FlatListBuilder merges onto the entry so- // `plugin` is a plain ChatToolPayload β the same shape the raw path- // produces, and what `request_human_approve` / `call_tool` expect.- const { intervention, result: _result, result_msg_id, ...plugin } = tool;- return {- id: result_msg_id,- parentId: group.id,- plugin: plugin as ChatToolPayload,- pluginIntervention: intervention,- role: 'tool',- tool_call_id: tool.id,- };- });+ return pendingToolMessagesFromGroup(group);}/**@@ -1004,6 +929,12 @@ export class GeneralChatAgent implements Agent {// Single sub-agent completed, continue to call LLM with resultconst { parentMessageId } = context.payload as SubAgentResultPayload;+ // Same decision point as the batch variant: hand the turn back for+ // queued user messages instead of another model call first.+ if (context.stepContext?.hasQueuedMessages) {+ return { reason: 'queued_message_interrupt', type: 'finish' };+ }+// Continue to call LLM with the latest state after the sub-agent run.return this.toLLMCall({diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.queuedMessages.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.queuedMessages.test.tsnew file mode 100644index 00000000000..c453bc34dc5--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.queuedMessages.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import type { AgentRuntimeContext, AgentState } from '../../types';+import { GeneralChatAgent } from '../GeneralChatAgent';++const state = {+ messages: [+ { content: 'Execute task', role: 'user' },+ { content: '', role: 'assistant' },+ { content: 'Task result', role: 'tool', tool_call_id: 'call-sub-agent-1' },+ ],+ operationId: 'test-session',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+} as unknown as AgentState;++const context = (phase: AgentRuntimeContext['phase'], hasQueuedMessages: boolean) =>+ ({+ payload: { parentMessageId: 'task-parent-msg', result: { success: true } },+ phase,+ session: { messageCount: 0, sessionId: 'test-session', status: 'running', stepCount: 0 },+ stepContext: hasQueuedMessages ? { hasQueuedMessages: true } : undefined,+ }) as unknown as AgentRuntimeContext;++const agent = () =>+ new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ operationId: 'test-session',+ });++describe('GeneralChatAgent β queued user messages at a sub-agent result', () => {+ it.each(['sub_agent_result', 'sub_agents_batch_result'] as const)(+ 'hands the turn back at %s when user messages are queued, before another model call',+ async (phase) => {+ await expect(agent().runner(context(phase, true), state)).resolves.toEqual({+ reason: 'queued_message_interrupt',+ type: 'finish',+ });+ },+ );++ it('continues to the model after a single sub-agent when nothing is queued', async () => {+ await expect(agent().runner(context('sub_agent_result', false), state)).resolves.toMatchObject({+ type: 'call_llm',+ });+ });+});diff --git a/packages/agent-runtime/src/agents/index.ts b/packages/agent-runtime/src/agents/index.tsindex 256e7078eed..8c3e95d335a 100644--- a/packages/agent-runtime/src/agents/index.ts+++ b/packages/agent-runtime/src/agents/index.ts@@ -1,2 +1,3 @@export * from './GeneralChatAgent';export * from './graph';+export * from './pendingToolMessages';diff --git a/packages/agent-runtime/src/agents/pendingToolMessages.ts b/packages/agent-runtime/src/agents/pendingToolMessages.tsnew file mode 100644index 00000000000..d4cda57a83c--- /dev/null+++ b/packages/agent-runtime/src/agents/pendingToolMessages.ts@@ -0,0 +1,94 @@+import type { ChatToolPayload } from '@lobechat/types';++export const isFoldedAssistantGroup = (message: any): boolean => {+ return (+ (message?.role === 'assistantGroup' || message?.role === 'supervisor') &&+ (message.children ?? []).some((child: any) => child.tools?.length > 0)+ );+};++/**+ * Normalize an `assistantGroup`'s folded tool entries back into the tool-row+ * shape the rest of the runner expects (`plugin`, `pluginIntervention`,+ * `parentId`), keeping only the pending ones.+ */+export const pendingToolMessagesFromGroup = (group: any): any[] => {+ return (group.children ?? [])+ .flatMap((child: any) => child.tools ?? [])+ .filter((tool: any) => tool.intervention?.status === 'pending')+ .map((tool: any) => {+ // Drop the display-only fields FlatListBuilder merges onto the entry so+ // `plugin` is a plain ChatToolPayload β the same shape the raw path+ // produces, and what `request_human_approve` / `call_tool` expect.+ const { intervention, result: _result, result_msg_id, ...plugin } = tool;+ return {+ id: result_msg_id,+ parentId: group.id,+ plugin: plugin as ChatToolPayload,+ pluginIntervention: intervention,+ role: 'tool',+ tool_call_id: tool.id,+ };+ });+};++/**+ * Pending-tool scope guard for the main loop.+ *+ * The pending-approval check must only count tool messages produced by the+ * **current** assistant turn. Stale `pluginIntervention.status === 'pending'`+ * rows from a previous turn (e.g. an abandoned approval flow whose user+ * never clicked approve/reject) get loaded back into `state.messages` via+ * `historyMessages` and would otherwise hijack every subsequent+ * `tool_result` / `tools_batch_result` phase, parking the loop in+ * `waiting_for_human` forever.+ *+ * "Current turn" = the most recent assistant message that emitted tool calls,+ * stored as either model-native `tool_calls` or persisted `tools`. All pending+ * tool messages legitimately belonging to this turn have+ * `parentId === currentAssistantId`.+ *+ * Two message shapes reach this method and BOTH must be handled:+ *+ * 1. **Raw shape** (client runtime, and any step that never round-tripped+ * through the DB): a `role: 'assistant'` row carrying `tools` /+ * `tool_calls`, followed by sibling `role: 'tool'` rows whose+ * `pluginIntervention.status` is the approval state.+ * 2. **Parsed shape** (server runtime): `AgentRuntimeService` rebuilds+ * `state.messages` from the DB through `conversation-flow`'s `parse()` on+ * every step entry, and `FlatListBuilder` folds an assistant plus its tool+ * rows into ONE `role: 'assistantGroup'` virtual message. In that shape+ * there is no `role: 'assistant'` row carrying tools and no top-level+ * `role: 'tool'` row at all β the tool calls live in+ * `children[].tools[]`, each carrying `intervention` and `result_msg_id`.+ *+ * Matching only shape 1 made this guard a no-op on the entire server runtime:+ * approving one tool of a parallel batch resumed the LLM immediately while the+ * other N-1 tool rows were still `pending` with empty content, so the model+ * saw blank tool results and (visibly, in reproduction) re-issued the whole+ * batch. Every parallel-approval defect downstream of that β forked parent+ * chains, duplicate batches β starts here.+ */+export const findCurrentTurnPendingToolMessages = (stateMessages: unknown[] | undefined): any[] => {+ const messages = (stateMessages ?? []) as any[];++ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i];++ // Shape 2 β parsed `assistantGroup`. Read the folded tool entries; their+ // `result_msg_id` is the tool message id the approval flow addresses.+ if (isFoldedAssistantGroup(m)) {+ return pendingToolMessagesFromGroup(m);+ }++ // Shape 1 β raw assistant + sibling tool rows.+ if (m.role === 'assistant' && (m.tool_calls?.length > 0 || m.tools?.length > 0)) {+ return messages.filter(+ (t: any) =>+ t.role === 'tool' && t.pluginIntervention?.status === 'pending' && t.parentId === m.id,+ );+ }+ }++ return [];+};diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.tsindex 7f12597fc80..0cf01d74dcd 100644--- a/packages/const/src/apiKeyScope.test.ts+++ b/packages/const/src/apiKeyScope.test.ts@@ -117,6 +117,14 @@ describe('requiredApiKeyScopeForTrpc', () => {expect(requiredApiKeyScopeForTrpc('aiAgent.execAgent', 'mutation')).toEqual({scopes: ['agent:write', 'chat:write', 'model:invoke'],});+ // listing the queue reads conversation content+ expect(requiredApiKeyScopeForTrpc('agentSteerQueue.list', 'query')).toEqual({+ scopes: ['agent:read', 'chat:read'],+ });+ // a queued follow-up is a deferred agent run+ expect(requiredApiKeyScopeForTrpc('agentSteerQueue.append', 'mutation')).toEqual({+ scopes: ['agent:write', 'chat:write', 'model:invoke'],+ });// provider connectivity test sends a real model requestexpect(requiredApiKeyScopeForTrpc('aiProvider.checkProviderConnectivity', 'mutation')).toEqual({scopes: ['model:write', 'model:invoke'],diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 13b609317bd..86ba335cc8a 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -189,6 +189,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleagentShare: 'blocked',agentSignal: rw('agent:read', 'agent:write'),agentSkills: rw('agent:read', 'agent:write'),+ agentSteerQueue: rw('agent:read', 'agent:write'),// a trace snapshot is the whole inside of a run β system role, injected user// memory, tool results β and `getSnapshotUrl` hands back a presigned URL that// needs no further auth, so a restricted key holding one would read past its@@ -349,6 +350,12 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {'aiAgent.execSubAgentTask': AGENT_RUN_SCOPES,'aiAgent.scheduleAgentRun': AGENT_RUN_SCOPES,'aiAgent.startExecution': AGENT_RUN_SCOPES,+ // a queued follow-up is a deferred composer send: the run that drains it+ // starts a model turn and writes the user message+ 'agentSteerQueue.append': AGENT_RUN_SCOPES,+ 'agentSteerQueue.remove': ['chat:write'],+ // returns the queued prompts and attachments, i.e. conversation content+ 'agentSteerQueue.list': ['chat:read'],// thread/message state writes without starting a run'aiAgent.createClientGroupAgentTaskThread': ['chat:write'],'aiAgent.createClientTaskThread': ['chat:write'],