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(chat): queue follow-ups behind a Gateway run on the server (#21243)

Arvin Xu18a24662866c
diff --git a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
index 3fdec1a8a6f..5264cf7dd75 100644
--- a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
@@ -7,10 +7,12 @@ import { agentSteerQueueRouter } from '../agentSteerQueue';
const mocks = vi.hoisted(() => ({
append: vi.fn(),
+ entryState: vi.fn(),
isRunningOperationAlive: vi.fn(),
list: vi.fn(),
liveCandidates: vi.fn(),
remove: vi.fn(),
+ snapshot: vi.fn(),
}));
vi.mock('@/database/models/topic', () => ({
@@ -20,7 +22,12 @@ vi.mock('@/database/models/topic', () => ({
}));
vi.mock('@/server/services/redis', () => ({
redisService: {
- steerQueue: { append: mocks.append, list: mocks.list, remove: mocks.remove },
+ steerQueue: {
+ append: mocks.append,
+ entryState: mocks.entryState,
+ remove: mocks.remove,
+ snapshot: mocks.snapshot,
+ },
},
}));
vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({
@@ -76,13 +83,45 @@ describe('agentSteerQueueRouter.append', () => {
mocks.isRunningOperationAlive.mockResolvedValue(true);
mocks.append.mockResolvedValue(1);
mocks.remove.mockResolvedValue(true);
+ mocks.entryState.mockResolvedValue('absent');
});
+ // ROOT CAUSE:
+ //
+ // A retry of an append whose answer was lost went through the liveness
+ // check first. Had the run ended meanwhile, it answered `idle` and the
+ // client sent the follow-up itself while the server still held (or had
+ // delivered) the first copy — the follow-up ran twice.
+ //
+ // Before: liveness decided first.
+ // After: what the server already holds for that id decides.
+ it.each([
+ ['still waiting', 'queued', 1],
+ ['being delivered', 'delivering', 0],
+ ['delivered', 'taken', 0],
+ ] as const)(
+ 'answers a retry of an entry %s as queued, whatever the run',
+ async (_l, state, length) => {
+ mocks.entryState.mockResolvedValue(state);
+ mocks.liveCandidates.mockReturnValue([]);
+
+ // `state` lets a client tell delivered (`taken`) from still on its way.
+ await expect(caller().append(appendInput)).resolves.toEqual({
+ id: 'q-1',
+ length,
+ queued: true,
+ state,
+ });
+ expect(mocks.append).not.toHaveBeenCalled();
+ },
+ );
+
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,
+ state: 'queued',
});
const [scope, entry, behindOperationId] = mocks.append.mock.calls[0];
@@ -102,6 +141,35 @@ describe('agentSteerQueueRouter.append', () => {
expect(entry.request.streamFeatures).toBeUndefined();
});
+ it('keeps the composer state it was sent from, up to a cap', async () => {
+ const editorData = { root: { children: [], type: 'root' } };
+ await caller().append({ ...appendInput, composer: { editorData } });
+ expect(mocks.append.mock.calls[0][1].composer).toEqual({ editorData });
+
+ const huge = { root: { text: 'x'.repeat(40 * 1024) } };
+ await caller().append({ ...appendInput, composer: { editorData: huge } });
+ expect(mocks.append.mock.calls[1][1].composer).toBeUndefined();
+ });
+
+ // ROOT CAUSE:
+ //
+ // One cap over the whole composer state dropped the attachment previews
+ // with a long editor document (and the reverse), so a reload lost both.
+ //
+ // Before: all or nothing.
+ // After: each part is kept or dropped on its own.
+ it('keeps the attachment previews when only the editor document is too large', async () => {
+ const filesPreview = [{ id: 'f1', name: 'a.png' }];
+ const huge = { root: { text: 'x'.repeat(40 * 1024) } };
+
+ await caller().append({ ...appendInput, composer: { editorData: huge, filesPreview } });
+
+ expect(mocks.append.mock.calls[0][1].composer).toEqual({
+ editorData: undefined,
+ filesPreview,
+ });
+ });
+
it('tells the client to send directly when no run is live', async () => {
mocks.isRunningOperationAlive.mockResolvedValue(false);
@@ -133,6 +201,7 @@ describe('agentSteerQueueRouter.append', () => {
id: 'q-1',
length: 0,
queued: true,
+ state: 'taken',
});
});
@@ -172,38 +241,145 @@ describe('agentSteerQueueRouter.append', () => {
});
it.each([
- [undefined, 'unavailable'],
+ ['notStored', '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 });
});
+
+ // ROOT CAUSE:
+ //
+ // A retried append whose earlier try may be stored looked its id up first,
+ // but a Redis that could not be read fell through to the liveness
+ // check: with the run ended it answered `idle`, and the client sent its copy
+ // while the first one could still run later.
+ //
+ // Before: an unreadable lookup counted as "not there".
+ // After: it is an unknown outcome, whatever the run.
+ it('answers unknown when the retry lookup cannot read Redis', async () => {
+ mocks.entryState.mockResolvedValue(undefined);
+ mocks.liveCandidates.mockReturnValue([]);
+
+ await expect(caller().append(appendInput)).rejects.toMatchObject({
+ code: 'SERVICE_UNAVAILABLE',
+ });
+ expect(mocks.append).not.toHaveBeenCalled();
+ });
+
+ // ROOT CAUSE:
+ //
+ // A Redis outage (circuit open) looked like "not stored", so a retry of an
+ // append that had landed earlier was answered `unavailable` and sent by the
+ // client while the server still held the first copy.
+ //
+ // Before: no client meant "send directly".
+ // After: no client is an unknown outcome (Redis is a deployment requirement).
+ it('answers unknown, not send-directly, while Redis is out', async () => {
+ mocks.append.mockResolvedValue(undefined);
+
+ await expect(caller().append(appendInput)).rejects.toMatchObject({
+ code: 'SERVICE_UNAVAILABLE',
+ });
+ });
});
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);
+ mocks.snapshot.mockResolvedValue({
+ delivering: [],
+ waiting: [
+ { createdAt: 1, id: 'mine', request: { prompt: 'a' }, userId: 'user-1' },
+ { createdAt: 2, id: 'theirs', request: { prompt: 'b' }, userId: 'user-2' },
+ ],
+ });
});
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' },
+ expect.objectContaining({ createdAt: 1, delivering: false, id: 'mine', prompt: 'a' }),
+ ]);
+ });
+
+ // ROOT CAUSE:
+ //
+ // A drained entry left the waiting list before its run confirmed it, so a
+ // client treated it as delivered and dropped it, though a failed delivery
+ // returns it to the queue — invisible until another run or a reload.
+ //
+ // Before: only waiting entries were listed.
+ // After: taken-but-unconfirmed ones are listed as `delivering`, from one
+ // atomic read, with what a reloaded client needs to resend them as typed.
+ it('lists follow-ups a run took but has not confirmed as delivering', async () => {
+ const composer = { editorData: { root: { type: 'root' } }, filesPreview: [{ id: 'f1' }] };
+ mocks.snapshot.mockResolvedValue({
+ delivering: [
+ {
+ composer,
+ createdAt: 0,
+ id: 'taken',
+ request: { prompt: 'z', selectedSkillIds: ['s1'] },
+ userId: 'user-1',
+ },
+ { createdAt: 3, id: 'other', request: { prompt: 'y' }, userId: 'user-2' },
+ ],
+ waiting: [{ createdAt: 1, id: 'mine', request: { prompt: 'a' }, userId: 'user-1' }],
+ });
+
+ await expect(caller().list({ topicId: 'tpc-1' })).resolves.toEqual([
+ expect.objectContaining({
+ delivering: true,
+ editorData: composer.editorData,
+ filesPreview: composer.filesPreview,
+ id: 'taken',
+ selectedSkillIds: ['s1'],
+ }),
+ expect.objectContaining({ delivering: false, id: 'mine' }),
]);
});
- it('removes only the caller’s own follow-ups', async () => {
- await expect(caller().remove({ id: 'theirs', topicId: 'tpc-1' })).resolves.toEqual({
- removed: false,
+ // ROOT CAUSE:
+ //
+ // Without a Redis client the entry's state is unknown, but the withdrawal
+ // answered `absent`: Delete reported success and Edit / Send now resent a
+ // follow-up the server could still deliver.
+ //
+ // Before: an outage read as "never stored".
+ // After: it is an error, so the client keeps the row and retries.
+ it('refuses to answer a withdrawal while Redis is out', async () => {
+ mocks.entryState.mockResolvedValue(undefined);
+
+ await expect(caller().remove({ id: 'mine', topicId: 'tpc-1' })).rejects.toMatchObject({
+ code: 'SERVICE_UNAVAILABLE',
+ });
+ });
+
+ it('refuses to list while Redis is out, rather than reporting an empty queue', async () => {
+ mocks.snapshot.mockRejectedValue(new Error('Redis is unavailable'));
+
+ await expect(caller().list({ topicId: 'tpc-1' })).rejects.toMatchObject({
+ code: 'SERVICE_UNAVAILABLE',
});
+ });
+
+ it.each([
+ ['removed', true],
+ ['delivering', false],
+ ['taken', false],
+ ['absent', false],
+ ] as const)('withdraws in one step and says where it is: %s', async (state, removed) => {
+ mocks.entryState.mockResolvedValue(state);
+
await expect(caller().remove({ id: 'mine', topicId: 'tpc-1' })).resolves.toEqual({
- removed: true,
+ removed,
+ state,
});
- expect(mocks.remove).toHaveBeenCalledTimes(1);
+ expect(mocks.entryState).toHaveBeenCalledWith(
+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },
+ 'mine',
+ { remove: true },
+ );
});
});
diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.ts
index 5e031594480..9ac7d5c2757 100644
--- a/apps/server/src/routers/lambda/agentSteerQueue.ts
+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts
@@ -56,9 +56,39 @@ const AppendSchema = z.object({
.string()
.regex(/^[\w-]{1,64}$/, 'Use letters, digits, `_` or `-` (at most 64)')
.optional(),
+ /**
+ * The composer state the follow-up was sent from, stored opaquely so a
+ * reloaded client can show and resend it as typed. Dropped above the cap.
+ */
+ composer: z
+ .object({
+ editorData: z.record(z.string(), z.unknown()).optional(),
+ /** Attachment previews (id, name, type, url) the tray and Edit rebuild uploads from. */
+ filesPreview: z.array(z.record(z.string(), z.unknown())).max(50).optional(),
+ })
+ .optional(),
request: QueuedRequestSchema,
});
+/**
+ * Composer state kept with an entry. Each part has its own cap, so a long
+ * editor document never costs the attachment previews, nor the reverse.
+ */
+const MAX_EDITOR_DATA_BYTES = 32 * 1024;
+const MAX_FILES_PREVIEW_BYTES = 16 * 1024;
+const within = (value: unknown, bytes: number) =>
+ value !== undefined && JSON.stringify(value).length <= bytes;
+const storedComposer = (composer: z.infer<typeof AppendSchema>['composer']) => {
+ if (!composer) return;
+ const editorData = within(composer.editorData, MAX_EDITOR_DATA_BYTES)
+ ? composer.editorData
+ : undefined;
+ const filesPreview = within(composer.filesPreview, MAX_FILES_PREVIEW_BYTES)
+ ? composer.filesPreview
+ : undefined;
+ return editorData || filesPreview ? { editorData, filesPreview } : undefined;
+};
+
const steerQueueProcedure = wsCompatProcedure.use(serverDatabase);
const steerQueueWriteProcedure = steerQueueProcedure.use(withScopedPermission('message:create'));
@@ -105,6 +135,20 @@ export const agentSteerQueueRouter = router({
});
const scope = toScope({ threadId: request.appContext?.threadId, topicId }, ctx.userId);
+ // A retry of an append whose answer was lost: what the server already holds
+ // decides, before liveness — the run may have ended since, but the entry is
+ // still delivered (or was), so the client must never send it too.
+ if (input.id) {
+ const state = await redisService.steerQueue.entryState(scope, input.id);
+ // Redis cannot be read: an earlier try may be stored, and the run may
+ // have ended since — neither "queued" nor "send directly".
+ if (!state)
+ throw new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Queue unavailable' });
+ if (state === 'queued')
+ return { id: input.id, length: 1, queued: true as const, state: 'queued' as const };
+ if (state === 'delivering' || state === 'taken')
+ return { id: input.id, length: 0, queued: true as const, state };
+ }
const liveRuns = await findOwnLiveRuns(
{ db: ctx.serverDB, workspaceId: ctx.workspaceId },
scope,
@@ -117,6 +161,7 @@ export const agentSteerQueueRouter = router({
const entry: QueuedFollowUp = {
audit: { clientIp: ctx.clientIp ?? undefined, userAgent: ctx.userAgent ?? undefined },
+ composer: storedComposer(input.composer),
createdAt: Date.now(),
id: input.id ?? randomUUID(),
request: {
@@ -144,11 +189,18 @@ export const agentSteerQueueRouter = router({
// 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 };
+ // Taken back after its command failed: definitely not stored.
+ if (length === 'notStored') return { queued: false as const, reason: 'unavailable' as const };
+ // Redis is a deployment requirement, so no client is an outage: an earlier
+ // try of this id may have been stored. Unknown — the client keeps it the
+ // server's and retries the same id.
+ if (length === undefined)
+ throw new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Queue unavailable' });
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 };
+ if (length === 'taken')
+ return { id: entry.id, length: 0, queued: true as const, state: 'taken' 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
@@ -165,10 +217,14 @@ export const agentSteerQueueRouter = router({
}
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 };
+ return { id: entry.id, length, queued: true as const, state: 'queued' as const };
}),
- /** The follow-ups waiting on a conversation, oldest first. */
+ /**
+ * The follow-ups on a conversation that are not delivered yet, oldest first.
+ * `delivering` ones were taken by a run that has not confirmed them: they
+ * cannot be withdrawn, and come back as waiting should the delivery fail.
+ */
list: steerQueueProcedure.input(ScopeSchema).query(async ({ input, ctx }) => {
await assertCanUseAgentRunConversation({
db: ctx.serverDB,
@@ -177,29 +233,59 @@ export const agentSteerQueueRouter = router({
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,
+ const scope = toScope(input, ctx.userId);
+ let snapshot: { delivering: QueuedFollowUp[]; waiting: QueuedFollowUp[] };
+ try {
+ snapshot = await redisService.steerQueue.snapshot<QueuedFollowUp>(scope);
+ } catch (error) {
+ // Unknown, not empty: a client must keep what it shows as queued.
+ throw new TRPCError({
+ cause: error,
+ code: 'SERVICE_UNAVAILABLE',
+ message: 'Queue unavailable',
+ });
+ }
+ const { delivering, waiting } = snapshot;
+ const own = (entry: QueuedFollowUp) => entry.userId === ctx.userId;
+ const waitingIds = new Set(waiting.map((entry) => entry.id));
+ return [
+ ...waiting.filter(own).map((entry) => ({ entry, delivering: false })),
+ // An entry returned to the queue mid-read is listed once, as waiting.
+ ...delivering
+ .filter((entry) => own(entry) && !waitingIds.has(entry.id))
+ .map((entry) => ({ entry, delivering: true })),
+ ]
+ .sort((a, b) => a.entry.createdAt - b.entry.createdAt)
+ .map(({ entry, delivering: isDelivering }) => ({
+ createdAt: entry.createdAt,
+ delivering: isDelivering,
+ editorData: entry.composer?.editorData,
+ fileIds: entry.request.fileIds,
+ filesPreview: entry.composer?.filesPreview,
+ id: entry.id,
+ mentionedAgents: entry.request.mentionedAgents,
+ prompt: entry.request.prompt,
+ selectedSkillIds: entry.request.selectedSkillIds,
+ selectedToolIds: entry.request.selectedToolIds,
}));
}),
/**
- * Withdraw a queued follow-up. `removed: false` means it is gone already —
- * most likely a finishing run just started it.
+ * Withdraw a queued follow-up, in one step with reading where it is:
+ * `removed`, or why not — `delivering` (a run took it and has not settled;
+ * it may still come back), `taken` (delivered) or `absent` (never stored).
+ * The queue is the caller's own, so only their follow-ups can be withdrawn.
*/
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) };
+ const state = await redisService.steerQueue.entryState(toScope(input, ctx.userId), input.id, {
+ remove: true,
+ });
+ // Without Redis nothing is known: it may still be delivered, so it must
+ // neither read as withdrawn nor be resent.
+ if (!state)
+ throw new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Queue unavailable' });
+ return { removed: state === 'removed', state };
}),
});
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index 5503eb9a475..d5ee7c561b9 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -36,6 +36,12 @@ export type QueuedFollowUpRequest = Omit<
export interface QueuedFollowUp extends SteerQueueEntry {
/** Server-derived provenance of the request that queued it. */
audit?: { clientIp?: string; userAgent?: string };
+ /**
+ * The composer state the follow-up was sent from, opaque to the server, so a
+ * client that reloads can show and resend it exactly as typed (selections,
+ * mentions). Never used to run it.
+ */
+ composer?: { editorData?: Record<string, unknown>; filesPreview?: Record<string, unknown>[] };
request: QueuedFollowUpRequest;
/** Who queued it; only the run owner's own follow-ups are started for them. */
userId: string;
diff --git a/apps/server/src/services/redis/steerQueue.test.ts b/apps/server/src/services/redis/steerQueue.test.ts
index 4bf2e8822be..1d772dec2b1 100644
--- a/apps/server/src/services/redis/steerQueue.test.ts
+++ b/apps/server/src/services/redis/steerQueue.test.ts
@@ -28,10 +28,13 @@ const createFakeRedis = () => {
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);
+ // Whether the scripts' `pushFront` renews the queue TTL, read off their source.
+ let pushFrontRenewsTtl = false;
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)]);
+ if (pushFrontRenewsTtl) ttls.set(qkey, 24 * 60 * 60);
batchesOf(pkey).delete(id);
}
}
@@ -40,9 +43,32 @@ const createFakeRedis = () => {
const evalScript = vi.fn(async (script: string, numKeys: number, ...rest: any[]) => {
const keys = rest.slice(0, numKeys);
const args = rest.slice(numKeys);
+ pushFrontRenewsTtl = /local function pushFront[\s\S]*?'EXPIRE', qkey[\s\S]*?\nend/.test(script);
const [key] = keys;
const list = listOf(key);
+ if (script.includes('local delivering = {}')) {
+ reclaim(key, keys[1], Number(args[0]));
+ return [listOf(key), [...batchesOf(keys[1]).values()].flatMap((batch) => batch.items)];
+ }
+ if (script.includes("return 'absent'")) {
+ const [, takenKey, drainedKey] = keys;
+ const [id, mode, now] = args;
+ reclaim(key, drainedKey, Number(now));
+ const current = listOf(key);
+ const index = current.findIndex((item) => header(item).id === id);
+ if (index >= 0) {
+ if (mode !== 'remove') return 'queued';
+ current.splice(index, 1);
+ lists.set(key, current);
+ return 'removed';
+ }
+ const inBatch = [...batchesOf(drainedKey).values()].some((batch) =>
+ batch.items.some((item) => header(item).id === id),
+ );
+ if (inBatch) return 'delivering';
+ return setOf(takenKey).has(id) ? 'taken' : 'absent';
+ }
if (script.includes('reclaimLapsed(KEYS[1], KEYS[3]')) {
const [, , pkey] = keys;
const [op, drainId, now, lease, , ...ended] = args;
@@ -148,6 +174,89 @@ describe('redisService.steerQueue', () => {
await expect(q.boundOperations(scope)).resolves.toMatchObject({ total: 0 });
});
+ it('shows a drained entry as delivering until its batch is settled', 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 expect(q.snapshot(scope)).resolves.toEqual({
+ delivering: [entry('a'), entry('b')],
+ waiting: [],
+ });
+
+ // `b` cannot join and goes back to wait; `a` is still on its way.
+ await q.settle(scope, 'd1', ['b']);
+ await expect(q.snapshot(scope)).resolves.toEqual({
+ delivering: [entry('a')],
+ waiting: [expect.objectContaining({ id: 'b' })],
+ });
+ await expect(q.entryState(scope, 'a')).resolves.toBe('delivering');
+
+ // `a` delivered.
+ await q.settle(scope, 'd1');
+ await expect(q.entryState(scope, 'a')).resolves.toBe('taken');
+ });
+
+ // ROOT CAUSE:
+ //
+ // A batch whose run crashed before settling stayed `delivering` after its
+ // lease lapsed, until a later drain reclaimed it: with no further run the
+ // user could neither withdraw nor resend it, and once the hash expired it
+ // read as delivered.
+ //
+ // Before: only a drain reclaimed lapsed batches.
+ // After: reading the queue or an entry's state reclaims them first.
+ it('returns a lapsed batch to the queue before reporting what is delivering', async () => {
+ vi.useFakeTimers();
+ await q.append(scope, entry('a'), 'op-1');
+ await q.drain(scope, 'op-1', [], 'd1');
+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);
+
+ await expect(q.snapshot(scope)).resolves.toEqual({
+ delivering: [],
+ waiting: [expect.objectContaining({ id: 'a' })],
+ });
+
+ await q.drain(scope, 'op-2', [], 'd2');
+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);
+ await expect(q.entryState(scope, 'a', { remove: true })).resolves.toBe('removed');
+ });
+
+ // ROOT CAUSE:
+ //
+ // A drain that took the whole list deleted the queue key; returning a lapsed
+ // batch recreated it without a TTL, so an abandoned follow-up never expired
+ // and could replay into an unrelated run much later.
+ //
+ // Before: the reclaimed queue had no expiry.
+ // After: moving entries back renews the queue TTL.
+ it('keeps the queue expiring after a lapsed batch recreates it', async () => {
+ vi.useFakeTimers();
+ await q.append(scope, entry('a'), 'op-1');
+ await q.drain(scope, 'op-1', [], 'd1');
+ redis.ttls.clear();
+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);
+
+ await q.snapshot(scope);
+
+ expect(redis.ttls.get('follow_ups:v1:u1:tpc-1:main')).toBe(24 * 60 * 60);
+ });
+
+ it('reports an outage instead of an empty queue', async () => {
+ getRedisServiceClient.mockResolvedValue(null);
+
+ await expect(q.snapshot(scope)).rejects.toThrow('unavailable');
+ await expect(q.entryState(scope, 'a')).resolves.toBeUndefined();
+ });
+
+ it('withdraws only a waiting entry, and says where any other one is', async () => {
+ await q.append(scope, entry('a'), 'op-1');
+
+ await expect(q.entryState(scope, 'a')).resolves.toBe('queued');
+ await expect(q.entryState(scope, 'a', { remove: true })).resolves.toBe('removed');
+ await expect(q.entryState(scope, 'a', { remove: true })).resolves.toBe('absent');
+ });
+
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');
@@ -268,7 +377,7 @@ describe('redisService.steerQueue', () => {
throw new Error('command timed out');
});
- await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBeUndefined();
+ await expect(q.append(scope, entry('a'), 'op-1')).resolves.toBe('notStored');
expect(await ids()).toEqual([]);
});
diff --git a/apps/server/src/services/redis/steerQueue.ts b/apps/server/src/services/redis/steerQueue.ts
index d5b63c3aa7c..ec0a2fa2747 100644
--- a/apps/server/src/services/redis/steerQueue.ts
+++ b/apps/server/src/services/redis/steerQueue.ts
@@ -103,7 +103,11 @@ local function joinBatch(expiry, items)
return tostring(expiry) .. SEP .. table.concat(items, SEP)
end
local function pushFront(qkey, items)
+ if #items == 0 then return end
for i = #items, 1, -1 do redis.call('LPUSH', qkey, unbind(items[i])) end
+ -- A drain that took the whole list deleted the queue key; the push recreated
+ -- it without a TTL, and an abandoned follow-up must still expire.
+ redis.call('EXPIRE', qkey, ${QUEUE_TTL_SECONDS})
end
local function reclaimLapsed(qkey, pkey, now)
local all = redis.call('HGETALL', pkey)
@@ -149,6 +153,57 @@ return length
/** KEYS[1] = queue */
const LIST_SCRIPT = `return redis.call('LRANGE', KEYS[1], 0, -1)`;
+/**
+ * Waiting entries and those in drained batches, read in one step so an entry
+ * moving between the two is never missed. A batch whose lease lapsed goes back
+ * to the queue first: nothing is delivering it any more.
+ *
+ * KEYS[1] = queue; KEYS[2] = drained batches; ARGV[1] = now ms.
+ * Returns `{ waiting, delivering }`.
+ */
+const SNAPSHOT_SCRIPT = `${LUA_HELPERS}
+reclaimLapsed(KEYS[1], KEYS[2], tonumber(ARGV[1]))
+local delivering = {}
+for _, batch in ipairs(redis.call('HVALS', KEYS[2])) do
+ local _, items = splitBatch(batch)
+ for _, item in ipairs(items) do table.insert(delivering, item) end
+end
+return { redis.call('LRANGE', KEYS[1], 0, -1), delivering }
+`;
+
+/**
+ * Where one entry is, in one step — and with ARGV[2] = 'remove', takes it out
+ * when it is still waiting. Returns `removed`, `queued`, `delivering` (a run
+ * took it and has not settled), `taken` (delivered) or `absent`.
+ *
+ * A batch whose lease lapsed goes back to the queue first, as in a drain.
+ *
+ * KEYS[1] = queue; KEYS[2] = taken ids; KEYS[3] = drained batches;
+ * ARGV[1] = id; ARGV[2] = 'remove' | 'peek'; ARGV[3] = now ms
+ */
+const ENTRY_STATE_SCRIPT = `${LUA_HELPERS}
+reclaimLapsed(KEYS[1], KEYS[3], tonumber(ARGV[3]))
+for _, item in ipairs(redis.call('LRANGE', KEYS[1], 0, -1)) do
+ if header(item) == ARGV[1] then
+ if ARGV[2] == 'remove' then
+ redis.call('LREM', KEYS[1], 1, item)
+ return 'removed'
+ end
+ return 'queued'
+ end
+end
+for _, batch in ipairs(redis.call('HVALS', KEYS[3])) do
+ local _, items = splitBatch(batch)
+ for _, item in ipairs(items) do
+ if header(item) == ARGV[1] then return 'delivering' end
+ end
+end
+if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return 'taken' end
+return 'absent'
+`;
+
+export type SteerQueueEntryState = 'absent' | 'delivering' | 'queued' | 'removed' | 'taken';
+
/**
* Entries a run would take: queued ones it owns, plus any in a lapsed batch
* (they go back unbound on the next drain).
@@ -296,9 +351,10 @@ const parseEntries = <T extends SteerQueueEntry>(raw: unknown): T[] => {
* 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.
+ * `append` returns `notStored` when it took back a write whose command failed —
+ * definitely not stored, so the client sends the message itself, as it did
+ * before this queue — and `undefined` without a Redis client. Redis is a
+ * deployment requirement, so that is an outage, where the state is unknown.
*/
export const steerQueue = {
/**
@@ -345,7 +401,7 @@ export const steerQueue = {
// 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;
+ return 'notStored' as const;
}
},
@@ -460,6 +516,56 @@ export const steerQueue = {
return parseEntries<T>(await redis.eval<unknown>(LIST_SCRIPT, 1, keyOf(scope)));
},
+ /**
+ * The entries not delivered yet, read atomically: `waiting` ones, and
+ * `delivering` ones a drain took that are not settled — on their way into a
+ * run, or back to the queue should that fail. A lapsed batch is returned to
+ * the queue first.
+ *
+ * @throws when Redis is unavailable — an outage is not an empty queue
+ */
+ async snapshot<T extends SteerQueueEntry>(
+ scope: SteerQueueScope,
+ ): Promise<{ delivering: T[]; waiting: T[] }> {
+ const redis = await getClient();
+ if (!redis) throw new Error('Redis is unavailable to read queued follow-ups');
+
+ const raw = await redis.eval<unknown>(
+ SNAPSHOT_SCRIPT,
+ 2,
+ keyOf(scope),
+ drainedKeyOf(scope),
+ Date.now(),
+ );
+ const [waiting, delivering] = Array.isArray(raw) ? raw : [];
+ return { delivering: parseEntries<T>(delivering), waiting: parseEntries<T>(waiting) };
+ },
+
+ /**
+ * Where one entry is (see {@link SteerQueueEntryState}); with `remove`, takes
+ * it out in the same step when it is still waiting. `undefined` without Redis:
+ * then nothing about it is known.
+ */
+ async entryState(
+ scope: SteerQueueScope,
+ id: string,
+ options?: { remove?: boolean },
+ ): Promise<SteerQueueEntryState | undefined> {
+ const redis = await getClient();
+ if (!redis) return;
+
+ return (await redis.eval<string>(
+ ENTRY_STATE_SCRIPT,
+ 3,
+ keyOf(scope),
+ takenKeyOf(scope),
+ drainedKeyOf(scope),
+ id,
+ options?.remove ? 'remove' : 'peek',
+ Date.now(),
+ )) as SteerQueueEntryState;
+ },
+
/**
* Removes one entry by id.
*
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 46edca7113b..7c619e19c2f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1607,12 +1607,14 @@
"input.viewOnlyGroup": "You can only view this group",
"input.warp": "New Line",
"input.warpWithKey": "Press <key/> to insert a line break",
+ "inputQueue.alreadyDelivered": "Already sent to the agent",
"inputQueue.delete": "Delete",
"inputQueue.edit": "Edit",
"inputQueue.enqueueRejected": "Queue is full. Try again after the current run finishes.",
"inputQueue.queuedHint": "Sends when the current step finishes",
"inputQueue.queuedMergeHint": "Merged and sent when the current step finishes",
"inputQueue.sendNow": "Send now (interrupts current run)",
+ "inputQueue.withdrawFailed": "Couldn’t take the message back. Try again.",
"intentUnderstanding.title": "Understanding your intent...",
"internalLink.agent.open": "Open agent",
"internalLink.preview.acceptance": "Acceptance",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index fff7506fcb7..617d79c9db4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1607,12 +1607,14 @@
"input.viewOnlyGroup": "您仅可查看该群组",
"input.warp": "换行",
"input.warpWithKey": "按 <key/> 换行",
+ "inputQueue.alreadyDelivered": "已经发给助理了",
"inputQueue.delete": "删除",
"inputQueue.edit": "编辑",
"inputQueue.enqueueRejected": "队列已满。请在当前运行完成后再试。",
"inputQueue.queuedHint": "当前步骤完成后发送",
"inputQueue.queuedMergeHint": "当前步骤完成后合并发送",
"inputQueue.sendNow": "立即发送(中断当前运行)",
+ "inputQueue.withdrawFailed": "没能撤回这条消息,请重试",
"intentUnderstanding.title": "正在理解你的意图…",
"internalLink.agent.open": "打开助理",
"internalLink.preview.acceptance": "验收",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 4e73f563b09..9791c4256cf 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -975,6 +975,8 @@ export default {
'inputQueue.queuedHint': 'Sends when the current step finishes',
'inputQueue.queuedMergeHint': 'Merged and sent when the current step finishes',
'inputQueue.sendNow': 'Send now (interrupts current run)',
+ 'inputQueue.alreadyDelivered': 'Already sent to the agent',
+ 'inputQueue.withdrawFailed': 'Couldn’t take the message back. Try again.',
'intentUnderstanding.title': 'Understanding your intent...',
'inviteMembers': 'Invite members',
'knowledgeBase.all': 'All Content',
diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsx
index 233802d62dc..09f67636c0a 100644
--- a/src/features/Conversation/ChatInput/QueueTray.tsx
+++ b/src/features/Conversation/ChatInput/QueueTray.tsx
@@ -1,6 +1,6 @@
'use client';
-import { ActionIcon, createStaticStyles, Flexbox, Icon, Image, Tooltip } from '@lobehub/ui';
+import { ActionIcon, createStaticStyles, Flexbox, Icon, Image, toast, Tooltip } from '@lobehub/ui';
import { ArrowUp, Info, ListEnd, Pencil, Trash2 } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,14 +13,13 @@ import {
type QueuedFile,
type QueuedMessage,
reconstructUploadFilesFromQueue,
- SEND_NOW_CANCEL_REASON,
} from '@/store/chat/slices/operation/types';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useFileStore } from '@/store/file';
import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';
import { useConversationStore } from '../store';
-import { createQueueSendNowGate } from './utils';
+import { createQueueSendNowGate, putQueuedMessageInEditor, sendQueuedMessageNow } from './utils';
const PREVIEW_SIZE = 28;
@@ -202,7 +201,7 @@ const QueueTray = memo(() => {
);
const queuedMessages = useChatStore((s) => operationSelectors.getQueuedMessages(context)(s));
- const removeQueuedMessage = useChatStore((s) => s.removeQueuedMessage);
+ const withdrawQueuedMessage = useChatStore((s) => s.withdrawQueuedMessage);
const dispatchChatUploadFileList = useFileStore((s) => s.dispatchChatUploadFileList);
const editor = useConversationStore((s) => s.editor);
const sendNowGate = useSingleton(createQueueSendNowGate);
@@ -211,17 +210,32 @@ const QueueTray = memo(() => {
// input area, so the user can tweak the message and re-send. Without the
// file restore, images attached to a queued message would silently disappear
// when the user clicks the pencil.
+ // A follow-up queued on the server may already be on its way into the run;
+ // then it is neither edited nor sent again.
+ const withdraw = useCallback(
+ async (msg: QueuedMessage) => {
+ const withdrawn = await withdrawQueuedMessage(contextKey, msg.id).catch((error) => {
+ console.error('[QueueTray] withdrawing a queued message failed:', error);
+ toast.error(t('inputQueue.withdrawFailed'));
+ return undefined;
+ });
+ if (withdrawn === false) toast.info(t('inputQueue.alreadyDelivered'));
+ return !!withdrawn;
+ },
+ [contextKey, t, withdrawQueuedMessage],
+ );
+
const handleEdit = useCallback(
- (msg: QueuedMessage) => {
- removeQueuedMessage(contextKey, msg.id);
- editor?.setDocument('markdown', msg.content);
+ async (msg: QueuedMessage) => {
+ if (!(await withdraw(msg))) return;
+ if (editor) putQueuedMessageInEditor(editor, msg);
editor?.focus();
if (msg.filesPreview?.length) {
const restored = reconstructUploadFilesFromQueue(msg.filesPreview);
dispatchChatUploadFileList({ files: restored, type: 'addFiles' });
}
},
- [contextKey, dispatchChatUploadFileList, editor, removeQueuedMessage],
+ [dispatchChatUploadFileList, editor, withdraw],
);
// "Send now": cancel the currently running agent run for this context, then
@@ -232,43 +246,18 @@ const QueueTray = memo(() => {
const handleSendNow = useCallback(
async (msg: QueuedMessage) => {
await sendNowGate
- .run(async () => {
- const chat = useChatStore.getState();
- // Cancel EVERY running blocker the item could be queued behind, not just the
- // first: matching one op would miss an interim blocker or the second of the
- // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread
- // retry runs (outer wrapper + inner regenerateUserMessage). Leaving any
- // blocker running would make the sendMessage below re-enqueue the item, so
- // "Send now" becomes a no-op. The selector shares the queue-blocking
- // predicate with the enqueue check.
- const runningOpIds =
- operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);
- const cancellationConfirmed = await Promise.all(
- runningOpIds.map((id) => chat.cancelOperation(id, SEND_NOW_CANCEL_REASON)),
- );
- if (cancellationConfirmed.some((confirmed) => !confirmed)) {
- throw new Error('Running agent cancellation was not confirmed');
- }
- removeQueuedMessage(contextKey, msg.id);
-
- // Reconstruct UploadFileItem-shaped objects so the optimistic temp message
- // can rebuild imageList/videoList from the snapshotted preview metadata.
- const filesArray = msg.filesPreview?.length
- ? reconstructUploadFilesFromQueue(msg.filesPreview)
- : msg.files?.length
- ? (msg.files.map((id) => ({ id })) as any)
- : undefined;
- await chat.sendMessage({
+ .run(() =>
+ sendQueuedMessageNow({
+ chat: useChatStore.getState(),
context,
- editorData: msg.editorData,
- files: filesArray,
- message: msg.content,
- metadata: { ...msg.metadata, steer: true },
- });
- })
+ contextKey,
+ msg,
+ withdraw,
+ }),
+ )
.catch((error) => console.error('[QueueTray] sendNow failed:', error));
},
- [context, contextKey, removeQueuedMessage, sendNowGate],
+ [context, contextKey, sendNowGate, withdraw],
);
if (queuedMessages.length === 0) return null;
@@ -351,7 +340,7 @@ const QueueTray = memo(() => {
icon={Trash2}
size="small"
title={t('inputQueue.delete')}
- onClick={() => removeQueuedMessage(contextKey, msg.id)}
+ onClick={() => withdraw(msg)}
/>
</Flexbox>
);
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index f37d481212e..b4ef00c75ed 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -45,6 +45,7 @@ import QueueTray from './QueueTray';
import { sendVoiceMessage } from './sendVoiceMessage';
import { transcribeVoiceMessage } from './transcribeVoiceMessage';
import { useConversationChatInputUiState } from './useConversationChatInputUiState';
+import { useRestoreServerQueue } from './useRestoreServerQueue';
import {
getContextWindowMessages,
getConversationSendButtonProps,
@@ -205,6 +206,7 @@ const ChatInput = memo<ChatInputProps>(
const dbMessages = useConversationStore(dataSelectors.dbMessages);
const context = useConversationStore((s) => s.context);
const contextKey = useMemo(() => messageMapKey(context), [context]);
+ useRestoreServerQueue(context, !disableQueue);
const canRecordVoiceMessage = useCanSendVoiceMessage(context);
// The composer's controls must resolve their topic from THIS conversation,
// not the global `activeTopicId`: a page copilot embedded next to another
diff --git a/src/features/Conversation/ChatInput/useRestoreServerQueue.test.ts b/src/features/Conversation/ChatInput/useRestoreServerQueue.test.ts
new file mode 100644
index 00000000000..fd477d9d3c3
--- /dev/null
+++ b/src/features/Conversation/ChatInput/useRestoreServerQueue.test.ts
@@ -0,0 +1,46 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useRestoreServerQueue } from './useRestoreServerQueue';
+
+const { restoreServerQueuedMessages } = vi.hoisted(() => ({
+ restoreServerQueuedMessages: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue', () => ({
+ restoreServerQueuedMessages,
+}));
+
+describe('useRestoreServerQueue', () => {
+ beforeEach(() => restoreServerQueuedMessages.mockClear());
+
+ // ROOT CAUSE:
+ //
+ // Reconnecting to a running operation was the only path that read the
+ // server queue back. Follow-ups that went back to the queue after their
+ // next turn failed to start sat behind an idle topic, which never showed
+ // them when reopened.
+ //
+ // Before: only a reconnect restored them.
+ // After: opening the conversation does too.
+ it('reads the server queue back when a conversation opens, once per conversation', () => {
+ const context = { agentId: 'agt-1', topicId: 'tpc-1' };
+ const { rerender } = renderHook(({ ctx }) => useRestoreServerQueue(ctx, true), {
+ initialProps: { ctx: context },
+ });
+ rerender({ ctx: { ...context } });
+ expect(restoreServerQueuedMessages).toHaveBeenCalledTimes(1);
+ expect(restoreServerQueuedMessages).toHaveBeenCalledWith(expect.any(Function), context);
+
+ rerender({ ctx: { ...context, topicId: 'tpc-2' } });
+ expect(restoreServerQueuedMessages).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips threads, new conversations and surfaces without a queue', () => {
+ renderHook(() =>
+ useRestoreServerQueue({ agentId: 'agt-1', threadId: 'thd-1', topicId: 'tpc-1' }, true),
+ );
+ renderHook(() => useRestoreServerQueue({ agentId: 'agt-1', topicId: null }, true));
+ renderHook(() => useRestoreServerQueue({ agentId: 'agt-1', topicId: 'tpc-1' }, false));
+ expect(restoreServerQueuedMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatInput/useRestoreServerQueue.ts b/src/features/Conversation/ChatInput/useRestoreServerQueue.ts
new file mode 100644
index 00000000000..9095c79d4b1
--- /dev/null
+++ b/src/features/Conversation/ChatInput/useRestoreServerQueue.ts
@@ -0,0 +1,22 @@
+import type { ConversationContext } from '@lobechat/types';
+import { useEffect, useRef } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { restoreServerQueuedMessages } from '@/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue';
+
+/**
+ * Show the follow-ups still queued on the server for this conversation when it
+ * opens — also when nothing runs, e.g. after a queued next turn failed to
+ * start and they went back to the queue. A running conversation reloads them
+ * on reconnect as well; both add each follow-up once.
+ */
+export const useRestoreServerQueue = (context: ConversationContext, enabled: boolean) => {
+ const { agentId, threadId, topicId } = context;
+ // Read once per conversation: the object's identity changes on unrelated updates.
+ const contextRef = useRef(context);
+ contextRef.current = context;
+ useEffect(() => {
+ if (!enabled || !agentId || !topicId || threadId) return;
+ void restoreServerQueuedMessages(useChatStore.getState, contextRef.current);
+ }, [enabled, agentId, threadId, topicId]);
+};
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index c5d1c0c2f76..ee721513718 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -1,11 +1,15 @@
import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
import {
createQueueSendNowGate,
getContextWindowMessages,
getConversationChatInputUiState,
getConversationSendButtonProps,
+ putQueuedMessageInEditor,
+ sendQueuedMessageNow,
toChatInputMessages,
toDisplayableSendErrorMessage,
} from './utils';
@@ -274,3 +278,142 @@ describe('toDisplayableSendErrorMessage', () => {
expect(toDisplayableSendErrorMessage()).toBeUndefined();
});
});
+
+describe('sendQueuedMessageNow', () => {
+ const context = { agentId: 'agt-1', topicId: 'tpc-1' };
+ const msg = {
+ content: 'now',
+ createdAt: 1,
+ id: 'q1',
+ interruptMode: 'soft' as const,
+ serverDelivery: 'server' as const,
+ };
+ const chatWith = (cancelled: boolean | Error) => {
+ const order: string[] = [];
+ const chat = {
+ cancelOperation: vi.fn(async () => {
+ order.push('cancel');
+ if (cancelled instanceof Error) throw cancelled;
+ return cancelled;
+ }),
+ restoreQueuedMessage: vi.fn(),
+ operations: {
+ 'op-1': {
+ context,
+ id: 'op-1',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ },
+ operationsByContext: { [messageMapKey(context)]: ['op-1'] },
+ queuedMessages: {
+ [messageMapKey(context)]: [
+ { content: 'before', createdAt: 0, id: 'q0', interruptMode: 'soft' },
+ msg,
+ { content: 'after', createdAt: 2, id: 'q2', interruptMode: 'soft' },
+ ],
+ },
+ sendMessage: vi.fn(async () => {
+ order.push('send');
+ }),
+ } as any;
+ return { chat, order };
+ };
+
+ // ROOT CAUSE:
+ //
+ // Send now interrupted the run before withdrawing the item. When that run
+ // had already taken it from the server, the withdrawal then failed and no
+ // replacement send happened, leaving the follow-up unanswered.
+ //
+ // Before: cancel, then withdraw.
+ // After: withdraw first; an item already on its way stops nothing.
+ it('withdraws the item before interrupting the run, then sends it', async () => {
+ const { chat, order } = chatWith(true);
+ const withdraw = vi.fn(async () => {
+ order.push('withdraw');
+ return true;
+ });
+
+ await sendQueuedMessageNow({
+ chat,
+ context,
+ contextKey: messageMapKey(context),
+ msg,
+ withdraw,
+ });
+
+ expect(order).toEqual(['withdraw', 'cancel', 'send']);
+ expect(chat.sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'now', metadata: { steer: true } }),
+ );
+ });
+
+ it('stops nothing and sends nothing when the run already took it', async () => {
+ const { chat } = chatWith(true);
+
+ await sendQueuedMessageNow({
+ chat,
+ context,
+ contextKey: messageMapKey(context),
+ msg,
+ withdraw: async () => false,
+ });
+
+ expect(chat.cancelOperation).not.toHaveBeenCalled();
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['unconfirmed', false],
+ ['failed', new Error('device unreachable')],
+ ])('puts the item back, held here, when the interrupt is %s', async (_label, cancelled) => {
+ const { chat } = chatWith(cancelled);
+
+ await expect(
+ sendQueuedMessageNow({
+ chat,
+ context,
+ contextKey: messageMapKey(context),
+ msg,
+ withdraw: async () => true,
+ }),
+ ).rejects.toThrow();
+
+ // Back at its own place (index 1), not at the tail, so the order holds.
+ expect(chat.restoreQueuedMessage).toHaveBeenCalledWith(
+ messageMapKey(context),
+ { ...msg, serverDelivery: undefined, serverUnconfirmed: undefined },
+ 1,
+ );
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('putQueuedMessageInEditor', () => {
+ // ROOT CAUSE:
+ //
+ // Edit rebuilt the composer from the message text as markdown, dropping the
+ // selected skills, tools and @-mentions the send reads from the structured
+ // document — so an edited follow-up silently lost them.
+ //
+ // Before: always markdown.
+ // After: the structured document when there is one.
+ it('restores the structured document, so selections survive an edit', () => {
+ const editor = { setDocument: vi.fn() };
+ const editorData = { root: { type: 'root' } };
+
+ putQueuedMessageInEditor(editor, { content: 'text', editorData });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('json', editorData);
+ });
+
+ it('falls back to markdown for a message without one', () => {
+ const editor = { setDocument: vi.fn() };
+
+ putQueuedMessageInEditor(editor, { content: 'text' });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'text');
+ });
+});
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index d74bbe7006c..5adc16d7195 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -1,8 +1,15 @@
-import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';
+import type { ConversationContext, OpenAIChatMessage, UIChatMessage } from '@lobechat/types';
import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';
import type { SendButtonProps } from '@/features/ChatInput/store/initialState';
import { chatHelpers } from '@/store/chat/helpers';
+import { operationSelectors } from '@/store/chat/selectors';
+import {
+ type QueuedMessage,
+ reconstructUploadFilesFromQueue,
+ SEND_NOW_CANCEL_REASON,
+} from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
type SupportedChatInputRole = Extract<OpenAIChatMessage['role'], 'assistant' | 'tool' | 'user'>;
@@ -145,3 +152,83 @@ export const toDisplayableSendErrorMessage = (message?: string): string | undefi
return trimmed;
};
+
+/**
+ * "Send now" for one queued message: take it out of the queue, stop every run
+ * it waits behind, then send it as a steered turn.
+ *
+ * Withdrawn first: interrupting a run that already took it from the server
+ * would leave that copy unanswered. `withdraw` resolving `false` means it is
+ * already on its way, so nothing is stopped or sent. Should the interrupt
+ * fail, it goes back to the tray, held by this client only.
+ */
+export const sendQueuedMessageNow = async ({
+ chat,
+ context,
+ contextKey,
+ msg,
+ withdraw,
+}: {
+ chat: ChatStore;
+ context: ConversationContext;
+ contextKey: string;
+ msg: QueuedMessage;
+ withdraw: (msg: QueuedMessage) => Promise<boolean>;
+}): Promise<void> => {
+ const index = chat.queuedMessages[contextKey]?.findIndex((queued) => queued.id === msg.id) ?? -1;
+ if (!(await withdraw(msg))) return;
+ // Back where it was, so the order the user queued in holds.
+ const putBack = () =>
+ chat.restoreQueuedMessage(
+ contextKey,
+ { ...msg, serverDelivery: undefined, serverUnconfirmed: undefined },
+ index < 0 ? Number.MAX_SAFE_INTEGER : index,
+ );
+
+ // Cancel EVERY running blocker the item could be queued behind, not just the
+ // first: matching one op would miss an interim blocker or the second of the
+ // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread retry
+ // runs (outer wrapper + inner regenerateUserMessage). Leaving any blocker
+ // running would make the sendMessage below re-enqueue the item, so "Send now"
+ // becomes a no-op. The selector shares the queue-blocking predicate with the
+ // enqueue check.
+ const runningOpIds = operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);
+ const cancellationConfirmed = await Promise.all(
+ runningOpIds.map((id) => chat.cancelOperation(id, SEND_NOW_CANCEL_REASON)),
+ ).catch((error: unknown) => {
+ putBack();
+ throw error;
+ });
+ if (cancellationConfirmed.some((confirmed) => !confirmed)) {
+ putBack();
+ throw new Error('Running agent cancellation was not confirmed');
+ }
+
+ // Reconstruct UploadFileItem-shaped objects so the optimistic temp message
+ // can rebuild imageList/videoList from the snapshotted preview metadata.
+ const files = msg.filesPreview?.length
+ ? reconstructUploadFilesFromQueue(msg.filesPreview)
+ : msg.files?.length
+ ? (msg.files.map((id) => ({ id })) as any)
+ : undefined;
+ await chat.sendMessage({
+ context,
+ editorData: msg.editorData,
+ files,
+ message: msg.content,
+ metadata: { ...msg.metadata, steer: true },
+ });
+};
+
+/**
+ * Put a queued message back into the composer for editing. The structured
+ * document keeps its selected skills, tools and @-mentions, which the send
+ * reads back from it; markdown only when there is none.
+ */
+export const putQueuedMessageInEditor = (
+ editor: { setDocument: (type: string, content: any) => void },
+ msg: Pick<QueuedMessage, 'content' | 'editorData'>,
+) => {
+ if (msg.editorData) editor.setDocument('json', msg.editorData);
+ else editor.setDocument('markdown', msg.content);
+};
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index c2d40a86b75..4ac81547cbb 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -194,6 +194,29 @@ export interface ExecAgentTaskParams {
userInterventionConfig?: UserInterventionConfig;
}
+/**
+ * A composer send queued behind the running turn on the server: the
+ * fresh-send part of {@link ExecAgentTaskParams}.
+ */
+export type QueuedFollowUpRequest = Omit<
+ ExecAgentTaskParams,
+ | 'autoStart'
+ | 'clientIds'
+ | 'clientOperations'
+ | 'existingMessageIds'
+ | 'parentMessageId'
+ | 'replacesOperationId'
+ | 'resumeApproval'
+ | 'resumeApprovals'
+ | 'resumeToolResult'
+ | 'steer'
+>;
+
+export interface QueuedFollowUpSurface {
+ threadId?: string | null;
+ topicId: string;
+}
+
/**
* Parameters for execSubAgentTask
* Supports both Group mode (with groupId) and Single Agent mode (without groupId)
@@ -314,6 +337,43 @@ class AiAgentService {
);
}
+ /**
+ * Queue a follow-up behind the surface's running turn on the server. It
+ * carries the same run declarations as {@link execAgentTask}, so the run can
+ * tell whether the follow-up can join it. `queued: false` means nothing was
+ * stored and this client must send it itself.
+ */
+ async appendQueuedFollowUp(params: {
+ /** Composer state to keep with it, so a reloaded page can show and resend it as typed. */
+ composer?: { editorData?: Record<string, any>; filesPreview?: Record<string, any>[] };
+ id: string;
+ request: QueuedFollowUpRequest;
+ }) {
+ const clientProtocol = canUseGatewayProtocolV2() ? CLIENT_PROTOCOL_VERSION : undefined;
+ const llmExecutor = buildLlmExecutorDeclaration();
+
+ return await lambdaClient.agentSteerQueue.append.mutate({
+ ...(params.composer && { composer: params.composer }),
+ id: params.id,
+ request: {
+ clientProtocol,
+ ...(llmExecutor && { llmExecutor }),
+ ...params.request,
+ streamFeatures: STREAM_FEATURES,
+ },
+ });
+ }
+
+ /** This user's follow-ups still waiting on the server, oldest first. */
+ async listQueuedFollowUps(surface: QueuedFollowUpSurface) {
+ return await lambdaClient.agentSteerQueue.list.query(surface);
+ }
+
+ /** `removed: false` means the follow-up already left the queue to be delivered. */
+ async removeQueuedFollowUp(params: QueuedFollowUpSurface & { id: string }) {
+ return await lambdaClient.agentSteerQueue.remove.mutate(params);
+ }
+
/**
* Defer an agent run to a future time. Creates an empty `scheduled` topic that
* the backend cron fires once `runAt` passes; nothing runs now.
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts
new file mode 100644
index 00000000000..35df2afa12c
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.serverSteerQueue.test.ts
@@ -0,0 +1,216 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { aiAgentService } from '@/services/aiAgent';
+import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { messageMapKey } from '../../../../utils/messageMapKey';
+import { createMockAgentConfig, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({
+ executeHeterogeneousAgent: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },
+ },
+}));
+
+const context = { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: TEST_IDS.TOPIC_ID };
+const contextKey = messageMapKey(context);
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ vi.spyOn(aiAgentService, 'setQueuedMessages').mockResolvedValue(undefined as never);
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([]);
+ useUserStore.setState({ workspaceUserPreference: {} });
+
+ act(() => {
+ useChatStore.setState({
+ executeClientAgent: vi.fn(),
+ executeGatewayAgent: vi.fn(),
+ isGatewayModeEnabled: () => true,
+ mainInputEditor: null,
+ operations: {
+ 'op-running': {
+ childOperationIds: [],
+ context,
+ id: 'op-running',
+ metadata: { serverOperationId: 'op-server' },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ } as any,
+ operationsByContext: { [contextKey]: ['op-running'] },
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('sendMessage behind a running Gateway run', () => {
+ it('queues the follow-up on the server, so the run reads it before its next model call', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'x', length: 1, queued: true });
+
+ await act(async () => {
+ await result.current.sendMessage({ context, message: 'also check the tests' });
+ });
+
+ await vi.waitFor(() =>
+ expect(useChatStore.getState().queuedMessages[contextKey]?.[0]?.serverDelivery).toBe(
+ 'server',
+ ),
+ );
+ const [{ id, request }] = append.mock.calls[0];
+ expect(id).toBe(useChatStore.getState().queuedMessages[contextKey][0].id);
+ expect(request).toMatchObject({
+ agentId: TEST_IDS.SESSION_ID,
+ appContext: { topicId: TEST_IDS.TOPIC_ID },
+ prompt: 'also check the tests',
+ });
+ // The server joins it; the run is not told to hand its turn back.
+ expect(aiAgentService.setQueuedMessages).not.toHaveBeenCalled();
+ expect(result.current.executeGatewayAgent).not.toHaveBeenCalled();
+ });
+
+ it('carries the content attached from the conversation or a page with the queued request', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'x', length: 1, queued: true, state: 'queued' } as any);
+ const contextSelections = [{ content: 'snippet', id: 'sel-1', type: 'text' }] as any;
+ const pageSelections = [{ content: 'para', id: 'pg-1', pageId: 'doc-1' }] as any;
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context,
+ contextSelections,
+ message: 'about this',
+ pageSelections,
+ });
+ });
+
+ await vi.waitFor(() => expect(append).toHaveBeenCalled());
+ expect(append.mock.calls[0][0].request).toMatchObject({ contextSelections, pageSelections });
+ });
+
+ it('keeps the follow-up in this client when the agent does not run on the Gateway', async () => {
+ act(() => {
+ useChatStore.setState({ isGatewayModeEnabled: () => false });
+ });
+ const { result } = renderHook(() => useChatStore());
+ const append = vi.spyOn(aiAgentService, 'appendQueuedFollowUp');
+
+ await act(async () => {
+ await result.current.sendMessage({ context, message: 'also check the tests' });
+ });
+
+ expect(append).not.toHaveBeenCalled();
+ const [queued] = useChatStore.getState().queuedMessages[contextKey];
+ expect(queued.content).toBe('also check the tests');
+ expect(queued.serverDelivery).toBeUndefined();
+ expect(aiAgentService.setQueuedMessages).toHaveBeenCalledWith({
+ operationId: 'op-server',
+ pending: true,
+ });
+ });
+
+ // ROOT CAUSE:
+ //
+ // Follow-ups restored behind an idle topic (or left by a failed run) were
+ // only sent after a newer message's turn finished: the newer send started
+ // at once and overtook them.
+ //
+ // Before: only a queue behind a Stop was folded into the new send.
+ // After: any queue nothing drains goes first, together with the new send.
+ it('sends follow-ups still queued here before a newer send, in one turn', async () => {
+ vi.useFakeTimers();
+ const sendQueued = vi.fn().mockResolvedValue(undefined);
+ act(() => {
+ useChatStore.setState({
+ operations: {},
+ operationsByContext: {},
+ queuedMessages: {
+ [contextKey]: [{ content: 'earlier', createdAt: 1, id: 'q0', interruptMode: 'soft' }],
+ },
+ });
+ });
+ const { result } = renderHook(() => useChatStore());
+ const original = result.current.sendMessage;
+
+ await act(async () => {
+ await original({ context, message: 'newer' });
+ });
+ useChatStore.setState({ sendMessage: sendQueued });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10);
+ });
+ vi.useRealTimers();
+
+ expect(sendQueued).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'earlier\n\nnewer', metadata: { steer: true } }),
+ );
+ });
+
+ it('waits behind a follow-up a run is still delivering, instead of overtaking it', async () => {
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'delivering',
+ });
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'x',
+ length: 2,
+ queued: true,
+ });
+ const serverRequest = {
+ agentId: TEST_IDS.SESSION_ID,
+ appContext: { topicId: TEST_IDS.TOPIC_ID },
+ prompt: 'earlier',
+ };
+ act(() => {
+ useChatStore.setState({
+ operations: {},
+ operationsByContext: {},
+ queuedMessages: {
+ [contextKey]: [
+ {
+ content: 'earlier',
+ createdAt: 1,
+ id: 'q0',
+ interruptMode: 'soft',
+ serverDelivery: 'server',
+ serverRequest,
+ },
+ ],
+ },
+ });
+ });
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.sendMessage({ context, message: 'newer' });
+ });
+
+ expect(result.current.executeGatewayAgent).not.toHaveBeenCalled();
+ expect(useChatStore.getState().queuedMessages[contextKey].map((m) => m.content)).toEqual([
+ 'earlier',
+ 'newer',
+ ]);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
new file mode 100644
index 00000000000..ff5dbe9f2e5
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService } from '@/services/aiAgent';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import type { GatewayConnection } from '../transports/gateway/gateway';
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+const reclaimServerQueuedMessages = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('../transports/gateway/serverSteerQueue', () => ({
+ restoreServerQueuedMessages: vi.fn(),
+ reclaimServerQueuedMessages,
+ withdrawQueuedMessage: vi.fn(),
+}));
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ getTopics: vi.fn().mockResolvedValue([]),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ // Defaults to "no detail readable" so the silent-end reconcile stays
+ // fail-safe unless a test opts in by returning a row.
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const moveChatContextSelections = vi.hoisted(() => vi.fn());
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatContextSelections }),
+}));
+
+const mockUserDefaultConfig = vi.hoisted(() => ({
+ disableGatewayMode: undefined as boolean | undefined,
+}));
+const mockToolInterventionConfig = vi.hoisted(() => ({
+ allowList: [] as string[],
+ approvalMode: 'manual' as 'allow-list' | 'auto-run' | 'manual',
+}));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: {
+ getState: vi.fn(() => mockUserState),
+ },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ // Lab flag off: this suite pins the v1 per-operation socket path.
+ labPreferSelectors: { enableGatewayMux: () => false },
+ settingsSelectors: {
+ defaultAgentConfig: () => ({
+ chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
+ }),
+ },
+ toolInterventionSelectors: {
+ allowList: () => mockToolInterventionConfig.allowList,
+ approvalMode: () => mockToolInterventionConfig.approvalMode,
+ },
+ userProfileSelectors: {
+ userId: (state: typeof mockUserState) => state.profile.id,
+ },
+}));
+
+// ─── Local-device activation (本机) test seams ───
+// Controlled per-test; default off so the rest of the suite runs as web (no
+// device resolution, no electron IPC).
+const mockEnv = vi.hoisted(() => ({ isDesktop: false }));
+const mockGateway = vi.hoisted(() => ({ getDeviceInfo: vi.fn() }));
+// Effective runtime mode === 'local' (what isLocalSystemEnabledById returns)
+// and chat mode (what isChatModeById returns).
+const mockRuntime = vi.hoisted(() => ({ isChatMode: false, isLocal: false }));
+const mockAgentStore = vi.hoisted(() => ({
+ state: { activeAgentId: undefined, agentMap: {} } as any,
+}));
+
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof ConstVersion>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockEnv.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },
+}));
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.agencyConfig,
+ getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.chatConfig ?? {},
+ isChatModeById: () => () => mockRuntime.isChatMode,
+ isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
+ },
+}));
+
+function createMockClient(): GatewayConnection['client'] & {
+ emitEvent: (event: string, ...args: any[]) => void;
+} {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emitEvent(event: string, ...args: any[]) {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ },
+ on: vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ }),
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+ delete (globalThis as any).window;
+});
+
+const context = { agentId: 'agent-1', scope: 'main' as const, threadId: null, topicId: 'topic-1' };
+
+/** Start a Gateway run and return its registered cancel hook. */
+const startRun = async (interrupt: { deviceCancellationConfirmed?: boolean }) => {
+ const onOperationCancel = vi.fn();
+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
+ const set = vi.fn((updater: any) => {
+ Object.assign(state, typeof updater === 'function' ? updater(state) : updater);
+ });
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation: vi.fn(),
+ connectToGateway: vi.fn(),
+ internal_dispatchTopic: vi.fn(),
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel,
+ replaceMessages: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'gw-op-local' })),
+ switchTopic: vi.fn(),
+ })) as any;
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => createMockClient());
+ vi.mocked(aiAgentService.interruptTask).mockResolvedValue({
+ ...interrupt,
+ operationId: 'server-op',
+ success: true,
+ });
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({ context, message: 'Hello' });
+ const [, handler] = onOperationCancel.mock.calls[0];
+ return { get, handler: handler as () => Promise<void> };
+};
+
+describe('stopping a Gateway run', () => {
+ // ROOT CAUSE:
+ //
+ // A stopped run starts nothing next, yet the follow-ups this client had
+ // handed to the server queue stayed there: the tray kept them as the
+ // server's, and the next run would have joined them unasked.
+ //
+ // Before: the cancel hook only interrupted the run.
+ // After: once the stop is confirmed, the follow-ups come back to this client.
+ it('takes the follow-ups queued on the server back once the stop is confirmed', async () => {
+ const { get, handler } = await startRun({});
+ await handler();
+
+ expect(reclaimServerQueuedMessages).toHaveBeenCalledWith(get, messageMapKey(context));
+ });
+
+ it('keeps them on the server when the stop is not confirmed', async () => {
+ const { handler } = await startRun({ deviceCancellationConfirmed: false });
+ await expect(handler()).rejects.toThrow();
+
+ expect(reclaimServerQueuedMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index f83c400822c..165624fac6e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -77,17 +77,23 @@ import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch
import { executeDirectMention } from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';
import { resolveNewThreadIntent } from '@/store/chat/slices/agentRun/actions/dispatch/newThreadIntent';
import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';
+import {
+ findOrphanedQueueKey,
+ sendQueuedMessages,
+} from '@/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp';
import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';
+import { buildQueuedFollowUpRequest } from '@/store/chat/slices/agentRun/actions/transports/gateway/execRequest';
+import {
+ canQueueOnServer,
+ findServerHeldQueueKey,
+ handOffQueuedMessage,
+ reclaimServerQueuedMessages,
+} from '@/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue';
import {
getNativeHeteroSessionBindingKey,
resolveHeteroResume,
} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
-import type { QueuedFile } from '@/store/chat/slices/operation/types';
-import {
- isQueueBlockingOperation,
- mergeQueuedMessages,
- reconstructUploadFilesFromQueue,
-} from '@/store/chat/slices/operation/types';
+import { isQueueBlockingOperation, snapshotQueuedFiles } from '@/store/chat/slices/operation/types';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
@@ -758,88 +764,78 @@ export class ConversationLifecycleActionImpl {
!runningQueueBlockingOp &&
!onlyAddUserMessage &&
operationSelectors.isQueueDrainPending(operationContext)(this.#get());
- if (runningQueueBlockingOp || queueDrainPending) {
- // Snapshot file previews so the tray can render thumbnails AND the
- // resumed sendMessage can rebuild audioList/imageList/videoList — by the time
- // we drain, chatUploadFileList has long been cleared.
- const filesPreview: QueuedFile[] = (files ?? []).map((f) => ({
- audioMetadata: f.audioMetadata,
- id: f.id,
- mimeType: f.file?.type ?? '',
- name: f.file?.name ?? f.id,
- url: f.fileUrl || f.base64Url || f.previewUrl || '',
- }));
-
+ /** Queue this send behind what holds `key`; on the server when the run can join it there. */
+ const queueThisSend = (key: string) => {
+ const queuedId = nanoid();
+ const queueOnServer =
+ !onlyAddUserMessage &&
+ canQueueOnServer(this.#get, key, {
+ context: operationContext,
+ isGatewayRun: runtimeType === 'gateway' && !directMentionRoute && !willCreateNewTopic,
+ });
this.#get().enqueueMessage(
- queueTargetKey,
+ key,
{
- id: nanoid(),
+ id: queuedId,
content: message,
editorData: editorData ?? undefined,
files: fileIdList,
- filesPreview: filesPreview.length > 0 ? filesPreview : undefined,
+ filesPreview: snapshotQueuedFiles(files),
...(forceRuntime ? { forceRuntime } : {}),
interruptMode: 'soft',
metadata: userMessageMetadata,
createdAt: Date.now(),
+ ...(queueOnServer && { serverDelivery: 'appending' as const }),
},
runningQueueBlockingOp?.id,
);
+ if (queueOnServer)
+ void handOffQueuedMessage(this.#get, key, operationContext, queuedId, () =>
+ buildQueuedFollowUpRequest(this.#get, {
+ context: operationContext,
+ contextSelections,
+ fileIds: fileIdList,
+ mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
+ message,
+ pageSelections,
+ selectedSkillIds: selectedSkills.map((skill) => skill.identifier),
+ selectedToolIds: selectedTools.map((tool) => tool.identifier),
+ trigger: requestTrigger,
+ }),
+ );
notifyMessageAccepted();
- return;
- }
+ };
+ if (runningQueueBlockingOp || queueDrainPending) return void queueThisSend(queueTargetKey);
- // Stop may already have moved the old operation to `cancelled`, so there is
- // no live blocker left to drain follow-ups that were queued before Stop.
- // Fold the new send into that FIFO and immediately restart the whole batch;
- // otherwise the new message jumps ahead and the older queue drains after it.
- const orphanedQueueKey = queueCandidateKeys.find((key) => {
- if ((this.#get().queuedMessages[key]?.length ?? 0) === 0) return false;
- return (this.#get().operationsByContext[key] || []).some((id) => {
- const operation = this.#get().operations[id];
- return operation?.status === 'cancelled' && operation.metadata.isAborting;
- });
- });
+ // Nothing runs: take server-queued follow-ups back; one still being delivered keeps its place.
+ await Promise.all(queueCandidateKeys.map((key) => reclaimServerQueuedMessages(this.#get, key)));
+ const heldKey = findServerHeldQueueKey(this.#get, queueCandidateKeys);
+ if (heldKey && !onlyAddUserMessage) return void queueThisSend(heldKey);
+
+ const orphanedQueueKey = findOrphanedQueueKey(
+ this.#get,
+ queueCandidateKeys,
+ willCreateNewTopic,
+ );
if (orphanedQueueKey && !onlyAddUserMessage) {
- const filesPreview: QueuedFile[] = (files ?? []).map((file) => ({
- audioMetadata: file.audioMetadata,
- id: file.id,
- mimeType: file.file?.type ?? '',
- name: file.file?.name ?? file.id,
- url: file.fileUrl || file.base64Url || file.previewUrl || '',
- }));
this.#get().enqueueMessage(orphanedQueueKey, {
content: message,
createdAt: Date.now(),
editorData: editorData ?? undefined,
files: fileIdList,
- filesPreview: filesPreview.length > 0 ? filesPreview : undefined,
+ filesPreview: snapshotQueuedFiles(files),
...(forceRuntime ? { forceRuntime } : {}),
id: nanoid(),
interruptMode: 'soft',
metadata: userMessageMetadata,
});
- const merged = mergeQueuedMessages(this.#get().drainQueuedMessages(orphanedQueueKey));
+ const restarted = this.#get().drainQueuedMessages(orphanedQueueKey);
notifyMessageAccepted();
setTimeout(() => {
- this.#get()
- .sendMessage({
- context: operationContext,
- editorData: merged.editorData,
- files:
- merged.filesPreview.length > 0
- ? reconstructUploadFilesFromQueue(merged.filesPreview)
- : merged.files.length > 0
- ? (merged.files.map((id) => ({ id })) as any)
- : undefined,
- ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
- message: merged.content,
- metadata: { ...merged.metadata, steer: true },
- })
- .catch((error: unknown) => {
- console.error('[sendMessage] restarting queued content after Stop failed:', error);
- });
+ sendQueuedMessages(this.#get, operationContext, restarted).catch((error: unknown) => {
+ console.error('[sendMessage] restarting queued content after Stop failed:', error);
+ });
}, 0);
return;
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index 97a0ae186e6..9d7b5022e59 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -69,6 +69,7 @@ const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {
summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
// topicDataMap / messagesMap reads default to empty (no topic, no messages).
topicDataMap: {},
+ updateOperationMetadata: vi.fn(),
updateTopicStatus: vi.fn(async () => {}),
};
return { get: (() => store) as unknown as () => ChatStore, store };
@@ -178,6 +179,10 @@ describe('buildRunLifecycle.completeRun — transport-driven disposition', () =>
// gateway/hetero reach completeRun with the op still `running`, so cancelled
// must move it to terminal here. No markUnread, no failOperation, no signal.
expect(store.completeOperation).toHaveBeenCalledWith(OP);
+ // Settled as `completed`, yet nothing drains its queue: say so.
+ expect(store.updateOperationMetadata).toHaveBeenCalledWith(OP, {
+ endedWithoutCompletion: true,
+ });
expect(store.markTopicUnread).not.toHaveBeenCalled();
expect(store.failOperation).not.toHaveBeenCalled();
expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index 1d847953856..f8c317e000c 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -22,7 +22,7 @@ import { markdownToTxt } from '@/utils/markdownToTxt';
import { messageMapKey } from '../../../../utils/messageMapKey';
import { displayMessageSelectors } from '../../../message/selectors/displayMessage';
import type { OperationStatus } from '../../../operation/types';
-import { AI_RUNTIME_OPERATION_TYPES } from '../../../operation/types';
+import { AI_RUNTIME_OPERATION_TYPES, isClientHeldQueuedMessage } from '../../../operation/types';
import { topicSelectors } from '../../../topic/selectors';
import { scheduleQueuedFollowUp } from './queuedFollowUp';
import type {
@@ -455,7 +455,8 @@ export const buildRunLifecycle = (
if (
disposition === 'success' &&
adapter.runScope !== 'sub_agent' &&
- (get().queuedMessages?.[contextKey]?.length ?? 0) > 0
+ // The server delivers the follow-ups it holds itself.
+ get().queuedMessages?.[contextKey]?.some(isClientHeldQueuedMessage)
) {
completeSuccess();
emitComplete(operationId, runtimeStatus);
@@ -484,7 +485,12 @@ export const buildRunLifecycle = (
// must be moved to terminal here. The client is exempt: its cancel
// path already set the op to `cancelled` out of band, and
// `completeOperation` deliberately preserves a `cancelled` status.
- if (adapter.runtimeType !== 'client') get().completeOperation(operationId);
+ if (adapter.runtimeType !== 'client') {
+ get().completeOperation(operationId);
+ // A stop from elsewhere settles as `completed`; nothing drains the
+ // queue now, so the input must not wait for that hand-off.
+ get().updateOperationMetadata(operationId, { endedWithoutCompletion: true });
+ }
break;
}
// `undefined`: unrecognized terminal status — fall through untouched.
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts
index a2ace09d87f..b4e9474e390 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts
@@ -3,11 +3,55 @@ import type { ConversationContext, UploadFileItem } from '@lobechat/types';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import {
mergeQueuedMessages,
+ type QueuedMessage,
reconstructUploadFilesFromQueue,
} from '@/store/chat/slices/operation/types';
import type { ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+/**
+ * The conversation key whose queue nothing will drain, so a new send must
+ * take it along instead of overtaking it: behind a Stop, or — on an existing
+ * topic — left by a failed run or restored from the server.
+ */
+export const findOrphanedQueueKey = (
+ get: () => ChatStore,
+ keys: string[],
+ willCreateNewTopic: boolean,
+): string | undefined =>
+ keys.find((key) => {
+ if ((get().queuedMessages[key]?.length ?? 0) === 0) return false;
+ if (!willCreateNewTopic) return true;
+ return (get().operationsByContext[key] || []).some((id) => {
+ const operation = get().operations[id];
+ return operation?.status === 'cancelled' && operation.metadata.isAborting;
+ });
+ });
+
+/** Send drained queued messages as one steered turn. */
+export const sendQueuedMessages = (
+ get: () => ChatStore,
+ context: ConversationContext,
+ messages: QueuedMessage[],
+): Promise<unknown> => {
+ const merged = mergeQueuedMessages(messages);
+ const mergedFiles =
+ merged.filesPreview.length > 0
+ ? reconstructUploadFilesFromQueue(merged.filesPreview)
+ : merged.files.length > 0
+ ? (merged.files.map((id) => ({ id })) as UploadFileItem[])
+ : undefined;
+
+ return get().sendMessage({
+ context,
+ editorData: merged.editorData,
+ files: mergedFiles,
+ ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
+ message: merged.content,
+ metadata: { ...merged.metadata, steer: true },
+ });
+};
+
/** Shared by streamed completion and recovery from a server terminal snapshot. */
export const scheduleQueuedFollowUp = (
get: () => ChatStore,
@@ -28,25 +72,8 @@ export const scheduleQueuedFollowUp = (
return;
}
- const merged = mergeQueuedMessages(remainingQueued);
- const mergedFiles =
- merged.filesPreview.length > 0
- ? reconstructUploadFilesFromQueue(merged.filesPreview)
- : merged.files.length > 0
- ? (merged.files.map((id) => ({ id })) as UploadFileItem[])
- : undefined;
-
- get()
- .sendMessage({
- context: execContext,
- editorData: merged.editorData,
- files: mergedFiles,
- ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
- message: merged.content,
- metadata: { ...merged.metadata, steer: true },
- })
- .catch((error: unknown) => {
- console.error('[executeClientAgent] sendMessage for queued content failed:', error);
- });
+ sendQueuedMessages(get, execContext, remainingQueued).catch((error: unknown) => {
+ console.error('[executeClientAgent] sendMessage for queued content failed:', error);
+ });
}, 100);
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
new file mode 100644
index 00000000000..c74cbb9c6a6
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
@@ -0,0 +1,256 @@
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+import type {
+ ChatTopic,
+ ChatTopicMetadata,
+ ContextSelection,
+ ConversationContext,
+ ExecAgentAppContext,
+ PageSelection,
+ RuntimeMentionedAgent,
+} from '@lobechat/types';
+import { resolveAgentAgencyConfig } from '@lobechat/types';
+
+import { isDesktop } from '@/const/version';
+import {
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+} from '@/helpers/agentManagementAccess';
+import {
+ applyTopicDeviceBinding,
+ getTopicBoundDeviceId,
+ resolveExecutionTarget,
+ resolveWorkspaceScoped,
+} from '@/helpers/executionTarget';
+import type { QueuedFollowUpRequest } from '@/services/aiAgent';
+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
+import { getAgentStoreState } from '@/store/agent';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { topicSelectors } from '@/store/chat/selectors';
+import type { ChatStore } from '@/store/chat/store';
+import { getElectronStoreState } from '@/store/electron';
+import { useUserStore } from '@/store/user';
+import { toolInterventionSelectors, userProfileSelectors } from '@/store/user/selectors';
+
+import { resolveNewThreadIntent } from '../../dispatch/newThreadIntent';
+
+/**
+ * When the agent runs against the local machine, resolve this desktop's
+ * own gateway deviceId so it can be passed as the run's routing `deviceId` and
+ * `localDeviceId` capability hint. The server then presets `activeDeviceId`,
+ * injects `lobe-local-system` into the first LLM payload, and advertises direct
+ * image reads only when the routed device still matches this desktop. This
+ * skips the extra `activateDevice` round-trip the model is otherwise forced to
+ * make whenever more than one device is online (with a single device the
+ * server's heuristic already covered it).
+ *
+ * Gated on the effective runtime mode (`isLocalSystemEnabledById`), which
+ * derives from `agencyConfig.executionTarget` — only a `local` target presets
+ * the device. Resolving a device for `sandbox` / `none` / `device` targets
+ * would wrongly route the run to this machine.
+ *
+ * Desktop-only and best-effort: any failure falls back to the server-side
+ * device-resolution heuristics. We don't pre-check online status here — an
+ * offline id simply fails the server's `onlineDevices` guard and stays unrouted.
+ */
+export const resolveDesktopDeviceHints = async (
+ agentId?: string,
+ topic?: ChatTopic,
+): Promise<{ deviceId?: string; localDeviceId?: string }> => {
+ if (!isDesktop || !agentId) return {};
+
+ const agentState = getAgentStoreState();
+ // Chat mode means "no execution environment" — never resolve a device, even
+ // when the target is `local`. The server enforces this too (it auto-activates
+ // a single online device), but skipping the deviceId round-trip here avoids
+ // sending an id the server would only discard.
+ if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return {};
+
+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ const userState = useUserStore.getState();
+ const currentUserId = userProfileSelectors.userId(userState);
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
+ // server (`isResourceAuthorOrAdmin`) — an admin's own override must survive
+ // a `fixed` selection policy just like the author's does. Resolve from the
+ // server first when the picker's hook never primed the cache (cold load /
+ // direct mention); no-op for authors and cached answers.
+ await ensureAgentManagementAccess({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ });
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
+ const usesWorkspaceMemberSelection =
+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
+ // Every workspace caller's override matters — a manager's / private owner's
+ // `local` pick also lives in `agentDeviceOverrides` (the shared row must
+ // never reference a personal device); `resolveAgentAgencyConfig` decides how
+ // it applies per role.
+ const deviceOverride = agent?.workspaceId
+ ? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]
+ : undefined;
+ // A conversation pinned to another machine must not be preset to this one —
+ // the server then routes it by the topic's own binding.
+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
+ {
+ agencyConfig: resolveAgentAgencyConfig(
+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),
+ deviceOverride,
+ {
+ canManage,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ },
+ ),
+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
+ },
+ getTopicBoundDeviceId(topic, agentId),
+ getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ );
+ const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');
+ const executionTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: true,
+ isHetero: !!agencyConfig?.heterogeneousProvider,
+ workspaceScoped,
+ });
+ // Platform hints are capability claims, not routing overrides. Always send
+ // this desktop best-effort and let the server's authoritative execution plan
+ // decide whether the effective target may consume it.
+ if (!isPlatformTask && executionTarget !== 'local') return {};
+
+ try {
+ const info = await gatewayConnectionService.getDeviceInfo();
+ if (!info?.deviceId) return {};
+ return isPlatformTask
+ ? { localDeviceId: info.deviceId }
+ : { deviceId: info.deviceId, localDeviceId: info.deviceId };
+ } catch {
+ return {};
+ }
+};
+
+/** The approval settings this user runs agents with, read at send time. */
+export const resolveUserInterventionConfig = () => ({
+ approvalMode: toolInterventionSelectors.approvalMode(useUserStore.getState()),
+ allowList: toolInterventionSelectors.allowList(useUserStore.getState()),
+});
+
+/**
+ * The `appContext` of a Gateway run request: what the server acts on, read
+ * from the conversation the send came from.
+ */
+export const buildExecAppContext = (
+ get: () => ChatStore,
+ {
+ executionContext,
+ initialTopicMetadata,
+ messageContext = executionContext,
+ projectWorkingDirectoryId,
+ }: {
+ executionContext: ConversationContext;
+ /** Seed metadata for the topic this run creates. */
+ initialTopicMetadata?: Partial<ChatTopicMetadata>;
+ messageContext?: ConversationContext;
+ /** The project directory the topic this run creates is bound to. */
+ projectWorkingDirectoryId?: string;
+ },
+): ExecAgentAppContext => {
+ const newThread = resolveNewThreadIntent(executionContext);
+
+ return {
+ agentDocumentId: executionContext.agentDocumentId,
+ ...(messageContext.agentId !== executionContext.agentId && {
+ conversationAgentId: messageContext.agentId,
+ }),
+ defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,
+ documentId: executionContext.documentId,
+ // When AgentBuilder runs, context.agentId is the builtin builder agent.
+ // The actual editing target is chatStore.activeAgentId (kept in sync by
+ // AgentBuilderProvider). Pass it so the server can route tool calls to
+ // the correct agent rather than the builder itself.
+ ...(executionContext.scope === 'agent_builder' && {
+ editingAgentId: get().activeAgentId ?? undefined,
+ }),
+ // Same shape as `editingAgentId`, for the Group Agent Builder panel on
+ // the group Profile page. The builder conversation is keyed by the
+ // builtin builder agent (no groupId in its ConversationContext, so the
+ // message map key and the group's own chat stay separate), which left
+ // the server runtime with no idea which group it was editing.
+ // The context value wins, and every surface that opens this scope sets
+ // it from its own route/group: it is fixed for the run, so a mid-run
+ // navigation cannot make the server stamp a different group than the
+ // panel is reading from. The `activeGroupId` fallback is a last resort
+ // for a caller that forgot — it is sampled here, AFTER the async
+ // preflight above, so it can already be stale by this point.
+ ...(executionContext.scope === 'group_agent_builder' && {
+ editingGroupId: executionContext.editingGroupId ?? get().activeGroupId,
+ }),
+ groupId: executionContext.groupId,
+ ...(initialTopicMetadata && { initialTopicMetadata }),
+ ...(newThread && { newThread }),
+ // Forward the group orchestration role so the server can stamp it onto
+ // the assistant message metadata. Without this the gateway-created
+ // supervisor turn loses its role on the step_start snapshot / refetch
+ // and renders as a generic assistant.
+ orchestrationRole: executionContext.orchestrationRole,
+ ...(projectWorkingDirectoryId && { projectWorkingDirectoryId }),
+ scope: executionContext.scope,
+ taskId:
+ executionContext.viewedTask?.type === 'detail'
+ ? executionContext.viewedTask.taskId
+ : undefined,
+ threadId: executionContext.threadId,
+ topicId: executionContext.topicId,
+ // Goal-page side conversation: lets the server build the goal
+ // overview injection for gateway-run agents (mirrors the client
+ // streaming executor).
+ viewedGoal: executionContext.viewedGoal,
+ };
+};
+
+/**
+ * The request a composer send queued behind a running Gateway run is started
+ * with, should the server start it: the same fields the send would carry, for
+ * an existing topic.
+ */
+export const buildQueuedFollowUpRequest = async (
+ get: () => ChatStore,
+ params: {
+ context: ConversationContext;
+ /** Content attached from the conversation, a page or code, kept on the user row. */
+ contextSelections?: ContextSelection[];
+ fileIds?: string[];
+ mentionedAgents?: RuntimeMentionedAgent[];
+ message: string;
+ pageSelections?: PageSelection[];
+ selectedSkillIds?: string[];
+ selectedToolIds?: string[];
+ trigger?: string;
+ },
+): Promise<QueuedFollowUpRequest> => {
+ const { context } = params;
+ const desktopDeviceHints = await resolveDesktopDeviceHints(
+ context.agentId,
+ context.topicId ? topicSelectors.getTopicById(context.topicId)(get()) : undefined,
+ );
+
+ return {
+ agentId: context.agentId,
+ appContext: buildExecAppContext(get, { executionContext: context }),
+ ...desktopDeviceHints,
+ contextSelections: params.contextSelections?.length ? params.contextSelections : undefined,
+ fileIds: params.fileIds?.length ? params.fileIds : undefined,
+ mentionedAgents: params.mentionedAgents,
+ pageSelections: params.pageSelections?.length ? params.pageSelections : undefined,
+ prompt: params.message,
+ selectedSkillIds: params.selectedSkillIds,
+ selectedToolIds: params.selectedToolIds,
+ trigger: params.trigger,
+ userInterventionConfig: resolveUserInterventionConfig(),
+ };
+};
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 8bc1e59b2fb..f2035ec1ca0 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -13,7 +13,6 @@ import {
type OperationClientOptions,
type ToolResultPayload,
} from '@lobechat/agent-gateway-client';
-import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
ChatTopic,
ChatTopicMetadata,
@@ -26,19 +25,7 @@ import type {
PageSelection,
RuntimeMentionedAgent,
} from '@lobechat/types';
-import { resolveAgentAgencyConfig } from '@lobechat/types';
-import { isDesktop } from '@/const/version';
-import {
- ensureAgentManagementAccess,
- getRuntimeCanManageAgent,
-} from '@/helpers/agentManagementAccess';
-import {
- applyTopicDeviceBinding,
- getTopicBoundDeviceId,
- resolveExecutionTarget,
- resolveWorkspaceScoped,
-} from '@/helpers/executionTarget';
import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';
import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
import {
@@ -47,13 +34,12 @@ import {
type ResumeApprovalParam,
type ResumeToolResultParam,
} from '@/services/aiAgent';
-import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { getLlmExecutorDeclarationFor, getLlmRelayClientId } from '@/services/llmRelay';
import { messageService } from '@/services/message';
import { shareChatService } from '@/services/shareChat';
import { topicService } from '@/services/topic';
import { getAgentStoreState } from '@/store/agent';
-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import {
consumePendingSandboxSelection,
getPendingSandboxSelection,
@@ -70,22 +56,21 @@ import { isInterventionRunActive } from '@/store/chat/utils/interventionSync';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import type { TopicMapScope } from '@/store/chat/utils/topicMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
-import { getElectronStoreState } from '@/store/electron';
import { getFileStoreState } from '@/store/file/store';
import { getServerConfigStoreState } from '@/store/serverConfig';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
-import {
- settingsSelectors,
- toolInterventionSelectors,
- userProfileSelectors,
-} from '@/store/user/selectors';
+import { settingsSelectors } from '@/store/user/selectors';
import { isTrpcErrorCode } from '@/utils/trpcError';
-import { resolveNewThreadIntent } from '../../dispatch/newThreadIntent';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import { scheduleQueuedFollowUp } from '../../lifecycle/queuedFollowUp';
import type { RunScope } from '../../lifecycle/types';
+import {
+ buildExecAppContext,
+ resolveDesktopDeviceHints,
+ resolveUserInterventionConfig,
+} from './execRequest';
import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
@@ -99,113 +84,13 @@ import {
} from './muxRegistry';
import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';
import { isCompletedRuntimeEnd } from './runtimeEndReason';
+import * as serverSteerQueue from './serverSteerQueue';
const getGatewayServerConfig = () =>
(typeof window !== 'undefined'
? window.global_serverConfigStore?.getState()?.serverConfig
: undefined) ?? getServerConfigStoreState()?.serverConfig;
-/**
- * When the agent runs against the local machine, resolve this desktop's
- * own gateway deviceId so it can be passed as the run's routing `deviceId` and
- * `localDeviceId` capability hint. The server then presets `activeDeviceId`,
- * injects `lobe-local-system` into the first LLM payload, and advertises direct
- * image reads only when the routed device still matches this desktop. This
- * skips the extra `activateDevice` round-trip the model is otherwise forced to
- * make whenever more than one device is online (with a single device the
- * server's heuristic already covered it).
- *
- * Gated on the effective runtime mode (`isLocalSystemEnabledById`), which
- * derives from `agencyConfig.executionTarget` — only a `local` target presets
- * the device. Resolving a device for `sandbox` / `none` / `device` targets
- * would wrongly route the run to this machine.
- *
- * Desktop-only and best-effort: any failure falls back to the server-side
- * device-resolution heuristics. We don't pre-check online status here — an
- * offline id simply fails the server's `onlineDevices` guard and stays unrouted.
- */
-const resolveDesktopDeviceHints = async (
- agentId?: string,
- topic?: ChatTopic,
-): Promise<{ deviceId?: string; localDeviceId?: string }> => {
- if (!isDesktop || !agentId) return {};
-
- const agentState = getAgentStoreState();
- // Chat mode means "no execution environment" — never resolve a device, even
- // when the target is `local`. The server enforces this too (it auto-activates
- // a single online device), but skipping the deviceId round-trip here avoids
- // sending an id the server would only discard.
- if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return {};
-
- const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
- const userState = useUserStore.getState();
- const currentUserId = userProfileSelectors.userId(userState);
- // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
- // server (`isResourceAuthorOrAdmin`) — an admin's own override must survive
- // a `fixed` selection policy just like the author's does. Resolve from the
- // server first when the picker's hook never primed the cache (cold load /
- // direct mention); no-op for authors and cached answers.
- await ensureAgentManagementAccess({
- agentId,
- agentUserId: agent?.userId,
- currentUserId,
- visibility: agent?.visibility,
- workspaceId: agent?.workspaceId,
- });
- const canManage = getRuntimeCanManageAgent({
- agentId,
- agentUserId: agent?.userId,
- currentUserId,
- });
- const usesWorkspaceMemberSelection =
- !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
- // Every workspace caller's override matters — a manager's / private owner's
- // `local` pick also lives in `agentDeviceOverrides` (the shared row must
- // never reference a personal device); `resolveAgentAgencyConfig` decides how
- // it applies per role.
- const deviceOverride = agent?.workspaceId
- ? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]
- : undefined;
- // A conversation pinned to another machine must not be preset to this one —
- // the server then routes it by the topic's own binding.
- const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
- {
- agencyConfig: resolveAgentAgencyConfig(
- agentByIdSelectors.getAgencyConfigById(agentId)(agentState),
- deviceOverride,
- {
- canManage,
- visibility: agent?.visibility,
- workspaceId: agent?.workspaceId,
- },
- ),
- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
- },
- getTopicBoundDeviceId(topic, agentId),
- getElectronStoreState().gatewayDeviceInfo?.deviceId,
- );
- const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');
- const executionTarget = resolveExecutionTarget(agencyConfig, {
- clientExecutionAvailable: true,
- isHetero: !!agencyConfig?.heterogeneousProvider,
- workspaceScoped,
- });
- // Platform hints are capability claims, not routing overrides. Always send
- // this desktop best-effort and let the server's authoritative execution plan
- // decide whether the effective target may consume it.
- if (!isPlatformTask && executionTarget !== 'local') return {};
-
- try {
- const info = await gatewayConnectionService.getDeviceInfo();
- if (!info?.deviceId) return {};
- return isPlatformTask
- ? { localDeviceId: info.deviceId }
- : { deviceId: info.deviceId, localDeviceId: info.deviceId };
- } catch {
- return {};
- }
-};
-
type Setter = StoreSetter<ChatStore>;
// ─── Types ───
@@ -900,6 +785,10 @@ export class GatewayActionImpl {
syncQueuedMessagesFlag(this.#get, contextKey);
};
+ /** Withdraw a queued message (also from the server); `false`: already taken to deliver. */
+ withdrawQueuedMessage = (contextKey: string, messageId: string): Promise<boolean> =>
+ serverSteerQueue.withdrawQueuedMessage(this.#get, contextKey, messageId);
+
/**
* Get the connection status for a specific operation.
*/
@@ -1119,11 +1008,6 @@ export class GatewayActionImpl {
// server materialises it as part of this run. Without forwarding the intent
// the turn persists onto the topic's main spine and the subtopic collapses
// back into the main chat.
- const newThread = resolveNewThreadIntent(executionContext);
- const taskId =
- executionContext.viewedTask?.type === 'detail'
- ? executionContext.viewedTask.taskId
- : undefined;
// If this is a new topic, read any repos the user pre-selected before
// sending the first message. We read without consuming yet — if execAgentTask
@@ -1189,10 +1073,7 @@ export class GatewayActionImpl {
? topicSelectors.getTopicById(executionContext.topicId)(this.#get())
: undefined,
);
- const userInterventionConfig = {
- approvalMode: toolInterventionSelectors.approvalMode(useUserStore.getState()),
- allowList: toolInterventionSelectors.allowList(useUserStore.getState()),
- };
+ const userInterventionConfig = resolveUserInterventionConfig();
if (abortSignal?.aborted) {
throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
@@ -1237,52 +1118,12 @@ export class GatewayActionImpl {
// Fresh sends only — resume flows never pass this, and the server drops
// it defensively on resume-like params anyway.
clientIds,
- appContext: {
- agentDocumentId: executionContext.agentDocumentId,
- ...(messageContext.agentId !== executionContext.agentId && {
- conversationAgentId: messageContext.agentId,
- }),
- defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,
- documentId: executionContext.documentId,
- // When AgentBuilder runs, context.agentId is the builtin builder agent.
- // The actual editing target is chatStore.activeAgentId (kept in sync by
- // AgentBuilderProvider). Pass it so the server can route tool calls to
- // the correct agent rather than the builder itself.
- ...(executionContext.scope === 'agent_builder' && {
- editingAgentId: this.#get().activeAgentId ?? undefined,
- }),
- // Same shape as `editingAgentId`, for the Group Agent Builder panel on
- // the group Profile page. The builder conversation is keyed by the
- // builtin builder agent (no groupId in its ConversationContext, so the
- // message map key and the group's own chat stay separate), which left
- // the server runtime with no idea which group it was editing.
- // The context value wins, and every surface that opens this scope sets
- // it from its own route/group: it is fixed for the run, so a mid-run
- // navigation cannot make the server stamp a different group than the
- // panel is reading from. The `activeGroupId` fallback is a last resort
- // for a caller that forgot — it is sampled here, AFTER the async
- // preflight above, so it can already be stale by this point.
- ...(executionContext.scope === 'group_agent_builder' && {
- editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,
- }),
- groupId: executionContext.groupId,
- ...(initialTopicMetadata && { initialTopicMetadata }),
- ...(newThread && { newThread }),
- // Forward the group orchestration role so the server can stamp it onto
- // the assistant message metadata. Without this the gateway-created
- // supervisor turn loses its role on the step_start snapshot / refetch
- // and renders as a generic assistant.
- orchestrationRole: executionContext.orchestrationRole,
- ...(isCreateNewTopic && projectWorkingDirectoryId && { projectWorkingDirectoryId }),
- scope: executionContext.scope,
- taskId,
- threadId: executionContext.threadId,
- topicId: executionContext.topicId,
- // Goal-page side conversation: lets the server build the goal
- // overview injection for gateway-run agents (mirrors the client
- // streaming executor).
- viewedGoal: executionContext.viewedGoal,
- },
+ appContext: buildExecAppContext(this.#get, {
+ executionContext,
+ initialTopicMetadata,
+ messageContext,
+ projectWorkingDirectoryId: isCreateNewTopic ? projectWorkingDirectoryId : undefined,
+ }),
...desktopDeviceHints,
clientOperations,
contextSelections,
@@ -1647,6 +1488,10 @@ export class GatewayActionImpl {
operationId: result.operationId,
topicId: result.topicId,
});
+ await serverSteerQueue.reclaimServerQueuedMessages(
+ this.#get,
+ messageMapKey(resolvedMessageContext),
+ );
if (result.topicId) {
this.#settleLocalTopicAfterConfirmedStop({
@@ -1958,6 +1803,7 @@ export class GatewayActionImpl {
});
this.#get().associateMessageWithOperation(assistantMessageId, gatewayOpId);
+ void serverSteerQueue.restoreServerQueuedMessages(this.#get, context);
// Forward local-op cancellation to the server-side agent loop via tRPC.
// See note in executeGatewayAgent for details.
@@ -1973,6 +1819,7 @@ export class GatewayActionImpl {
}
await interruptGatewayTaskOrThrow({ operationId });
+ await serverSteerQueue.reclaimServerQueuedMessages(this.#get, messageMapKey(context));
this.#settleLocalTopicAfterConfirmedStop({
agentId: context.agentId,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts
index 3e16df63861..03773e1dfc7 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/queuedMessagesFlag.ts
@@ -1,5 +1,6 @@
import { aiAgentService } from '@/services/aiAgent';
import { shareChatService } from '@/services/shareChat';
+import { isClientHeldQueuedMessage } from '@/store/chat/slices/operation/types';
import type { ChatStore } from '@/store/chat/store';
interface FlagWrite {
@@ -61,7 +62,9 @@ const writeFlag = (
*/
export const syncQueuedMessagesFlag = (get: () => ChatStore, contextKey: string): void => {
const state = get();
- const pending = (state.queuedMessages?.[contextKey]?.length ?? 0) > 0;
+ // Follow-ups the server holds are its own to join or start; only the ones
+ // this client still has to send make the run hand its turn back.
+ const pending = !!state.queuedMessages?.[contextKey]?.some(isClientHeldQueuedMessage);
for (const id of state.operationsByContext?.[contextKey] ?? []) {
const operation = state.operations?.[id];
@@ -97,7 +100,7 @@ export const syncQueuedMessagesFlag = (get: () => ChatStore, contextKey: string)
* needs no request.
*/
export const flagQueuedMessagesOnRunStart = (get: () => ChatStore, contextKey: string): void => {
- if (!get().queuedMessages?.[contextKey]?.length) return;
+ if (!get().queuedMessages?.[contextKey]?.some(isClientHeldQueuedMessage)) return;
syncQueuedMessagesFlag(get, contextKey);
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts
new file mode 100644
index 00000000000..e2cca9d1ddf
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.test.ts
@@ -0,0 +1,755 @@
+import { TRPCClientError } from '@trpc/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService, type QueuedFollowUpRequest } from '@/services/aiAgent';
+import { topicService } from '@/services/topic';
+import type { QueuedMessage } from '@/store/chat/slices/operation/types';
+import { useChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import {
+ canQueueOnServer,
+ handOffQueuedMessage,
+ reclaimServerQueuedMessages,
+ restoreServerQueuedMessages,
+ SERVER_QUEUE_POLL_MS,
+ watchServerQueue,
+ withdrawQueuedMessage,
+} from './serverSteerQueue';
+
+const context = { agentId: 'agt-1', topicId: 'tpc-1' };
+const key = messageMapKey(context);
+const request: QueuedFollowUpRequest = {
+ agentId: 'agt-1',
+ appContext: { topicId: 'tpc-1' },
+ prompt: 'next',
+};
+
+const get = () => useChatStore.getState();
+const queued = (id: string, patch: Partial<QueuedMessage> = {}): QueuedMessage => ({
+ content: id,
+ // Queued just now: an unconfirmed row past a day is dropped, not settled.
+ createdAt: Date.now(),
+ id,
+ interruptMode: 'soft',
+ ...patch,
+});
+const queue = () => get().queuedMessages[key] ?? [];
+/** One entry of `agentSteerQueue.list`. */
+const pending = (id: string, patch: Record<string, unknown> = {}) =>
+ ({ createdAt: 1, delivering: false, fileIds: undefined, id, prompt: id, ...patch }) as any;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ useChatStore.setState(useChatStore.getInitialState());
+ useChatStore.setState({ isGatewayModeEnabled: () => true });
+ vi.spyOn(aiAgentService, 'setQueuedMessages').mockResolvedValue(undefined as never);
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([]);
+});
+
+afterEach(async () => {
+ // An emptied tray ends any watch a test left running.
+ useChatStore.setState(useChatStore.getInitialState());
+ await vi.runOnlyPendingTimersAsync();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+const startRun = () =>
+ get().startOperation({
+ context,
+ metadata: { serverOperationId: 'op-server' },
+ type: 'execServerAgentRuntime',
+ });
+
+describe('canQueueOnServer', () => {
+ it('queues behind a Gateway run on an existing main-topic conversation', () => {
+ expect(canQueueOnServer(get, key, { context, isGatewayRun: true })).toBe(true);
+ });
+
+ it.each([
+ ['the run is not on the Gateway', () => {}, context, false],
+ ['the conversation is a thread', () => {}, { ...context, threadId: 'thd-1' }, true],
+ ['the visitor is on a share', () => {}, { ...context, agentShareId: 'shr-1' }, true],
+ // The server queue is per topic: these share one topic between several
+ // message buckets it cannot tell apart.
+ ['it is a group conversation', () => {}, { ...context, groupId: 'grp-1' }, true],
+ [
+ 'it is one group member’s stream',
+ () => {},
+ { ...context, groupId: 'grp-1', scope: 'group_agent' as const, subAgentId: 'agt-2' },
+ true,
+ ],
+ [
+ 'it is a page document’s conversation',
+ () => {},
+ { ...context, documentId: 'doc-1', scope: 'page' as const },
+ true,
+ ],
+ ])('keeps the send here when %s', (_label, arrange, ctx, isGatewayRun) => {
+ arrange();
+ expect(canQueueOnServer(get, key, { context: ctx, isGatewayRun })).toBe(false);
+ });
+
+ it('keeps it here behind a message only this client holds, so it cannot overtake it', () => {
+ get().enqueueMessage(key, queued('first'));
+ expect(canQueueOnServer(get, key, { context, isGatewayRun: true })).toBe(false);
+ });
+});
+
+describe('handOffQueuedMessage', () => {
+ it('hands the follow-up to the server and leaves the run unflagged, so it joins instead of handing back', async () => {
+ startRun();
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'q1', length: 1, queued: true });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(append).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1', request }));
+ expect(queue()[0]).toMatchObject({ serverDelivery: 'server', serverRequest: request });
+ expect(aiAgentService.setQueuedMessages).not.toHaveBeenCalled();
+ // The server delivers it; the client's own drain takes nothing.
+ expect(get().drainQueuedMessages(key)).toEqual([]);
+ });
+
+ it('keeps the follow-up here and flags the run when no run of ours is live on the server', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ queued: false,
+ reason: 'idle',
+ });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(queue()[0].serverDelivery).toBeUndefined();
+ expect(aiAgentService.setQueuedMessages).toHaveBeenCalledWith({
+ operationId: 'op-server',
+ pending: true,
+ });
+ });
+
+ it('sends a kept follow-up itself when the run ended while it was being queued', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ queued: false,
+ reason: 'idle',
+ });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'q1', metadata: { steer: true } }),
+ );
+ });
+
+ it('retries an append whose outcome is unknown with the same id', async () => {
+ startRun();
+ const unavailable = new TRPCClientError('unknown', {
+ result: { error: { data: { code: 'SERVICE_UNAVAILABLE' } } } as any,
+ });
+ Object.assign(unavailable, { data: { code: 'SERVICE_UNAVAILABLE' } });
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockRejectedValueOnce(unavailable)
+ .mockResolvedValueOnce({ id: 'q1', length: 1, queued: true });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(append).toHaveBeenCalledTimes(2);
+ expect(append.mock.calls[1][0].id).toBe('q1');
+ expect(queue()[0].serverDelivery).toBe('server');
+ });
+
+ // ROOT CAUSE:
+ //
+ // An append that committed but whose answers all failed fell back to this
+ // client, which then sent it after the run while the server delivered its
+ // copy too — the follow-up (and any tool side effects) ran twice.
+ //
+ // Before: an unknown outcome kept it here.
+ // After: it stays the server's until the same id is appended again and the
+ // server says where it is.
+ it('keeps an append with an unknown outcome the server’s and settles it by its id', async () => {
+ const unavailable = Object.assign(new Error('unknown'), {
+ data: { code: 'SERVICE_UNAVAILABLE' },
+ });
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockRejectedValueOnce(unavailable)
+ .mockRejectedValueOnce(unavailable)
+ .mockRejectedValueOnce(unavailable)
+ .mockResolvedValueOnce({ id: 'q1', length: 1, queued: true });
+ startRun();
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(queue()[0]).toMatchObject({ serverDelivery: 'server', serverUnconfirmed: true });
+ expect(get().drainQueuedMessages(key)).toEqual([]);
+
+ // Not listed: append the same id again; the server says it is waiting.
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(append).toHaveBeenCalledTimes(4);
+ expect(append.mock.calls[3][0].id).toBe('q1');
+ expect(queue()[0]).toMatchObject({ serverDelivery: 'server', serverUnconfirmed: undefined });
+ });
+
+ // ROOT CAUSE:
+ //
+ // An unconfirmed follow-up the retry found already delivered was just
+ // dropped: the watch skipped its delivery handling, so the run the server
+ // started was not picked up and what was queued here behind it never sent.
+ //
+ // Before: `taken` on reconcile removed the row only.
+ // After: it completes like any delivered follow-up.
+ it('completes an unconfirmed follow-up the server says it delivered, and sends what waited behind', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 0,
+ queued: true,
+ state: 'taken',
+ } as any);
+ get().enqueueMessage(
+ key,
+ queued('q1', { serverDelivery: 'server', serverRequest: request, serverUnconfirmed: true }),
+ );
+ get().enqueueMessage(key, queued('q2', { createdAt: 2 }));
+ // No next run was started for it in this test.
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(null);
+ watchServerQueue(get, key, context);
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 8);
+
+ expect(queue().map((m) => m.id)).not.toContain('q1');
+ expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ message: 'q2' }));
+ });
+
+ // ROOT CAUSE:
+ //
+ // The server remembers delivered ids for a day. A tab suspended longer
+ // retried its unconfirmed append, got `idle` (the marker had expired) and
+ // sent it again, though it may well have run.
+ //
+ // Before: an unconfirmed row could fall back here at any age.
+ // After: past that window it is dropped, never sent from here.
+ it('drops an unconfirmed follow-up too old to settle by its id, without sending it', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ queued: false, reason: 'idle' } as any);
+ get().enqueueMessage(
+ key,
+ queued('q1', {
+ createdAt: Date.now() - 25 * 60 * 60 * 1000,
+ serverDelivery: 'server',
+ serverRequest: request,
+ serverUnconfirmed: true,
+ }),
+ );
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(null);
+ watchServerQueue(get, key, context);
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 8);
+
+ expect(append).not.toHaveBeenCalled();
+ expect(queue()).toHaveLength(0);
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unconfirmed follow-up the server says is on its way, now confirmed', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 0,
+ queued: true,
+ state: 'delivering',
+ } as any);
+ get().enqueueMessage(
+ key,
+ queued('q1', { serverDelivery: 'server', serverRequest: request, serverUnconfirmed: true }),
+ );
+ watchServerQueue(get, key, context);
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+
+ expect(queue()[0]).toMatchObject({ serverDelivery: 'server', serverUnconfirmed: undefined });
+ });
+
+ it('sends an unconfirmed follow-up here only once the server says it never held it', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ useChatStore.setState({ sendMessage });
+ const unavailable = Object.assign(new Error('unknown'), {
+ data: { code: 'SERVICE_UNAVAILABLE' },
+ });
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockRejectedValueOnce(unavailable)
+ .mockRejectedValueOnce(unavailable)
+ .mockRejectedValueOnce(unavailable)
+ .mockResolvedValueOnce({ queued: false, reason: 'idle' });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ // A client-held follow-up behind no run would be sent within 100ms.
+ await vi.advanceTimersByTimeAsync(300);
+ expect(sendMessage).not.toHaveBeenCalled();
+
+ // The next check appends the id again; the server never held it.
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('withdraws from the server a follow-up removed from the tray while it was being queued', async () => {
+ startRun();
+ let resolveAppend!: (value: { id: string; length: number; queued: true }) => void;
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockReturnValue(
+ new Promise((resolve) => (resolveAppend = resolve)),
+ );
+ const remove = vi
+ .spyOn(aiAgentService, 'removeQueuedFollowUp')
+ .mockResolvedValue({ removed: true, state: 'removed' });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ const handOff = handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.waitFor(() => expect(aiAgentService.appendQueuedFollowUp).toHaveBeenCalled());
+ get().removeQueuedMessage(key, 'q1');
+ resolveAppend({ id: 'q1', length: 1, queued: true });
+ await handOff;
+
+ expect(remove).toHaveBeenCalledWith({ id: 'q1', threadId: null, topicId: 'tpc-1' });
+ });
+});
+
+describe('server queue watch', () => {
+ it('drops each follow-up from the tray once the server took it into the run', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ const list = vi
+ .spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([pending('q1', { createdAt: 1, prompt: 'q1' })])
+ .mockResolvedValue([]);
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(queue()).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(list).toHaveBeenCalledWith({ threadId: null, topicId: 'tpc-1' });
+ expect(queue()).toHaveLength(0);
+ });
+});
+
+describe('server queue watch while a run delivers', () => {
+ // ROOT CAUSE:
+ //
+ // A drained follow-up left the waiting list before its run confirmed it, and
+ // the watch dropped it from the tray then. A failed delivery returns it to
+ // the queue, where it waited unseen until another run or a reload.
+ //
+ // Before: absence from the waiting list counted as delivered.
+ // After: one listed as `delivering` stays until it is gone from both.
+ it('keeps a follow-up the run took but has not confirmed, and one it gave back', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ const list = vi
+ .spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([pending('q1', { delivering: true })])
+ .mockResolvedValueOnce([pending('q1')])
+ .mockResolvedValue([]);
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(queue()).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(queue()).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(list).toHaveBeenCalledTimes(3);
+ expect(queue()).toHaveLength(0);
+ });
+
+ it('keeps every follow-up while the queue cannot be read, rather than taking them as delivered', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockRejectedValue(
+ Object.assign(new Error('Queue unavailable'), { data: { code: 'SERVICE_UNAVAILABLE' } }),
+ );
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 3);
+
+ expect(queue()).toEqual([expect.objectContaining({ id: 'q1', serverDelivery: 'server' })]);
+ });
+
+ it('backs off while the queue cannot be read, and resumes the normal pace once it can', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ const list = vi
+ .spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockRejectedValueOnce(new Error('down'))
+ .mockRejectedValueOnce(new Error('down'))
+ .mockResolvedValue([pending('q1')]);
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS); // 1st read fails
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 2 - 1);
+ expect(list).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1); // 2nd read after 3s, fails
+ expect(list).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 4); // 3rd after 6s, succeeds
+ expect(list).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS); // back to 1.5s
+ expect(list).toHaveBeenCalledTimes(4);
+ });
+
+ it('keeps the row and reports the failure when a withdrawal cannot reach the queue', async () => {
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'server', serverRequest: request }));
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockRejectedValue(
+ Object.assign(new Error('Queue unavailable'), { data: { code: 'SERVICE_UNAVAILABLE' } }),
+ );
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).rejects.toThrow('Queue unavailable');
+ expect(queue()).toEqual([expect.objectContaining({ id: 'q1', serverDelivery: 'server' })]);
+ });
+
+ it('keeps showing one it could not withdraw because a run is delivering it', async () => {
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'server', serverRequest: request }));
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'delivering',
+ });
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).resolves.toBe(false);
+ expect(queue()).toEqual([expect.objectContaining({ id: 'q1', serverDelivery: 'server' })]);
+ });
+
+ it('stores the composer state with the follow-up, so a reload can resend it as typed', async () => {
+ startRun();
+ const editorData = { root: { type: 'root' } };
+ const append = vi
+ .spyOn(aiAgentService, 'appendQueuedFollowUp')
+ .mockResolvedValue({ id: 'q1', length: 1, queued: true });
+ get().enqueueMessage(key, queued('q1', { editorData, serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ expect(append).toHaveBeenCalledWith({
+ composer: { editorData, filesPreview: undefined },
+ id: 'q1',
+ request,
+ });
+ });
+});
+
+describe('server queue watch after the run ended without taking them', () => {
+ // ROOT CAUSE:
+ //
+ // A stopped (or failed) run starts nothing next, but the watch kept polling
+ // the server queue every 1.5s for as long as the page stayed open, and the
+ // follow-ups stayed on the server, waiting to join whatever run came next.
+ //
+ // Before: the follow-ups never came back to this client.
+ // After: with no run here and nothing taken, they come back after a while.
+ it('takes the follow-ups back and stops polling', async () => {
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ const list = vi
+ .spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValue([pending('q1', { createdAt: 1, prompt: 'q1' })]);
+ const remove = vi
+ .spyOn(aiAgentService, 'removeQueuedFollowUp')
+ .mockResolvedValue({ removed: true, state: 'removed' });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 25);
+
+ expect(remove).toHaveBeenCalledWith({ id: 'q1', threadId: null, topicId: 'tpc-1' });
+ expect(queue()).toEqual([expect.objectContaining({ id: 'q1' })]);
+ expect(queue()[0].serverDelivery).toBeUndefined();
+ const polls = list.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 5);
+ expect(list).toHaveBeenCalledTimes(polls);
+ });
+
+ it('takes them back at once when the run was stopped elsewhere', async () => {
+ const { operationId } = startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([
+ pending('q1', { createdAt: 1, prompt: 'q1' }),
+ ]);
+ const remove = vi
+ .spyOn(aiAgentService, 'removeQueuedFollowUp')
+ .mockResolvedValue({ removed: true, state: 'removed' });
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+
+ // agent_runtime_end(interrupted) from a stop in another tab.
+ get().completeOperation(operationId);
+ get().updateOperationMetadata(operationId, { endedWithoutCompletion: true });
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 2);
+
+ expect(remove).toHaveBeenCalledWith({ id: 'q1', threadId: null, topicId: 'tpc-1' });
+ expect(queue()[0].serverDelivery).toBeUndefined();
+ });
+
+ it('keeps watching while the run is still going here', async () => {
+ startRun();
+ vi.spyOn(aiAgentService, 'appendQueuedFollowUp').mockResolvedValue({
+ id: 'q1',
+ length: 1,
+ queued: true,
+ });
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([
+ pending('q1', { createdAt: 1, prompt: 'q1' }),
+ ]);
+ const remove = vi.spyOn(aiAgentService, 'removeQueuedFollowUp');
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'appending' }));
+
+ await handOffQueuedMessage(get, key, context, 'q1', async () => request);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS * 25);
+
+ expect(remove).not.toHaveBeenCalled();
+ expect(queue()[0].serverDelivery).toBe('server');
+ });
+});
+
+describe('restoreServerQueuedMessages', () => {
+ // ROOT CAUSE:
+ //
+ // The tray only lived in this page's memory. After a reload during a run the
+ // follow-ups still waiting on the server were gone from the tray, nothing
+ // followed them, and the run the server started for them never showed up on
+ // the reloaded page until another reload.
+ //
+ // Before: nothing read the server queue back on reconnect.
+ // After: they are back in the tray as the server's, and watched again.
+ it('puts the follow-ups waiting on the server back in the tray and watches them', async () => {
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([pending('q1', { createdAt: 5, prompt: 'later' })])
+ .mockResolvedValue([]);
+ startRun();
+
+ await restoreServerQueuedMessages(get, context);
+
+ expect(queue()).toEqual([
+ expect.objectContaining({ content: 'later', id: 'q1', serverDelivery: 'server' }),
+ ]);
+ // Never told to the run as a client-held message: the server joins it.
+ expect(aiAgentService.setQueuedMessages).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ expect(queue()).toHaveLength(0);
+ });
+
+ it('brings back the composer state and selections it was sent with', async () => {
+ const editorData = { root: { type: 'root' } };
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([
+ pending('q1', {
+ editorData,
+ mentionedAgents: [{ id: 'agt-2', name: 'B' }],
+ selectedSkillIds: ['s1'],
+ selectedToolIds: ['t1'],
+ }),
+ ])
+ .mockResolvedValue([]);
+ startRun();
+
+ await restoreServerQueuedMessages(get, context);
+
+ // A local resend (after a stop, or Send now) re-reads these from `editorData`.
+ expect(queue()[0]).toMatchObject({
+ editorData,
+ serverRequest: {
+ mentionedAgents: [{ id: 'agt-2', name: 'B' }],
+ selectedSkillIds: ['s1'],
+ selectedToolIds: ['t1'],
+ },
+ });
+ });
+
+ it('brings back attachment previews, so the tray shows them and Edit restores them', async () => {
+ const filesPreview = [
+ { id: 'f1', mimeType: 'image/png', name: 'a.png', url: 'https://x/a.png' },
+ ];
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([pending('q1', { fileIds: ['f1'], filesPreview })])
+ .mockResolvedValue([]);
+
+ // Nothing runs: e.g. its next turn failed to start and it went back to wait.
+ await restoreServerQueuedMessages(get, context);
+
+ expect(queue()[0]).toMatchObject({ files: ['f1'], filesPreview, serverDelivery: 'server' });
+ });
+
+ it('retries reading the queue when the conversation opens during an outage', async () => {
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockRejectedValueOnce(new Error('down'))
+ .mockResolvedValueOnce([pending('q1', { prompt: 'later' })])
+ .mockResolvedValue([]);
+
+ const restoring = restoreServerQueuedMessages(get, context);
+ await vi.advanceTimersByTimeAsync(SERVER_QUEUE_POLL_MS);
+ await restoring;
+
+ expect(queue()).toEqual([expect.objectContaining({ content: 'later', id: 'q1' })]);
+ });
+
+ // ROOT CAUSE:
+ //
+ // Restoring was skipped when Gateway mode was off, though entries accepted
+ // while it was on stay up to a day: turning it off (or a rollout change) left
+ // them invisible and impossible to withdraw, still able to run.
+ //
+ // Before: restore required Gateway mode to be on now.
+ // After: it reads the owner's queue regardless.
+ it('restores follow-ups accepted earlier even with Gateway mode now off', async () => {
+ useChatStore.setState({ isGatewayModeEnabled: () => false });
+ vi.spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValueOnce([pending('q1', { prompt: 'earlier' })])
+ .mockResolvedValue([]);
+
+ await restoreServerQueuedMessages(get, context);
+
+ expect(queue()).toEqual([expect.objectContaining({ content: 'earlier', id: 'q1' })]);
+ });
+
+ it('adds nothing twice and stays out of threads', async () => {
+ const list = vi
+ .spyOn(aiAgentService, 'listQueuedFollowUps')
+ .mockResolvedValue([pending('q1', { createdAt: 5, prompt: 'later' })]);
+ get().enqueueMessage(key, queued('q1', { serverDelivery: 'server', serverRequest: request }));
+
+ await restoreServerQueuedMessages(get, context);
+ expect(queue()).toHaveLength(1);
+
+ list.mockClear();
+ await restoreServerQueuedMessages(get, { ...context, threadId: 'thd-1' });
+ await restoreServerQueuedMessages(get, { ...context, documentId: 'doc-1', scope: 'page' });
+ await restoreServerQueuedMessages(get, { ...context, groupId: 'grp-1' });
+ expect(list).not.toHaveBeenCalled();
+ });
+});
+
+describe('withdrawQueuedMessage / reclaimServerQueuedMessages', () => {
+ const holdOnServer = (id: string) =>
+ get().enqueueMessage(key, queued(id, { serverDelivery: 'server', serverRequest: request }));
+
+ it('takes a follow-up back from the server before it is edited or sent now', async () => {
+ holdOnServer('q1');
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: true,
+ state: 'removed',
+ });
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).resolves.toBe(true);
+ expect(queue()).toHaveLength(0);
+ });
+
+ it('reports a follow-up the server already took, so it is not sent twice', async () => {
+ holdOnServer('q1');
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'taken',
+ });
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).resolves.toBe(false);
+ expect(queue()).toHaveLength(0);
+ });
+
+ // ROOT CAUSE:
+ //
+ // Two tabs withdrawing the same confirmed follow-up: one got `removed`, the
+ // other `absent`, and both counted it as theirs — so both could Edit or Send
+ // now and run it twice.
+ //
+ // Before: `absent` meant "withdrawn" for any entry.
+ // After: only `removed` does for a confirmed one; `absent` only for an
+ // append that was never confirmed.
+ it('does not take a confirmed follow-up another tab already withdrew', async () => {
+ holdOnServer('q1');
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'absent',
+ });
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).resolves.toBe(false);
+ expect(queue()).toHaveLength(0);
+ });
+
+ it('takes an unconfirmed follow-up the server never stored', async () => {
+ get().enqueueMessage(
+ key,
+ queued('q1', { serverDelivery: 'server', serverRequest: request, serverUnconfirmed: true }),
+ );
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'absent',
+ });
+
+ await expect(withdrawQueuedMessage(get, key, 'q1')).resolves.toBe(true);
+ });
+
+ it('after a stop, leaves one another tab already took back to that tab', async () => {
+ holdOnServer('q1');
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockResolvedValue({
+ removed: false,
+ state: 'absent',
+ });
+
+ await reclaimServerQueuedMessages(get, key);
+
+ expect(queue()).toHaveLength(0);
+ });
+
+ it('after a stop, keeps here what the server still had and drops what it took', async () => {
+ holdOnServer('waiting');
+ holdOnServer('taken');
+ vi.spyOn(aiAgentService, 'removeQueuedFollowUp').mockImplementation(async ({ id }) =>
+ id === 'waiting' ? { removed: true, state: 'removed' } : { removed: false, state: 'taken' },
+ );
+
+ await reclaimServerQueuedMessages(get, key);
+
+ expect(queue()).toEqual([
+ expect.objectContaining({ id: 'waiting', serverDelivery: undefined }),
+ ]);
+ expect(get().drainQueuedMessages(key)).toHaveLength(1);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts
new file mode 100644
index 00000000000..4ad27595101
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/serverSteerQueue.ts
@@ -0,0 +1,546 @@
+import type { ConversationContext } from '@lobechat/types';
+import debug from 'debug';
+
+import { aiAgentService, type QueuedFollowUpRequest } from '@/services/aiAgent';
+import { topicService } from '@/services/topic';
+import { topicSelectors } from '@/store/chat/selectors';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+import {
+ isClientHeldQueuedMessage,
+ type QueuedFile,
+ type QueuedMessage,
+} from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { isTrpcErrorCode } from '@/utils/trpcError';
+
+import { scheduleQueuedFollowUp } from '../../lifecycle/queuedFollowUp';
+
+const log = debug('lobe-store:server-steer-queue');
+
+/** How often a conversation with follow-ups on the server checks which are still waiting. */
+export const SERVER_QUEUE_POLL_MS = 1500;
+/** Longest wait between checks while the queue cannot be read. */
+const MAX_POLL_BACKOFF_MS = 30_000;
+/** A hidden tab checks this rarely; nothing on screen needs the tray then. */
+const HIDDEN_POLL_MS = 15_000;
+/** Reads of the queue when a conversation opens, should the first ones fail. */
+const RESTORE_ATTEMPTS = 5;
+
+/** Delay before the next check: backs off after failed reads, and while hidden. */
+const nextPollDelay = (failures: number) => {
+ const delay = Math.min(SERVER_QUEUE_POLL_MS * 2 ** failures, MAX_POLL_BACKOFF_MS);
+ const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden';
+ return hidden ? Math.max(delay, HIDDEN_POLL_MS) : delay;
+};
+/** Reads of the topic after the server took the follow-ups, until its next run shows up. */
+const SUCCESSOR_SYNC_ATTEMPTS = 5;
+/** How long to wait for the run that took the follow-ups to end here. */
+const LOCAL_RUN_SETTLE_TIMEOUT_MS = 30 * 60 * 1000;
+/**
+ * Checks with no run here and the follow-ups still waiting on the server. The
+ * run that ended took nothing (it failed or was stopped), so they come back.
+ */
+const ORPHANED_QUEUE_TICKS = 20;
+/**
+ * How long an unconfirmed append may be settled by retrying its id. The server
+ * remembers delivered ids for a day after their drain; past that a retry could
+ * no longer tell "delivered" from "never stored", so it must not be sent here.
+ */
+const UNCONFIRMED_SETTLE_MS = 23 * 60 * 60 * 1000;
+/** An append whose outcome is unknown is retried with the same id. */
+const APPEND_ATTEMPTS = 3;
+
+type Get = () => ChatStore;
+
+/** In-flight hand-offs, chained per conversation so the server keeps the queue order. */
+const handOffChains = new Map<string, Promise<void>>();
+/** In-flight hand-off of each message, so a withdrawal waits for its outcome. */
+const handOffs = new Map<string, Promise<void>>();
+/** In-flight reclaims per conversation: two removes of one id would drop it. */
+const reclaims = new Map<string, Promise<void>>();
+/** Conversations whose follow-ups on the server are being watched. */
+const watchers = new Set<string>();
+
+const queueOf = (get: Get, contextKey: string): QueuedMessage[] =>
+ get().queuedMessages?.[contextKey] ?? [];
+
+const findQueued = (get: Get, contextKey: string, id: string) =>
+ queueOf(get, contextKey).find((message) => message.id === id);
+
+const surfaceOf = (request: QueuedFollowUpRequest) => ({
+ threadId: request.appContext?.threadId ?? null,
+ topicId: request.appContext!.topicId!,
+});
+
+const hasLocalRun = (get: Get, context: ConversationContext) =>
+ operationSelectors.getRunningQueueBlockingOperationIds(context)(get()).length > 0;
+
+/**
+ * Whether the server queue — one per user, topic and thread — is this
+ * conversation's alone: an agent's own main conversation on an existing
+ * topic. Group, group-member, page-document, builder, thread and shared
+ * conversations split one topic into several message buckets the server
+ * cannot tell apart, so they keep the client queue.
+ */
+const ownsTopicQueue = (context: ConversationContext): boolean =>
+ !!context.topicId &&
+ !context.threadId &&
+ !context.groupId &&
+ !context.agentShareId &&
+ !context.topicShareId &&
+ (!context.scope || context.scope === 'main');
+
+/**
+ * Whether a send queued behind this conversation's run can be queued on the
+ * server: a Gateway run on a conversation that owns its topic's server queue
+ * (see {@link ownsTopicQueue}), with nothing queued ahead that only this
+ * client holds (it would be overtaken).
+ */
+export const canQueueOnServer = (
+ get: Get,
+ contextKey: string,
+ params: { context: ConversationContext; isGatewayRun: boolean },
+): boolean => {
+ const { context, isGatewayRun } = params;
+ if (!isGatewayRun || !ownsTopicQueue(context)) return false;
+
+ return !queueOf(get, contextKey).some(isClientHeldQueuedMessage);
+};
+
+/** The conversation key holding a follow-up the server still has (one a run may be delivering). */
+export const findServerHeldQueueKey = (get: Get, keys: string[]): string | undefined =>
+ keys.find((key) => queueOf(get, key).some((message) => !isClientHeldQueuedMessage(message)));
+
+/** The follow-ups only this client holds are sent by it once nothing runs. */
+const sendIfIdle = (get: Get, contextKey: string, context: ConversationContext) => {
+ const queue = queueOf(get, contextKey);
+ if (queue.length === 0 || !queue.every(isClientHeldQueuedMessage)) return;
+ if (hasLocalRun(get, context)) return;
+
+ const operationIds = get().operationsByContext[contextKey] ?? [];
+ scheduleQueuedFollowUp(get, context, operationIds.at(-1) ?? '');
+};
+
+/** The server refused before storing anything; any other failure leaves it unknown. */
+const DEFINITE_REJECTIONS = ['BAD_REQUEST', 'FORBIDDEN', 'NOT_FOUND', 'UNAUTHORIZED'] as const;
+const isDefiniteRejection = (error: unknown) =>
+ DEFINITE_REJECTIONS.some((code) => isTrpcErrorCode(error, code));
+
+const appendWithRetry = async (
+ id: string,
+ request: QueuedFollowUpRequest,
+ message?: QueuedMessage,
+) => {
+ let lastError: unknown;
+ for (let attempt = 0; attempt < APPEND_ATTEMPTS; attempt++) {
+ try {
+ return await aiAgentService.appendQueuedFollowUp({
+ composer: message && {
+ editorData: message.editorData,
+ filesPreview: message.filesPreview as Record<string, any>[] | undefined,
+ },
+ id,
+ request,
+ });
+ } catch (error) {
+ lastError = error;
+ if (!isTrpcErrorCode(error, 'SERVICE_UNAVAILABLE')) break;
+ }
+ }
+ throw lastError;
+};
+
+/**
+ * Hand a queued message to the server queue behind the running Gateway run.
+ * Kept by the server, it joins that run before its next model call or starts
+ * as the next turn, also with this tab closed. Anything else keeps it here,
+ * where it is sent once the run ends, as before.
+ */
+export const handOffQueuedMessage = (
+ get: Get,
+ contextKey: string,
+ context: ConversationContext,
+ id: string,
+ buildRequest?: () => Promise<QueuedFollowUpRequest>,
+): Promise<void> => {
+ const run = async () => {
+ const keepHere = () => {
+ get().updateQueuedMessage(contextKey, id, { serverDelivery: undefined });
+ get().internal_syncQueuedMessagesFlag(contextKey);
+ sendIfIdle(get, contextKey, context);
+ };
+
+ const queue = queueOf(get, contextKey);
+ const index = queue.findIndex((message) => message.id === id);
+ if (index < 0) return;
+ // Something ahead of it stayed here: the server would deliver this one first.
+ if (queue.slice(0, index).some(isClientHeldQueuedMessage)) return keepHere();
+
+ let request = queue[index].serverRequest;
+ if (!request && buildRequest) {
+ try {
+ request = await buildRequest();
+ get().updateQueuedMessage(contextKey, id, { serverRequest: request });
+ } catch (error) {
+ console.error('[serverSteerQueue] building the queued request failed:', error);
+ }
+ }
+ if (!request) return keepHere();
+
+ get().updateQueuedMessage(contextKey, id, { serverDelivery: 'appending' });
+ let queued = false;
+ let unconfirmed = false;
+ try {
+ queued = (await appendWithRetry(id, request, findQueued(get, contextKey, id))).queued;
+ } catch (error) {
+ console.error('[serverSteerQueue] queueing on the server failed:', error);
+ // Unless refused outright it may have been stored, and sending it from
+ // here too could run it twice. It stays the server's until a retry of
+ // the same id says where it is.
+ unconfirmed = !isDefiniteRejection(error);
+ }
+
+ if (!findQueued(get, contextKey, id)) {
+ // Withdrawn while the append was in flight.
+ if (queued || unconfirmed)
+ await aiAgentService.removeQueuedFollowUp({ ...surfaceOf(request), id }).catch(() => {});
+ return;
+ }
+ if (!queued && !unconfirmed) return keepHere();
+
+ log('[%s] %s queued on the server%s', contextKey, id, unconfirmed ? ' (unconfirmed)' : '');
+ get().updateQueuedMessage(contextKey, id, {
+ serverDelivery: 'server',
+ serverUnconfirmed: unconfirmed || undefined,
+ });
+ watchServerQueue(get, contextKey, context);
+ };
+
+ const previous = handOffChains.get(contextKey) ?? Promise.resolve();
+ const handOff = previous.then(run, run);
+ const settled = handOff.finally(() => {
+ handOffs.delete(id);
+ if (handOffChains.get(contextKey) === settled) handOffChains.delete(contextKey);
+ });
+ handOffChains.set(contextKey, settled);
+ handOffs.set(id, settled);
+
+ return settled;
+};
+
+/**
+ * After the server took its follow-ups with no run of ours left locally, it
+ * started them as the next run: publish that run's marker so the conversation
+ * reconnects to it.
+ */
+const syncQueuedSuccessorRun = async (get: Get, context: ConversationContext) => {
+ const { topicId } = context;
+ if (!topicId) return;
+ const knownOperationId =
+ topicSelectors.getTopicById(topicId)(get())?.metadata?.runningOperation?.operationId;
+
+ for (let attempt = 0; attempt < SUCCESSOR_SYNC_ATTEMPTS; attempt++) {
+ if (hasLocalRun(get, context)) return;
+
+ const topic = await topicService.getTopicDetail(topicId).catch(() => undefined);
+ const runningOperation = topic?.metadata?.runningOperation;
+ if (runningOperation && runningOperation.operationId !== knownOperationId) {
+ const current = topicSelectors.getTopicById(topicId)(get());
+ if (!current) return;
+ get().internal_dispatchTopic({
+ id: topicId,
+ type: 'updateTopic',
+ value: { metadata: { ...current.metadata, runningOperation } },
+ });
+ if (get().activeTopicId === topicId) await get().refreshMessages();
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, SERVER_QUEUE_POLL_MS));
+ }
+};
+
+const onServerQueueDelivered = async (
+ get: Get,
+ contextKey: string,
+ context: ConversationContext,
+) => {
+ // Joined into the run, or taken by it as it ended — its end may not have
+ // reached this client yet. Either way, the next run (if any) is known once
+ // this one settles.
+ const settleBy = Date.now() + LOCAL_RUN_SETTLE_TIMEOUT_MS;
+ while (hasLocalRun(get, context) && Date.now() < settleBy)
+ await new Promise((resolve) => setTimeout(resolve, SERVER_QUEUE_POLL_MS));
+ if (!hasLocalRun(get, context)) await syncQueuedSuccessorRun(get, context);
+
+ // Queued here behind the delivered ones: the server can take them now.
+ const left = queueOf(get, contextKey).filter(
+ (message) => isClientHeldQueuedMessage(message) && message.serverRequest,
+ );
+ if (left.length === 0) return sendIfIdle(get, contextKey, context);
+ for (const message of left) void handOffQueuedMessage(get, contextKey, context, message.id);
+};
+
+/**
+ * An append whose answer was lost and that the server does not list: append
+ * the same id again, which never stores it twice, and let the answer say where
+ * it is — waiting, delivered, or never stored (then this client sends it).
+ */
+const reconcileUnconfirmed = async (
+ get: Get,
+ contextKey: string,
+ context: ConversationContext,
+ message: QueuedMessage,
+): Promise<'delivered' | 'held' | 'kept'> => {
+ // Too old to settle safely: drop it rather than risk running it twice.
+ if (Date.now() - message.createdAt > UNCONFIRMED_SETTLE_MS) {
+ console.warn('[serverSteerQueue] dropping %s: unconfirmed for too long to settle', message.id);
+ get().removeQueuedMessage(contextKey, message.id);
+ return 'delivered';
+ }
+ try {
+ const result = await appendWithRetry(message.id, message.serverRequest!, message);
+ // Delivered already: the caller completes it like any delivered one.
+ if (result.queued && result.state === 'taken') return 'delivered';
+ if (result.queued) {
+ // Waiting, or on its way into a run: the server's, now confirmed.
+ get().updateQueuedMessage(contextKey, message.id, { serverUnconfirmed: undefined });
+ return 'held';
+ }
+ } catch (error) {
+ if (!isDefiniteRejection(error)) return 'held';
+ }
+ // Not on the server and refused now: only this client holds it.
+ get().updateQueuedMessage(contextKey, message.id, {
+ serverDelivery: undefined,
+ serverUnconfirmed: undefined,
+ });
+ get().internal_syncQueuedMessagesFlag(contextKey);
+ sendIfIdle(get, contextKey, context);
+ return 'kept';
+};
+
+/**
+ * Follow the conversation's follow-ups on the server until all of them left
+ * its queue — joined into the run or started as the next turn — and drop
+ * each from the tray as it goes.
+ */
+export const watchServerQueue = (get: Get, contextKey: string, context: ConversationContext) => {
+ if (watchers.has(contextKey)) return;
+ watchers.add(contextKey);
+ let ticksWithoutRun = 0;
+ let failures = 0;
+
+ const tick = async () => {
+ const held = queueOf(get, contextKey).filter(
+ (message) => message.serverDelivery === 'server' && message.serverRequest,
+ );
+ if (held.length === 0) {
+ watchers.delete(contextKey);
+ return;
+ }
+
+ try {
+ // Taken by a run but not confirmed (`delivering`) still counts as held:
+ // a failed delivery returns it to the queue.
+ const notDelivered = new Set(
+ (await aiAgentService.listQueuedFollowUps(surfaceOf(held[0].serverRequest!))).map(
+ (entry) => entry.id,
+ ),
+ );
+ const settledDelivered = new Set<string>();
+ for (const message of held) {
+ if (!message.serverUnconfirmed) continue;
+ if (notDelivered.has(message.id))
+ get().updateQueuedMessage(contextKey, message.id, { serverUnconfirmed: undefined });
+ else if ((await reconcileUnconfirmed(get, contextKey, context, message)) === 'delivered')
+ settledDelivered.add(message.id);
+ }
+ // Confirmed ones gone from the server, and unconfirmed ones it says it delivered.
+ const delivered = held.filter((message) =>
+ message.serverUnconfirmed
+ ? settledDelivered.has(message.id)
+ : !notDelivered.has(message.id),
+ );
+ for (const message of delivered) {
+ if (findQueued(get, contextKey, message.id)?.serverDelivery === 'server')
+ get().removeQueuedMessage(contextKey, message.id);
+ }
+ const stillHeld = queueOf(get, contextKey).some(
+ (message) => message.serverDelivery === 'server',
+ );
+ if (delivered.length > 0 && !stillHeld) {
+ watchers.delete(contextKey);
+ await onServerQueueDelivered(get, contextKey, context);
+ return;
+ }
+ failures = 0;
+ } catch (error) {
+ // Unknown, not delivered: keep them, and back off an already failing path.
+ failures += 1;
+ console.error('[serverSteerQueue] reading the server queue failed:', error);
+ }
+
+ ticksWithoutRun = hasLocalRun(get, context) ? 0 : ticksWithoutRun + 1;
+ // Stopped elsewhere: that run starts nothing next, take them back now.
+ const stopped =
+ operationSelectors.getIdleQueueHost(context)(get())?.metadata.endedWithoutCompletion;
+ if (stopped || ticksWithoutRun >= ORPHANED_QUEUE_TICKS) {
+ await reclaimServerQueuedMessages(get, contextKey);
+ // One still on its way stays the server's until it lands or comes back.
+ if (!queueOf(get, contextKey).some((message) => message.serverDelivery === 'server')) {
+ watchers.delete(contextKey);
+ return;
+ }
+ }
+
+ setTimeout(tick, nextPollDelay(failures));
+ };
+
+ setTimeout(tick, nextPollDelay(0));
+};
+
+/** Read the queue, retrying with backoff: a failed read is unknown, not empty. */
+const listWithRetry = async (surface: { threadId: null; topicId: string }) => {
+ for (let attempt = 0; attempt < RESTORE_ATTEMPTS; attempt++) {
+ try {
+ return await aiAgentService.listQueuedFollowUps(surface);
+ } catch (error) {
+ console.error('[serverSteerQueue] reading the server queue failed:', error);
+ if (attempt < RESTORE_ATTEMPTS - 1)
+ await new Promise((resolve) => setTimeout(resolve, nextPollDelay(attempt)));
+ }
+ }
+ return [];
+};
+
+/**
+ * Put the follow-ups still waiting on the server back in the tray of a
+ * conversation this page reconnects to (after a reload, or opened elsewhere),
+ * and follow them again, so they show as queued and the run that takes them is
+ * picked up here.
+ */
+export const restoreServerQueuedMessages = async (
+ get: Get,
+ context: ConversationContext,
+): Promise<void> => {
+ const { agentId, topicId } = context;
+ // Not gated on Gateway mode being on now: entries accepted while it was stay
+ // up to a day and must remain visible and withdrawable after it is turned off.
+ if (!agentId || !topicId || !ownsTopicQueue(context)) return;
+
+ const surface = { threadId: null, topicId };
+ const pending = await listWithRetry(surface);
+ if (pending.length === 0) return;
+
+ const contextKey = messageMapKey(context);
+ const known = new Set(queueOf(get, contextKey).map((message) => message.id));
+ for (const entry of pending) {
+ if (known.has(entry.id)) continue;
+ get().enqueueMessage(contextKey, {
+ content: entry.prompt,
+ createdAt: entry.createdAt,
+ // The composer state it was sent from, so a local resend keeps its
+ // selected skills, tools and mentions.
+ ...(entry.editorData && { editorData: entry.editorData }),
+ // Previews let the tray show its attachments and Edit put them back.
+ ...(entry.filesPreview?.length && {
+ filesPreview: entry.filesPreview as unknown as QueuedFile[],
+ }),
+ ...(entry.fileIds?.length && { files: entry.fileIds }),
+ id: entry.id,
+ interruptMode: 'soft',
+ serverDelivery: 'server',
+ serverRequest: {
+ agentId,
+ appContext: { threadId: null, topicId },
+ fileIds: entry.fileIds ?? undefined,
+ mentionedAgents: entry.mentionedAgents ?? undefined,
+ prompt: entry.prompt,
+ selectedSkillIds: entry.selectedSkillIds ?? undefined,
+ selectedToolIds: entry.selectedToolIds ?? undefined,
+ },
+ });
+ }
+ log('[%s] restored %d follow-ups from the server', contextKey, pending.length);
+ watchServerQueue(get, contextKey, context);
+};
+
+/**
+ * Whether a withdrawal made this caller the only holder of the follow-up.
+ * Only `removed` proves that for a confirmed entry: `absent` then means
+ * another tab withdrew it first, and both sending it would run it twice. For
+ * an unconfirmed append, `absent` means it was never stored.
+ */
+const ownsWithdrawn = (message: QueuedMessage, state: string) =>
+ state === 'removed' || (state === 'absent' && !!message.serverUnconfirmed);
+
+/**
+ * Take the follow-ups back from the server queue, so only this client holds
+ * them again — for a stopped run, which starts nothing next. The ones the
+ * server already took are gone from the tray.
+ */
+export const reclaimServerQueuedMessages = (get: Get, contextKey: string): Promise<void> => {
+ const inFlight = reclaims.get(contextKey);
+ if (inFlight) return inFlight;
+
+ const reclaim = (async () => {
+ await handOffChains.get(contextKey);
+
+ for (const message of queueOf(get, contextKey)) {
+ if (message.serverDelivery !== 'server' || !message.serverRequest) continue;
+ try {
+ const { state } = await aiAgentService.removeQueuedFollowUp({
+ ...surfaceOf(message.serverRequest),
+ id: message.id,
+ });
+ // Removed by this call, or an unconfirmed append never stored: only
+ // this client holds it now.
+ if (ownsWithdrawn(message, state))
+ get().updateQueuedMessage(contextKey, message.id, {
+ serverDelivery: undefined,
+ serverUnconfirmed: undefined,
+ });
+ // Delivered, or taken back by another tab. One still `delivering` stays
+ // the server's until it lands or comes back.
+ else if (state !== 'delivering') get().removeQueuedMessage(contextKey, message.id);
+ } catch (error) {
+ // Still on the server, which delivers it on the conversation's next run.
+ console.error('[serverSteerQueue] taking a follow-up back failed:', error);
+ }
+ }
+ })().finally(() => reclaims.delete(contextKey));
+ reclaims.set(contextKey, reclaim);
+
+ return reclaim;
+};
+
+/**
+ * Withdraw one queued message from the tray, and from the server when it is
+ * there. `false` means the server already took it to deliver, so it must not
+ * be sent or edited again.
+ */
+export const withdrawQueuedMessage = async (
+ get: Get,
+ contextKey: string,
+ id: string,
+): Promise<boolean> => {
+ await handOffs.get(id);
+ const message = findQueued(get, contextKey, id);
+ if (!message) return false;
+
+ if (message.serverDelivery === 'server' && message.serverRequest) {
+ const { state } = await aiAgentService.removeQueuedFollowUp({
+ ...surfaceOf(message.serverRequest),
+ id,
+ });
+ // Taken but not settled: it stays shown until it lands or comes back.
+ if (state === 'delivering') return false;
+ get().removeQueuedMessage(contextKey, id);
+ return ownsWithdrawn(message, state);
+ }
+
+ get().removeQueuedMessage(contextKey, id);
+ return true;
+};
diff --git a/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts b/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts
new file mode 100644
index 00000000000..578a002cc7e
--- /dev/null
+++ b/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts
@@ -0,0 +1,91 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { operationSelectors } from '../selectors';
+
+const context = { agentId: 'agent1', topicId: 'topic1' };
+
+const queueBehind = (result: { current: ReturnType<typeof useChatStore.getState> }) =>
+ result.current.enqueueMessage(messageMapKey(context), {
+ content: 'follow up',
+ createdAt: 2000,
+ id: 'q1',
+ interruptMode: 'soft',
+ });
+
+describe('queue hand-off after a run stopped elsewhere', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ // ROOT CAUSE:
+ //
+ // A Gateway run stopped from another tab, device or the API ends with
+ // `agent_runtime_end(interrupted)`; the lifecycle settles it as `completed`,
+ // the same as a clean finish. With a follow-up queued, the selectors read
+ // that as the hand-off to the next turn, which never comes, so the input
+ // kept loading ("running") for as long as the page stayed open.
+ //
+ // Before: a completed host always counted as handing its queue off.
+ // After: one that ended without completing does not.
+ it('does not keep the input loading behind a run that ended without completing', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ const { operationId } = result.current.startOperation({
+ context,
+ metadata: { startTime: 1000 },
+ type: 'execServerAgentRuntime',
+ });
+ queueBehind(result);
+ result.current.completeOperation(operationId);
+ result.current.updateOperationMetadata(operationId, { endedWithoutCompletion: true });
+ });
+
+ expect(operationSelectors.isSteerHandoffPending(context)(result.current)).toBe(false);
+ expect(operationSelectors.isQueueDrainPending(context)(result.current)).toBe(false);
+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(false);
+ });
+
+ it('still hands the queue off behind a run that completed', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ const { operationId } = result.current.startOperation({
+ context,
+ metadata: { startTime: 1000 },
+ type: 'execServerAgentRuntime',
+ });
+ queueBehind(result);
+ result.current.completeOperation(operationId);
+ });
+
+ expect(operationSelectors.isSteerHandoffPending(context)(result.current)).toBe(true);
+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(true);
+ });
+});
+
+describe('restoreQueuedMessage', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ it('puts a message back at its place in the queue', () => {
+ const key = messageMapKey(context);
+ const item = (id: string) => ({
+ content: id,
+ createdAt: 1,
+ id,
+ interruptMode: 'soft' as const,
+ });
+ useChatStore.getState().enqueueMessage(key, item('a'));
+ useChatStore.getState().enqueueMessage(key, item('c'));
+
+ useChatStore.getState().restoreQueuedMessage(key, item('b'), 1);
+
+ expect(useChatStore.getState().queuedMessages[key].map((m) => m.id)).toEqual(['a', 'b', 'c']);
+ });
+});
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index d62bfbb9c3e..8c5cf662401 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -14,6 +14,7 @@ import { operationSelectors } from './selectors';
import {
type AfterCompletionCallback,
AI_RUNTIME_OPERATION_TYPES,
+ isClientHeldQueuedMessage,
type Operation,
type OperationCancelContext,
type OperationContext,
@@ -864,7 +865,9 @@ export class OperationActionsImpl {
// 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);
+ // One handed to the server queue is the server's to join or start.
+ if (message.interruptMode === 'soft' && isClientHeldQueuedMessage(message))
+ this.#get().internal_syncQueuedMessagesFlag(contextKey);
// Hard interrupt: cancel the running operation
if (message.interruptMode === 'hard' && runningOperationId) {
@@ -878,10 +881,14 @@ export class OperationActionsImpl {
/**
* Drain all queued messages for a context (atomic take-all).
+ *
+ * Takes nothing while the server holds any of them: it delivers those
+ * itself, and the ones queued after them must not overtake them.
*/
drainQueuedMessages = (contextKey: string): QueuedMessage[] => {
const queue = this.#get().queuedMessages[contextKey];
if (!queue || queue.length === 0) return [];
+ if (!queue.every(isClientHeldQueuedMessage)) return [];
const messages = [...queue];
@@ -924,6 +931,35 @@ export class OperationActionsImpl {
);
};
+ /** Put a queued message back where it was (e.g. after a failed Send now), keeping the order. */
+ restoreQueuedMessage = (contextKey: string, message: QueuedMessage, index: number): void => {
+ this.#set(
+ produce((state: ChatStore) => {
+ const queue = state.queuedMessages[contextKey] ?? [];
+ queue.splice(Math.max(0, Math.min(index, queue.length)), 0, message);
+ state.queuedMessages[contextKey] = queue;
+ }),
+ false,
+ n(`restoreQueuedMessage/${contextKey}/${message.id}`),
+ );
+ if (isClientHeldQueuedMessage(message)) this.#get().internal_syncQueuedMessagesFlag(contextKey);
+ };
+
+ updateQueuedMessage = (
+ contextKey: string,
+ messageId: string,
+ patch: Partial<Pick<QueuedMessage, 'serverDelivery' | 'serverRequest' | 'serverUnconfirmed'>>,
+ ): void => {
+ this.#set(
+ produce((state: ChatStore) => {
+ const message = state.queuedMessages[contextKey]?.find((m) => m.id === messageId);
+ if (message) Object.assign(message, patch);
+ }),
+ false,
+ n(`updateQueuedMessage/${contextKey}/${messageId}`),
+ );
+ };
+
removeQueuedMessage = (contextKey: string, messageId: string): void => {
this.#set(
produce((state: ChatStore) => {
@@ -936,8 +972,9 @@ export class OperationActionsImpl {
n(`removeQueuedMessage/${contextKey}/${messageId}`),
);
- // The last queued message is gone: let the run finish its turn normally.
- if (!this.#get().queuedMessages[contextKey]?.length)
+ // The last message only this client holds is gone: let the run finish its
+ // turn normally.
+ if (!this.#get().queuedMessages[contextKey]?.some(isClientHeldQueuedMessage))
this.#get().internal_syncQueuedMessagesFlag(contextKey);
};
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 628c096fe41..c7e3abdde7d 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -965,14 +965,17 @@ const getIdleQueueHost = (context: MessageMapKeyInput) => (s: ChatStoreState) =>
// A successful top-level run always drains its queue into a steered send, so a
// queue sitting behind a completed run is the hand-off window, not a stale queue.
+const isDrainingQueueHost = (host?: Operation): boolean =>
+ host?.status === 'completed' && !host.metadata.endedWithoutCompletion;
+
const isQueueDrainPending = (context: MessageMapKeyInput) => (s: ChatStoreState) =>
- getIdleQueueHost(context)(s)?.status === 'completed';
+ isDrainingQueueHost(getIdleQueueHost(context)(s));
// Send now keeps its item queued until the interrupt is confirmed; that wait is
// part of the hand-off too, but its own send must not be re-queued.
const isSteerHandoffPending = (context: MessageMapKeyInput) => (s: ChatStoreState) => {
const host = getIdleQueueHost(context)(s);
- if (host?.status === 'completed') return true;
+ if (isDrainingQueueHost(host)) return true;
return host?.status === 'cancelled' && host.metadata.cancelReason === SEND_NOW_CANCEL_REASON;
};
@@ -1045,6 +1048,7 @@ export const operationSelectors = {
visiblyRunningTopicIds,
// Message Queue
+ getIdleQueueHost,
getQueuedMessages,
queuedMessageCount,
};
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 82cffb4efa8..20602ebd53e 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -5,6 +5,8 @@ import type {
UploadFileItem,
} from '@lobechat/types';
+import type { QueuedFollowUpRequest } from '@/services/aiAgent';
+
/**
* Operation Type Definitions
* Unified operation state management for all async operations
@@ -132,6 +134,12 @@ export interface OperationMetadata {
// Cancel information
cancelReason?: string;
duration?: number;
+ /**
+ * The run ended without completing — stopped from another tab, device or the
+ * API — though it settles as `completed` here. Nothing drains its queue next.
+ */
+ endedWithoutCompletion?: boolean;
+
endTime?: number;
// Error information
@@ -151,7 +159,6 @@ export interface OperationMetadata {
// UI state (for sendMessage operation)
inputEditorTempState?: any | null; // Editor state snapshot for cancel restoration
-
inputSendErrorMsg?: string; // Error message to display in UI
// Progress information
progress?: {
@@ -159,6 +166,7 @@ export interface OperationMetadata {
total: number;
percentage?: number;
};
+
// Runtime hooks (collected during execution, executed after completion)
runtimeHooks?: RuntimeHooks;
@@ -262,6 +270,23 @@ export interface QueuedFile {
* optimistic-message path uses the `fileUrl || base64Url || previewUrl` fallback
* chain, while the desktop chat-input file preview only reads `previewUrl`.
*/
+/**
+ * Snapshot file previews so the tray can render thumbnails and the resumed
+ * sendMessage can rebuild audioList/imageList/videoList — by the time the
+ * queue drains, chatUploadFileList has long been cleared.
+ */
+export const snapshotQueuedFiles = (files?: UploadFileItem[]): QueuedFile[] | undefined => {
+ if (!files?.length) return undefined;
+
+ return files.map((f) => ({
+ audioMetadata: f.audioMetadata,
+ id: f.id,
+ mimeType: f.file?.type ?? '',
+ name: f.file?.name ?? f.id,
+ url: f.fileUrl || f.base64Url || f.previewUrl || '',
+ }));
+};
+
export const reconstructUploadFilesFromQueue = (files: QueuedFile[]): UploadFileItem[] =>
files.map((f) => ({
audioMetadata: f.audioMetadata,
@@ -289,8 +314,30 @@ export interface QueuedMessage {
id: string;
interruptMode: 'soft' | 'hard';
metadata?: MessageMetadata;
+ /**
+ * Where the server holds this follow-up: `appending` while it is being
+ * handed to the server queue behind the running Gateway run, `server` once
+ * it is there. The server then joins it into that run or starts it as the
+ * next turn, so this client never sends it. Unset: only this client has it.
+ */
+ serverDelivery?: 'appending' | 'server';
+ /**
+ * The run request the server starts this follow-up with. Set when the send
+ * could be queued on the server; such an item may be handed over later.
+ */
+ serverRequest?: QueuedFollowUpRequest;
+ /**
+ * The append's answer was lost, so it may or may not be on the server. It
+ * stays the server's — never sent from here — until the same id is appended
+ * again and the server says where it is.
+ */
+ serverUnconfirmed?: boolean;
}
+/** Whether only this client holds the queued message, so only it can send it. */
+export const isClientHeldQueuedMessage = (message: QueuedMessage): boolean =>
+ !message.serverDelivery;
+
/**
* Merged message ready for injection
*/