Skip to content

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

✨ feat(agent-runtime): hand a server run's turn back when messages are queued behind it (#19585)

Arvin Xu43e71aa7789d
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 7d95919074d..4532bcfc202 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -262,6 +262,20 @@ export class AgentRuntimeCoordinator {
return this.stateManager.isInterrupted(operationId);
}
+ /**
+ * Record whether the client holds user messages queued behind the operation.
+ */
+ async setQueuedMessages(operationId: string, pending: boolean): Promise<void> {
+ return this.stateManager.setQueuedMessages(operationId, pending);
+ }
+
+ /**
+ * Check the client's queued-messages flag.
+ */
+ async hasQueuedMessages(operationId: string): Promise<boolean> {
+ return this.stateManager.hasQueuedMessages(operationId);
+ }
+
/**
* Get operation metadata
*/
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index c401ca23dcb..4ebf45a1f1d 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -100,6 +100,7 @@ export class AgentStateManager {
private readonly STEPS_PREFIX = 'agent_runtime_steps';
private readonly METADATA_PREFIX = 'agent_runtime_meta';
private readonly INTERRUPT_PREFIX = 'agent_runtime_interrupt';
+ private readonly QUEUED_MESSAGES_PREFIX = 'agent_runtime_queued_messages';
private readonly INLINE_RESUME_PREFIX = 'agent_runtime_inline_resume';
private readonly DEFAULT_TTL = 2 * 3600; // 2h
@@ -212,6 +213,22 @@ export class AgentStateManager {
return exists === 1;
}
+ /**
+ * Mirror the client's queued-messages flag into a tiny key beside the state,
+ * for the same reason as the interrupt sentinel: the step boundary reads it
+ * without loading the state blob. Clearing deletes the key.
+ */
+ async setQueuedMessages(operationId: string, pending: boolean): Promise<void> {
+ const key = `${this.QUEUED_MESSAGES_PREFIX}:${operationId}`;
+ if (pending) await this.redis.setex(key, this.DEFAULT_TTL, '1');
+ else await this.redis.del(key);
+ }
+
+ async hasQueuedMessages(operationId: string): Promise<boolean> {
+ const exists = await this.redis.exists(`${this.QUEUED_MESSAGES_PREFIX}:${operationId}`);
+ return exists === 1;
+ }
+
/**
* Save step execution result
*/
@@ -422,6 +439,7 @@ export class AgentStateManager {
`${this.STEPS_PREFIX}:${operationId}`,
`${this.METADATA_PREFIX}:${operationId}`,
`${this.INTERRUPT_PREFIX}:${operationId}`,
+ `${this.QUEUED_MESSAGES_PREFIX}:${operationId}`,
`${this.INLINE_RESUME_PREFIX}:${operationId}`,
];
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index c6e7ac186b7..6aca6daaad1 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -17,6 +17,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
private stepLocks: Map<string, { expiresAt: number; ownerId: string }> = new Map();
private inlineResumes: Map<string, string> = new Map();
private interrupted: Set<string> = new Set();
+ private queuedMessages: Set<string> = new Set();
private executionLockKey(operationId: string): string {
return `agent_runtime_operation_lock:${operationId}`;
@@ -143,11 +144,21 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
return this.interrupted.has(operationId);
}
+ async setQueuedMessages(operationId: string, pending: boolean): Promise<void> {
+ if (pending) this.queuedMessages.add(operationId);
+ else this.queuedMessages.delete(operationId);
+ }
+
+ async hasQueuedMessages(operationId: string): Promise<boolean> {
+ return this.queuedMessages.has(operationId);
+ }
+
async deleteAgentOperation(operationId: string): Promise<void> {
this.states.delete(operationId);
this.steps.delete(operationId);
this.metadata.delete(operationId);
this.interrupted.delete(operationId);
+ this.queuedMessages.delete(operationId);
this.inlineResumes.delete(operationId);
log('Deleted operation %s', operationId);
}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index 52df665aa5a..ecbc31f1394 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -31,6 +31,8 @@ describe('AgentRuntimeCoordinator', () => {
isInterrupted: vi.fn(),
loadAgentState: vi.fn(),
markInterrupted: vi.fn(),
+ hasQueuedMessages: vi.fn(),
+ setQueuedMessages: vi.fn(),
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
};
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 950acfba285..5b0c4590eb8 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -271,11 +271,42 @@ describe('AgentStateManager', () => {
'agent_runtime_steps:op-del',
'agent_runtime_meta:op-del',
'agent_runtime_interrupt:op-del',
+ 'agent_runtime_queued_messages:op-del',
'agent_runtime_inline_resume:op-del',
);
});
});
+ describe('queued messages flag', () => {
+ it('setQueuedMessages(true) writes a small key with the state TTL', async () => {
+ await stateManager.setQueuedMessages('op-q', true);
+
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ 'agent_runtime_queued_messages:op-q',
+ 2 * 3600,
+ '1',
+ );
+ });
+
+ it('setQueuedMessages(false) deletes the key', async () => {
+ await stateManager.setQueuedMessages('op-q', false);
+
+ expect(redisMock.del).toHaveBeenCalledWith('agent_runtime_queued_messages:op-q');
+ expect(redisMock.setex).not.toHaveBeenCalled();
+ });
+
+ it('hasQueuedMessages checks key existence instead of loading the state blob', async () => {
+ redisMock.exists.mockResolvedValueOnce(1);
+ expect(await stateManager.hasQueuedMessages('op-q')).toBe(true);
+
+ redisMock.exists.mockResolvedValueOnce(0);
+ expect(await stateManager.hasQueuedMessages('op-q')).toBe(false);
+
+ expect(redisMock.exists).toHaveBeenCalledWith('agent_runtime_queued_messages:op-q');
+ expect(redisMock.get).not.toHaveBeenCalled();
+ });
+ });
+
describe('inline resume envelope', () => {
it('parks the envelope under the operation TTL', async () => {
await expect(stateManager.saveInlineResume('op-resume', '{"stepIndex":4}')).resolves.toBe(
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
index deca2855112..c8c27c8c039 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
@@ -297,6 +297,25 @@ describe('InMemoryAgentStateManager', () => {
});
});
+ describe('queued messages flag', () => {
+ it('should follow the latest setQueuedMessages value', async () => {
+ expect(await manager.hasQueuedMessages('op-q')).toBe(false);
+
+ await manager.setQueuedMessages('op-q', true);
+ expect(await manager.hasQueuedMessages('op-q')).toBe(true);
+
+ await manager.setQueuedMessages('op-q', false);
+ expect(await manager.hasQueuedMessages('op-q')).toBe(false);
+ });
+
+ it('should clear the flag when the operation is deleted', async () => {
+ await manager.setQueuedMessages('op-q', true);
+ await manager.deleteAgentOperation('op-q');
+
+ expect(await manager.hasQueuedMessages('op-q')).toBe(false);
+ });
+ });
+
describe('deleteAgentOperation', () => {
it('should remove all data for an operation', async () => {
await manager.createOperationMetadata('op-del', { userId: 'u1' });
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index dfc39a1736a..187c5e93fed 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -89,6 +89,12 @@ export interface IAgentStateManager {
totalOperations: number;
}>;
+ /**
+ * Whether the client flagged user messages queued behind this operation
+ * (see `setQueuedMessages`). Cheap to read at every step boundary.
+ */
+ hasQueuedMessages: (operationId: string) => Promise<boolean>;
+
/**
* Check the interrupt sentinel written by `markInterrupted`. Cheap enough
* to poll, unlike `loadAgentState` which pulls the whole state blob.
@@ -140,6 +146,14 @@ export interface IAgentStateManager {
*/
saveStepResult: (operationId: string, stepResult: StepResult) => Promise<void>;
+ /**
+ * Record whether the client still holds user messages queued behind this
+ * operation. The agent reads it at the next step boundary and hands the turn
+ * back early, so the follow-up runs as the next turn instead of waiting for
+ * the whole run to finish.
+ */
+ setQueuedMessages: (operationId: string, pending: boolean) => Promise<void>;
+
/**
* Atomically try to claim a step for execution (distributed lock).
* Returns true if the lock was acquired, false if another execution already holds it.
diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
index 4517b89d7ed..ba8dde27426 100644
--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts
@@ -98,10 +98,12 @@ vi.mock('@/database/models/user', () => ({
const mockExecAgent = vi.fn();
const mockInterruptTask = vi.fn();
+const mockSetQueuedMessages = vi.fn();
const AiAgentServiceMock = vi.fn(function () {
return {
execAgent: mockExecAgent,
interruptTask: mockInterruptTask,
+ setQueuedMessages: mockSetQueuedMessages,
};
});
vi.mock('@/server/services/aiAgent', () => ({
@@ -166,6 +168,7 @@ describe('shareChatRouter', () => {
mockMessageQuery.mockResolvedValue([]);
mockExecAgent.mockResolvedValue({ operationId: 'op-1', success: true });
mockInterruptTask.mockResolvedValue({ operationId: 'op-1', success: true });
+ mockSetQueuedMessages.mockResolvedValue({ success: true });
mockSignUserJWT.mockResolvedValue('visitor-jwt');
mockSpendGate.mockResolvedValue({ allowed: true });
});
@@ -256,6 +259,14 @@ describe('shareChatRouter', () => {
expect(mockExecAgent).not.toHaveBeenCalled();
});
+ it('keeps the steer mark of a follow-up the visitor queued behind a running turn', async () => {
+ const caller = await createCaller();
+
+ await caller.execAgent({ prompt: 'follow up', shareId: 'share-1', steer: true });
+
+ expect(mockExecAgent).toHaveBeenCalledWith(expect.objectContaining({ steer: true }));
+ });
+
it('dispatches a creator-scoped run carrying the share gate', async () => {
const caller = await createCaller();
@@ -462,6 +473,55 @@ describe('shareChatRouter', () => {
});
});
+ describe('setQueuedMessages', () => {
+ it('flags the running operation through the creator-scoped service', async () => {
+ const caller = await createCaller();
+
+ await expect(
+ caller.setQueuedMessages({
+ operationId: 'op-1',
+ pending: true,
+ shareId: 'share-1',
+ topicId: 'tpc_visitor',
+ }),
+ ).resolves.toEqual({ success: true });
+
+ expect(AiAgentServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER, {
+ includeShareVisitor: true,
+ });
+ expect(mockSetQueuedMessages).toHaveBeenCalledWith({ operationId: 'op-1', pending: true });
+ });
+
+ it('rejects an operationId that does not match the topic’s current running operation', async () => {
+ const caller = await createCaller();
+
+ await expect(
+ caller.setQueuedMessages({
+ operationId: 'op-someone-elses',
+ pending: true,
+ shareId: 'share-1',
+ topicId: 'tpc_visitor',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockSetQueuedMessages).not.toHaveBeenCalled();
+ });
+
+ it("fails closed when the topic is not the visitor's own share topic", async () => {
+ mockFindById.mockResolvedValue({ ...visitorTopic, senderId: 'someone-else' });
+ const caller = await createCaller();
+
+ await expect(
+ caller.setQueuedMessages({
+ operationId: 'op-1',
+ pending: false,
+ shareId: 'share-1',
+ topicId: 'tpc_visitor',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockSetQueuedMessages).not.toHaveBeenCalled();
+ });
+ });
+
describe('getTopics', () => {
it("returns only the visitor's own topics via agentId + senderId scoping", async () => {
const caller = await createCaller();
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 7e1a48bb627..f3aaaf958f7 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1097,6 +1097,12 @@ const ExecAgentSchema = z
* 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, {
@@ -1330,6 +1336,15 @@ const UpdateClientTaskThreadStatusSchema = z.object({
threadId: z.string(),
});
+/**
+ * Schema for setQueuedMessages - flag queued follow-ups on a running operation
+ */
+const SetQueuedMessagesSchema = z.object({
+ operationId: z.string(),
+ /** Whether the composer still holds user messages queued behind the run. */
+ pending: z.boolean(),
+});
+
/**
* Schema for interruptTask - interrupt a running task
*/
@@ -2134,6 +2149,7 @@ export const aiAgentRouter = router({
resumeApprovals,
resumeToolResult,
selectedToolIds,
+ steer,
trigger,
userInterventionConfig,
} = input;
@@ -2330,6 +2346,7 @@ export const aiAgentRouter = router({
resumeToolResult,
selectedToolIds,
slug,
+ steer,
trigger: trigger ?? RequestTrigger.Chat,
userAgent: ctx.userAgent ?? undefined,
userInterventionConfig,
@@ -3065,6 +3082,20 @@ export const aiAgentRouter = router({
}
}),
+ /**
+ * Tell a running server operation whether the composer still holds user
+ * messages queued behind it. The run reads the flag at its next step
+ * boundary and ends the turn early, so the queued follow-up starts as the
+ * next turn instead of waiting for the whole run to finish.
+ */
+ setQueuedMessages: aiAgentWriteProcedure
+ .input(SetQueuedMessagesSchema)
+ .mutation(async ({ input, ctx }) => {
+ log('setQueuedMessages: operationId=%s, pending=%s', input.operationId, input.pending);
+
+ return ctx.aiAgentService.setQueuedMessages(input);
+ }),
+
/**
* Ingest a batch of `AgentStreamEvent`s from a `lh hetero exec` producer
* (CLI standalone, sandboxed CC, etc.) and republish them through the
diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.ts
index 0427dd2d8a2..7175f8c9512 100644
--- a/apps/server/src/routers/lambda/shareChat.ts
+++ b/apps/server/src/routers/lambda/shareChat.ts
@@ -157,6 +157,47 @@ const toVisitorSafeStartupError = (
});
};
+/**
+ * Authorize a visitor to act on a share run. It is not enough that the topic
+ * belongs to this visitor: `operationId` must also match the operation
+ * CURRENTLY recorded as running on that topic. Without that check a visitor
+ * could pass an arbitrary operationId (topics/operations are creator-owned
+ * rows) and reach an unrelated run on the creator's account.
+ *
+ * Returns the creator-scoped service, same as `execAgent`: the run's operation
+ * / thread rows were written under the creator's identity.
+ */
+const authorizeVisitorRunningOperation = async (
+ db: LobeChatDatabase,
+ visitorUserId: string,
+ input: { operationId: string; shareId: string; topicId: string },
+) => {
+ const share = await resolveLinkShareOrThrow(db, input.shareId, visitorUserId);
+
+ const topicModel = new TopicModel(db, share.ownerId, undefined, undefined, {
+ includeShareVisitor: true,
+ });
+ const topic = await findVisitorTopicOrThrow(topicModel, {
+ agentId: share.agentId,
+ topicId: input.topicId,
+ visitorUserId,
+ });
+
+ const runningOperationId = topic.metadata?.runningOperation?.operationId;
+ if (!runningOperationId || runningOperationId !== input.operationId) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'No matching running operation found on this topic',
+ });
+ }
+
+ const aiAgentService = new AiAgentService(db, share.ownerId, {
+ includeShareVisitor: true,
+ });
+
+ return { aiAgentService, share };
+};
+
export const shareChatRouter = router({
/**
* Execute a shared agent as a visitor — the gateway-transport mirror of
@@ -177,6 +218,8 @@ export const shareChatRouter = router({
/** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */
prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),
shareId: z.string(),
+ /** Queued behind a running turn; see `aiAgent.execAgent`'s `steer`. */
+ steer: z.boolean().optional(),
/** Absent → the run creates a new visitor topic (counted against the topic cap). */
topicId: z.string().nullish(),
}),
@@ -318,6 +361,7 @@ export const shareChatRouter = router({
interactiveStart: false,
prompt: input.prompt,
shareGate,
+ steer: input.steer,
// Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,
// so its spend rows must be separable from the creator's own chat
// spend (they land on the same account). The trigger rides
@@ -422,59 +466,72 @@ export const shareChatRouter = router({
* visitor's Stop / tab-close cannot reach the server: the run keeps streaming
* and consuming the creator's budget until it finishes on its own.
*
- * Authorization is intentionally stricter than `execAgent`/`getMessages`: it
- * is not enough that the topic belongs to this visitor — the `operationId`
- * must also match the operation CURRENTLY recorded as running on that topic.
- * Without that check a visitor could pass an arbitrary operationId
- * (topics/operations are creator-owned rows) and interrupt an unrelated run
- * on the creator's account.
+ * Authorization is intentionally stricter than `execAgent`/`getMessages`;
+ * see {@link authorizeVisitorRunningOperation}.
*/
interruptTask: shareChatProcedure
.input(ShareTopicScopeSchema.extend({ operationId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);
+ const { aiAgentService, share } = await authorizeVisitorRunningOperation(
+ ctx.serverDB,
+ ctx.userId,
+ input,
+ );
- const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {
- includeShareVisitor: true,
- });
- const topic = await findVisitorTopicOrThrow(topicModel, {
- agentId: share.agentId,
- topicId: input.topicId,
- visitorUserId: ctx.userId,
- });
+ log(
+ 'interruptTask: share=%s visitor=%s topic=%s operation=%s',
+ input.shareId,
+ ctx.userId,
+ input.topicId,
+ input.operationId,
+ );
- const runningOperationId = topic.metadata?.runningOperation?.operationId;
- if (!runningOperationId || runningOperationId !== input.operationId) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'No matching running operation found on this topic',
+ try {
+ return await aiAgentService.interruptTask({
+ operationId: input.operationId,
+ topicId: input.topicId,
+ });
+ } catch (error: any) {
+ if (error instanceof TRPCError) throw error;
+
+ throw toVisitorSafeStartupError('interruptTask', error, {
+ showErrorDetails: share.shareConfig.showErrorDetails,
});
}
+ }),
- // Creator-scoped service, same as `execAgent` — the run's operation /
- // thread rows were written under the creator's identity, so the
- // underlying `interruptTask` implementation must resolve them there.
- const aiAgentService = new AiAgentService(ctx.serverDB, share.ownerId, {
- includeShareVisitor: true,
- });
+ /**
+ * The visitor counterpart of `aiAgent.setQueuedMessages`: a visitor can queue
+ * follow-ups behind a share run too, and needs the same early hand-back.
+ * Authorized exactly like `interruptTask`.
+ */
+ setQueuedMessages: shareChatProcedure
+ .input(ShareTopicScopeSchema.extend({ operationId: z.string(), pending: z.boolean() }))
+ .mutation(async ({ input, ctx }) => {
+ const { aiAgentService, share } = await authorizeVisitorRunningOperation(
+ ctx.serverDB,
+ ctx.userId,
+ input,
+ );
log(
- 'interruptTask: share=%s visitor=%s topic=%s operation=%s',
+ 'setQueuedMessages: share=%s visitor=%s topic=%s operation=%s pending=%s',
input.shareId,
ctx.userId,
input.topicId,
input.operationId,
+ input.pending,
);
try {
- return await aiAgentService.interruptTask({
+ return await aiAgentService.setQueuedMessages({
operationId: input.operationId,
- topicId: input.topicId,
+ pending: input.pending,
});
} catch (error: any) {
if (error instanceof TRPCError) throw error;
- throw toVisitorSafeStartupError('interruptTask', error, {
+ throw toVisitorSafeStartupError('setQueuedMessages', error, {
showErrorDetails: share.shareConfig.showErrorDetails,
});
}
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 1f44ae67a96..f657fa75d77 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1980,6 +1980,33 @@ describe('AgentRuntimeService', () => {
});
});
+ describe('setQueuedMessages', () => {
+ it('writes the flag for an operation owned by the caller', async () => {
+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: mockUserId });
+ mockCoordinator.setQueuedMessages.mockResolvedValue(undefined);
+
+ await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(true);
+
+ expect(mockCoordinator.setQueuedMessages).toHaveBeenCalledWith('op-1', true);
+ });
+
+ it("refuses another user's operation", async () => {
+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'someone-else' });
+
+ await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(false);
+
+ expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();
+ });
+
+ it('refuses an unknown operation', async () => {
+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);
+
+ await expect(service.setQueuedMessages('op-missing', false)).resolves.toBe(false);
+
+ expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();
+ });
+ });
+
describe('interruptOperation', () => {
it('should interrupt a running operation', async () => {
mockCoordinator.loadAgentState.mockResolvedValue({
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index ccf138df921..1c3754180e4 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -613,6 +613,36 @@ export class AgentRuntimeService {
return true;
}
+ /**
+ * Record whether the client still holds user messages queued behind a run.
+ * Only the run's owner may flag it; an unknown or foreign operation is a
+ * no-op, so a caller cannot touch another user's run by guessing its id.
+ *
+ * @returns true when the flag was written
+ */
+ async setQueuedMessages(operationId: string, pending: boolean): Promise<boolean> {
+ const metadata = await this.coordinator.getOperationMetadata(operationId);
+ if (!metadata || metadata.userId !== this.userId) return false;
+
+ await this.coordinator.setQueuedMessages(operationId, pending);
+ log('[%s] Queued messages flag set to %s', operationId, pending);
+ return true;
+ }
+
+ /**
+ * 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.
+ */
+ private async readQueuedMessagesFlag(operationId: string, stepIndex: number): Promise<boolean> {
+ try {
+ return await this.coordinator.hasQueuedMessages(operationId);
+ } catch (error) {
+ log('[%s][%d] Queued messages flag read failed: %O', operationId, stepIndex, error);
+ return false;
+ }
+ }
+
/** Load the authoritative runtime state for a deterministic intervention continuation. */
async loadInterventionContinuationState(operationId: string): Promise<AgentState | null> {
return this.coordinator.loadAgentState(operationId);
@@ -1959,6 +1989,22 @@ export class AgentRuntimeService {
}
}
+ // 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.
+ // 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 this.readQueuedMessagesFlag(operationId, stepIndex);
+ if (hasQueuedMessages !== Boolean(currentContext.stepContext?.hasQueuedMessages)) {
+ const stepContext = { ...currentContext.stepContext };
+ if (hasQueuedMessages) stepContext.hasQueuedMessages = true;
+ else delete stepContext.hasQueuedMessages;
+ currentContext = { ...currentContext, stepContext };
+ }
+ }
+
// Execute step (skipped when force-finishing a parked supervisor op).
const startAt = Date.now();
logToolCallPc(operationId, stepIndex, 'post.runtime_step_entered', () => ({
diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
index 952f7a3832e..b36d2b41083 100644
--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -40,6 +40,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
isInterrupted: vi.fn().mockResolvedValue(false),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index c06137ca821..f4c706bb72e 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -29,6 +29,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
isInterrupted: vi.fn().mockResolvedValue(false),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
tryClaimStep: vi.fn().mockResolvedValue(true),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
refreshStepLock: vi.fn().mockResolvedValue(true),
@@ -1858,3 +1859,86 @@ describe('AgentRuntimeService.executeStep - Agent Share authorization revoked mi
dispatchHooks.mockRestore();
});
});
+
+describe('AgentRuntimeService.executeStep - queued messages flag', () => {
+ const runStep = async (
+ readFlag: () => Promise<boolean>,
+ context: Record<string, unknown> = { payload: {}, phase: 'tools_batch_result' },
+ ) => {
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+ const coordinator = (service as any).coordinator;
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ lastModified: new Date().toISOString(),
+ metadata: {},
+ status: 'running',
+ stepCount: 1,
+ });
+ coordinator.hasQueuedMessages = vi.fn(readFlag);
+ vi.spyOn((service as any).completionLifecycle, 'registerFileWorks').mockResolvedValue(
+ undefined,
+ );
+ vi.spyOn((service as any).completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ vi.spyOn((service as any).completionLifecycle, 'dispatchHooks').mockResolvedValue(undefined);
+ const step = vi.fn().mockResolvedValue({
+ events: [],
+ newState: {
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {},
+ status: 'done',
+ stepCount: 2,
+ },
+ nextContext: undefined,
+ });
+ (service as any).createAgentRuntime = vi.fn().mockResolvedValue({ runtime: { step } });
+
+ await service.executeStep({
+ context: context as any,
+ operationId: 'op-queued',
+ stepIndex: 1,
+ });
+
+ return { hasQueuedMessages: coordinator.hasQueuedMessages, step };
+ };
+
+ // Regression: queued follow-ups only ever reached the step context in the
+ // browser runtime, so a server run never took the agent's early hand-back
+ // and the follow-up waited for every remaining step.
+ it('hands the flag to the agent through the step context', async () => {
+ const { hasQueuedMessages, step } = await runStep(async () => true);
+
+ expect(hasQueuedMessages).toHaveBeenCalledWith('op-queued');
+ expect(step.mock.calls[0][1].stepContext).toEqual(
+ expect.objectContaining({ hasQueuedMessages: true }),
+ );
+ });
+
+ // Regression: the flag was only ever added, so a context that arrived still
+ // carrying `true` kept ending the turn after the user emptied the queue.
+ it('drops a carried-in flag once the queue is empty', async () => {
+ const { step } = await runStep(async () => false, {
+ payload: {},
+ phase: 'tools_batch_result',
+ stepContext: { hasQueuedMessages: true, todos: { items: [] } },
+ });
+
+ const stepContext = step.mock.calls[0][1].stepContext;
+ expect(stepContext?.hasQueuedMessages).toBeUndefined();
+ expect(stepContext).toEqual(expect.objectContaining({ todos: { items: [] } }));
+ });
+
+ it('leaves the step context untouched when nothing is queued', async () => {
+ const { step } = await runStep(async () => false);
+
+ expect(step.mock.calls[0][1].stepContext?.hasQueuedMessages).toBeUndefined();
+ });
+
+ it('keeps the run going when the flag cannot be read', async () => {
+ const { step } = await runStep(async () => {
+ throw new Error('redis down');
+ });
+
+ expect(step).toHaveBeenCalledTimes(1);
+ expect(step.mock.calls[0][1].stepContext?.hasQueuedMessages).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
index 6e0faaf3bd8..0f57bed99e2 100644
--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -28,6 +28,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
isInterrupted: vi.fn().mockResolvedValue(false),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
index 55b12e234c8..865a860e410 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
@@ -316,3 +316,43 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {
expect(userMessageCall()![0]).toMatchObject({ parentId: 'thread-spine-1' });
});
});
+
+describe('AiAgentService.execAgent - queued follow-up steer mark', () => {
+ let service: AiAgentService;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockImplementation(async (payload: { role: string }) => ({
+ id: payload.role === 'user' ? 'user-msg-1' : 'assistant-msg-1',
+ }));
+ mockGetLatestSpineMessageId.mockResolvedValue('spine-head-1');
+ mockGetLatestNonToolMessageId.mockResolvedValue(undefined);
+ mockTryReserve.mockResolvedValue(true);
+ mockReleaseReservation.mockResolvedValue(undefined);
+
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ // Regression: the gateway path persisted a queued follow-up without its steer
+ // mark, so it rendered as a new turn instead of a continuation.
+ it('persists the steer mark on the user turn', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Follow up',
+ steer: true,
+ });
+
+ expect(userMessageCall()![0].metadata).toMatchObject({ steer: true });
+ });
+
+ it('leaves an ordinary user turn unmarked', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Hello',
+ });
+
+ expect(userMessageCall()![0].metadata?.steer).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index c99068b499b..0c681b21fd6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -690,6 +690,7 @@ export class AiAgentService {
provider: providerOverride,
stream,
title,
+ steer,
trigger,
cronJobId,
taskId,
@@ -1004,6 +1005,7 @@ export class AiAgentService {
resume,
runFromHistory,
shareGate,
+ steer,
throwIfExecutionAborted,
title,
trigger,
@@ -1577,6 +1579,17 @@ export class AiAgentService {
return this.interventionController.interruptTask(params);
}
+ /**
+ * Flags whether the composer still holds user messages queued behind a run.
+ * Delegates to {@link InterventionController}.
+ */
+ async setQueuedMessages(params: {
+ operationId: string;
+ pending: boolean;
+ }): Promise<{ success: boolean }> {
+ return this.interventionController.setQueuedMessages(params);
+ }
+
/** Settle a parked approval batch and terminate its operation. */
stopPendingApproval(params: {
approvalResolutionRequestId?: string;
diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
index 6a5cd237abb..be55a7a8e8a 100644
--- a/apps/server/src/services/aiAgent/intervention/InterventionController.ts
+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
@@ -48,6 +48,24 @@ export class InterventionController {
this.deps = deps;
}
+ /**
+ * Mirrors whether the composer still holds user messages queued behind a
+ * run, so the run hands its turn back at the next step boundary.
+ *
+ * Returns:
+ * - `success: false` when the operation is unknown or not owned by this user.
+ */
+ async setQueuedMessages(params: {
+ operationId: string;
+ pending: boolean;
+ }): Promise<{ success: boolean }> {
+ const { operationId, pending } = params;
+ const success = await this.deps.agentRuntimeService.setQueuedMessages(operationId, pending);
+ log('setQueuedMessages: operationId=%s, pending=%s, success=%s', operationId, pending, success);
+
+ return { success };
+ }
+
/**
* Interrupts a running task and coordinates any device-hosted process shutdown.
*
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index b9fe95ca14c..955f37b8c91 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -340,6 +340,8 @@ export interface TurnSetupInput {
runFromHistory: boolean;
/** Shared-agent visitor gate — set only by the shareChat router. */
shareGate?: AgentShareGate;
+ /** The prompt was queued behind a running turn; see `ExecAgentParams.steer`. */
+ steer?: boolean;
throwIfExecutionAborted: (stage: string) => Promise<void>;
title?: string;
trigger?: string;
@@ -361,6 +363,7 @@ export interface TurnSetupResult {
provider: string;
requestTriggerMetadata: {
agentDispatch?: { kind: 'callAgent'; visibility: 'internal' };
+ steer?: true;
trigger?: RequestTrigger;
};
runAttachments: RunAttachments;
@@ -411,6 +414,7 @@ export const setupTurn = async (
resume,
runFromHistory,
shareGate,
+ steer,
throwIfExecutionAborted,
title,
trigger,
@@ -671,6 +675,9 @@ export const setupTurn = async (
// Bot-channel turns are inserted under the OWNER's userId; keep the real
// platform author alongside so the UI can attribute the bubble correctly.
...(botSender ? { botSender } : undefined),
+ // A follow-up queued behind a running turn renders as that turn's
+ // continuation; the client's optimistic row is replaced by this one.
+ ...(steer ? { steer: true as const } : undefined),
};
// Attachment ingestion: raw bot/IM `files` → S3, pre-uploaded
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index dbd2415ace2..b28c93b2c53 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -233,6 +233,12 @@ export interface InternalExecAgentParams extends ExecAgentParams {
shareGate?: AgentShareGate;
/** Abort startup before the agent runtime operation is created */
signal?: AbortSignal;
+ /**
+ * The prompt was queued while the previous turn was still running. The user
+ * message is persisted with `metadata.steer` so it renders as a continuation
+ * of that turn.
+ */
+ steer?: boolean;
/**
* Whether the LLM call should use streaming.
* Defaults to true. Set to false for non-streaming scenarios (e.g., bot integrations).
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 9da0cc98b3d..15e8dfe11dc 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -136,6 +136,8 @@ export interface ExecAgentTaskParams {
/** Tool identifiers the user @-mentioned in this message; the server enables them for this run. */
selectedToolIds?: string[];
slug?: string;
+ /** The prompt was queued behind a running turn and renders as its continuation. */
+ steer?: boolean;
/**
* Override what initiated this operation. Server defaults to `'chat'` when
* omitted. Pass a more specific value (`'cli'`, `'openapi'`, …) so the
@@ -291,6 +293,14 @@ class AiAgentService {
return await lambdaClient.aiAgent.interruptTask.mutate(params);
}
+ /**
+ * Tell a running server operation whether user messages are queued behind it,
+ * so it hands the turn back at its next step boundary.
+ */
+ async setQueuedMessages(params: { operationId: string; pending: boolean }) {
+ return await lambdaClient.aiAgent.setQueuedMessages.mutate(params);
+ }
+
/**
* Stop a run parked on tool approval: settle the pending tool rows and end
* the operation without running anything or continuing the model.
diff --git a/src/services/shareChat.ts b/src/services/shareChat.ts
index 79d79b4de8d..b9bea9dcbb1 100644
--- a/src/services/shareChat.ts
+++ b/src/services/shareChat.ts
@@ -7,6 +7,8 @@ export interface ShareChatExecParams {
clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };
prompt: string;
shareId: string;
+ /** The prompt was queued behind a running turn and renders as its continuation. */
+ steer?: boolean;
/** Absent → the server creates a new visitor topic (counted against the topic cap). */
topicId?: string | null;
}
@@ -45,6 +47,18 @@ class ShareChatService {
return await lambdaClient.shareChat.interruptTask.mutate({ operationId, shareId, topicId });
}
+ /**
+ * The visitor counterpart of `aiAgentService.setQueuedMessages`.
+ */
+ async setQueuedMessages(shareId: string, topicId: string, operationId: string, pending: boolean) {
+ return await lambdaClient.shareChat.setQueuedMessages.mutate({
+ operationId,
+ pending,
+ shareId,
+ topicId,
+ });
+ }
+
async refreshGatewayToken(shareId: string, topicId: string): Promise<{ token: string }> {
return await lambdaClient.shareChat.refreshGatewayToken.query({ shareId, topicId });
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 806e9e09e2f..1b4bc7c0188 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -920,6 +920,39 @@ describe('GatewayActionImpl', () => {
);
});
+ // Regression: a queued follow-up lost its steer mark on the gateway path, so
+ // the row the server persisted rendered as a new turn instead of a
+ // continuation of the interrupted one.
+ it('should forward the steer mark of a queued follow-up to execAgentTask', async () => {
+ const { action } = createExecuteTestAction();
+
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1', threadId: null, scope: 'main' },
+ message: 'Follow up',
+ metadata: { steer: true },
+ });
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: 'Follow up', steer: true }),
+ expect.anything(),
+ );
+ });
+
it('should forward current user intervention config to execAgentTask', async () => {
const { action } = createExecuteTestAction();
mockToolInterventionConfig.approvalMode = 'allow-list';
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/queuedMessagesFlag.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/queuedMessagesFlag.test.ts
new file mode 100644
index 00000000000..4489b0902a5
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/queuedMessagesFlag.test.ts
@@ -0,0 +1,171 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService } from '@/services/aiAgent';
+import { shareChatService } from '@/services/shareChat';
+import type { QueuedMessage } from '@/store/chat/slices/operation/types';
+import { useChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { flagQueuedMessagesOnRunStart } from '../transports/gateway/queuedMessagesFlag';
+
+const context = { agentId: 'agent-1', scope: 'main' as const, threadId: null, topicId: 'topic-1' };
+const contextKey = messageMapKey(context);
+
+const queued = (id: string): QueuedMessage => ({
+ content: `follow up ${id}`,
+ createdAt: 1,
+ id,
+ interruptMode: 'soft',
+});
+
+const operation = (id: string, overrides: Record<string, unknown> = {}) => ({
+ abortController: new AbortController(),
+ childOperationIds: [],
+ context,
+ id,
+ metadata: { serverOperationId: `server-${id}`, startTime: 1 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ ...overrides,
+});
+
+const seedOperations = (operations: ReturnType<typeof operation>[]) => {
+ useChatStore.setState({
+ operations: Object.fromEntries(operations.map((op) => [op.id, op])) as any,
+ operationsByContext: { [contextKey]: operations.map((op) => op.id) },
+ });
+};
+
+describe('queued messages flag', () => {
+ let setQueuedMessages: ReturnType<typeof vi.spyOn>;
+ let setShareQueuedMessages: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ setQueuedMessages = vi
+ .spyOn(aiAgentService, 'setQueuedMessages')
+ .mockResolvedValue({ success: true });
+ setShareQueuedMessages = vi
+ .spyOn(shareChatService, 'setQueuedMessages')
+ .mockResolvedValue({ success: true });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('flags the running Gateway run when a message is queued behind it', () => {
+ seedOperations([operation('gw')]);
+
+ useChatStore.getState().enqueueMessage(contextKey, queued('q1'), 'gw');
+
+ expect(setQueuedMessages).toHaveBeenCalledWith({ operationId: 'server-gw', pending: true });
+ });
+
+ it('clears the flag only once the last queued message is removed', async () => {
+ seedOperations([operation('gw')]);
+ const store = useChatStore.getState();
+ store.enqueueMessage(contextKey, queued('q1'), 'gw');
+ store.enqueueMessage(contextKey, queued('q2'), 'gw');
+ setQueuedMessages.mockClear();
+
+ store.removeQueuedMessage(contextKey, 'q1');
+ expect(setQueuedMessages).not.toHaveBeenCalled();
+
+ store.removeQueuedMessage(contextKey, 'q2');
+ // Writes for one operation are ordered, so the clear follows the in-flight flag.
+ await vi.waitFor(() =>
+ expect(setQueuedMessages).toHaveBeenCalledWith({ operationId: 'server-gw', pending: false }),
+ );
+ });
+
+ // Regression: queue-then-delete sent both writes at once, so a delayed
+ // `pending: true` could land last and end the run with an empty queue.
+ it('sends a queue-then-delete in order, finishing on the latest value', async () => {
+ seedOperations([operation('gw')]);
+ let settleFirst!: () => void;
+ setQueuedMessages.mockImplementationOnce(
+ () => new Promise((resolve) => (settleFirst = () => resolve({ success: true }))),
+ );
+ const store = useChatStore.getState();
+
+ store.enqueueMessage(contextKey, queued('q1'), 'gw');
+ store.removeQueuedMessage(contextKey, 'q1');
+ expect(setQueuedMessages).toHaveBeenCalledTimes(1);
+
+ settleFirst();
+ await vi.waitFor(() => expect(setQueuedMessages).toHaveBeenCalledTimes(2));
+ expect(setQueuedMessages).toHaveBeenLastCalledWith({
+ operationId: 'server-gw',
+ pending: false,
+ });
+ });
+
+ it('skips the follow-up write when the queue ends where the in-flight write left it', async () => {
+ seedOperations([operation('gw')]);
+ let settleFirst!: () => void;
+ setQueuedMessages.mockImplementationOnce(
+ () => new Promise((resolve) => (settleFirst = () => resolve({ success: true }))),
+ );
+ const store = useChatStore.getState();
+
+ store.enqueueMessage(contextKey, queued('q1'), 'gw');
+ store.removeQueuedMessage(contextKey, 'q1');
+ store.enqueueMessage(contextKey, queued('q2'), 'gw');
+
+ settleFirst();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(setQueuedMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not flag a run executing in the browser', () => {
+ seedOperations([operation('client', { metadata: { startTime: 1 }, type: 'execAgentRuntime' })]);
+
+ useChatStore.getState().enqueueMessage(contextKey, queued('q1'), 'client');
+
+ expect(setQueuedMessages).not.toHaveBeenCalled();
+ });
+
+ it('routes a share visitor run through the share endpoint', () => {
+ seedOperations([operation('gw', { context: { ...context, agentShareId: 'share-1' } })]);
+
+ useChatStore.getState().enqueueMessage(contextKey, queued('q1'), 'gw');
+
+ expect(setShareQueuedMessages).toHaveBeenCalledWith('share-1', 'topic-1', 'server-gw', true);
+ expect(setQueuedMessages).not.toHaveBeenCalled();
+ });
+
+ it('flags a run that starts with messages already queued', () => {
+ seedOperations([operation('gw')]);
+ useChatStore.setState({ queuedMessages: { [contextKey]: [queued('q1')] } });
+
+ flagQueuedMessagesOnRunStart(useChatStore.getState, contextKey);
+
+ expect(setQueuedMessages).toHaveBeenCalledWith({ operationId: 'server-gw', pending: true });
+ });
+
+ // Regression: every Gateway run used to send a `pending: false` request on
+ // start, even though nothing was ever queued behind it.
+ it('sends nothing when a run starts with an empty queue', () => {
+ seedOperations([operation('gw')]);
+
+ flagQueuedMessagesOnRunStart(useChatStore.getState, contextKey);
+
+ expect(setQueuedMessages).not.toHaveBeenCalled();
+ });
+
+ it('leaves group member runs to their supervisor', () => {
+ seedOperations([
+ operation('supervisor'),
+ operation('member', { parentOperationId: 'supervisor' }),
+ ]);
+
+ useChatStore.getState().enqueueMessage(contextKey, queued('q1'), 'supervisor');
+
+ expect(setQueuedMessages).toHaveBeenCalledTimes(1);
+ expect(setQueuedMessages).toHaveBeenCalledWith({
+ operationId: 'server-supervisor',
+ pending: true,
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 2f4c31987c2..bd67ca72b5e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1721,7 +1721,11 @@ export class ConversationLifecycleActionImpl {
messageContext: operationContext,
fileIds: fileIdList,
message,
- metadata: requestMetadata,
+ // The server persists the user row on this path, so a queued
+ // follow-up's steer mark must travel with the request.
+ metadata: (metadata as Pick<MessageMetadata, 'steer'> | undefined)?.steer
+ ? { ...requestMetadata, steer: true }
+ : requestMetadata,
onMessageAccepted: notifyMessageAccepted,
parentOperationId: operationId,
replacesOperationId: replaceableGatewayOperationId,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 3baa49c98be..7c717b9d81a 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -63,6 +63,7 @@ import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEvent
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
import { type GatewayMuxIdentity, getGatewayMux } from './muxRegistry';
+import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';
/**
* Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
@@ -545,6 +546,14 @@ export class GatewayActionImpl {
conn.client.sendInterrupt();
};
+ /**
+ * Mirror whether a conversation still has messages queued behind its running
+ * Gateway run. See {@link syncQueuedMessagesFlag}.
+ */
+ internal_syncQueuedMessagesFlag = (contextKey: string): void => {
+ syncQueuedMessagesFlag(this.#get, contextKey);
+ };
+
/**
* Get the connection status for a specific operation.
*/
@@ -628,7 +637,7 @@ export class GatewayActionImpl {
*/
messageContext?: ConversationContext;
/** Request metadata carried from the originating user message. */
- metadata?: Pick<MessageMetadata, 'trigger'>;
+ metadata?: Pick<MessageMetadata, 'steer' | 'trigger'>;
/** Called as soon as phase-1 returns with a persisted user message. */
onMessageAccepted?: () => void;
/** Called when the gateway session completes (agent finished running) */
@@ -805,6 +814,7 @@ export class GatewayActionImpl {
clientIds,
prompt: message,
shareId: agentShareId,
+ steer: metadata?.steer,
topicId: executionContext.topicId,
},
{ signal: abortSignal },
@@ -870,6 +880,9 @@ export class GatewayActionImpl {
resumeApprovals,
resumeToolResult,
selectedToolIds,
+ // A queued follow-up keeps its continuation mark on the row the
+ // server persists, which replaces the optimistic one.
+ steer: metadata?.steer,
trigger: metadata?.trigger,
userInterventionConfig,
},
@@ -1049,6 +1062,10 @@ export class GatewayActionImpl {
type: 'execServerAgentRuntime',
});
+ // A follow-up may have been queued while execAgentTask was still in flight,
+ // before this run had a server operation id to flag.
+ flagQueuedMessagesOnRunStart(this.#get, messageMapKey(resolvedMessageContext));
+
// Associate the server-created assistant message with the gateway operation
this.#get().associateMessageWithOperation(result.assistantMessageId, gatewayOpId);
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts
new file mode 100644
index 00000000000..3e16df63861
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts
@@ -0,0 +1,103 @@
+import { aiAgentService } from '@/services/aiAgent';
+import { shareChatService } from '@/services/shareChat';
+import type { ChatStore } from '@/store/chat/store';
+
+interface FlagWrite {
+ desired: boolean;
+ sent?: boolean;
+}
+
+/** In-flight flag writes, keyed by server operation id. */
+const flagWrites = new Map<string, FlagWrite>();
+
+/**
+ * Write one operation's flag in order. Queue then delete fires two writes; sent
+ * concurrently, a delayed `true` could land after the `false` and end the run
+ * with an empty queue. While a request is in flight only the latest wanted
+ * value is kept, and it is sent once that request settles.
+ */
+const writeFlag = (
+ serverOperationId: string,
+ pending: boolean,
+ send: (pending: boolean) => Promise<unknown>,
+) => {
+ const inFlight = flagWrites.get(serverOperationId);
+ if (inFlight) {
+ inFlight.desired = pending;
+ return;
+ }
+
+ const write: FlagWrite = { desired: pending };
+ flagWrites.set(serverOperationId, write);
+
+ const drain = async () => {
+ while (write.sent !== write.desired) {
+ const value = write.desired;
+ try {
+ await send(value);
+ write.sent = value;
+ } catch (error) {
+ console.error('[Gateway] setQueuedMessages failed:', error);
+ // Retry only for a newer value; repeating the failed one would loop.
+ if (write.desired === value) break;
+ }
+ }
+ flagWrites.delete(serverOperationId);
+ };
+
+ void drain();
+};
+
+/**
+ * Mirror whether a conversation still has messages queued behind its running
+ * Gateway run, so the server-side run hands its turn back at the next step
+ * boundary instead of finishing every remaining step before the follow-up
+ * starts.
+ *
+ * Only top-level Gateway runs are flagged. A client-side run reads the queue
+ * straight from the store, and a group member run belongs to its supervisor,
+ * which owns the queue. Best-effort: a failed request only means the follow-up
+ * waits for the run to end, which is how it behaved before the flag existed.
+ */
+export const syncQueuedMessagesFlag = (get: () => ChatStore, contextKey: string): void => {
+ const state = get();
+ const pending = (state.queuedMessages?.[contextKey]?.length ?? 0) > 0;
+
+ for (const id of state.operationsByContext?.[contextKey] ?? []) {
+ const operation = state.operations?.[id];
+ const serverOperationId = operation?.metadata.serverOperationId;
+ if (
+ !operation ||
+ !serverOperationId ||
+ operation.type !== 'execServerAgentRuntime' ||
+ operation.status !== 'running'
+ )
+ continue;
+
+ const parent = operation.parentOperationId
+ ? state.operations[operation.parentOperationId]
+ : undefined;
+ if (parent?.type === 'execServerAgentRuntime') continue;
+
+ const { agentShareId, topicId } = operation.context;
+ // Share visitors have no access to the owner-scoped endpoint.
+ if (agentShareId && !topicId) continue;
+
+ writeFlag(serverOperationId, pending, (value) =>
+ agentShareId
+ ? shareChatService.setQueuedMessages(agentShareId, topicId!, serverOperationId, value)
+ : aiAgentService.setQueuedMessages({ operationId: serverOperationId, pending: value }),
+ );
+ }
+};
+
+/**
+ * Flag a Gateway run that has just started, but only when messages were already
+ * queued while it was being created. A run starts unflagged, so an empty queue
+ * needs no request.
+ */
+export const flagQueuedMessagesOnRunStart = (get: () => ChatStore, contextKey: string): void => {
+ if (!get().queuedMessages?.[contextKey]?.length) return;
+
+ syncQueuedMessagesFlag(get, contextKey);
+};
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index a8ca9e80b92..8bef925e9e2 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -817,6 +817,10 @@ export class OperationActionsImpl {
n(`enqueueMessage/${contextKey}`),
);
+ // Soft: a running Gateway run hands its turn back at the next step boundary
+ // instead of finishing every remaining step before the follow-up starts.
+ if (message.interruptMode === 'soft') this.#get().internal_syncQueuedMessagesFlag(contextKey);
+
// Hard interrupt: cancel the running operation
if (message.interruptMode === 'hard' && runningOperationId) {
const op = this.#get().operations[runningOperationId];
@@ -886,6 +890,10 @@ export class OperationActionsImpl {
false,
n(`removeQueuedMessage/${contextKey}/${messageId}`),
);
+
+ // The last queued message is gone: let the run finish its turn normally.
+ if (!this.#get().queuedMessages[contextKey]?.length)
+ this.#get().internal_syncQueuedMessagesFlag(contextKey);
};
clearMessageQueue = (contextKey: string): void => {
@@ -896,6 +904,8 @@ export class OperationActionsImpl {
false,
n(`clearMessageQueue/${contextKey}`),
);
+
+ this.#get().internal_syncQueuedMessagesFlag(contextKey);
};
}