🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(channel): answer a person's queued requests together in one run (#23634)
Arvin Xu19884184eccb
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.mdindex b949b679a32..155eb6514f1 100644--- a/apps/server/src/services/channel/README.md+++ b/apps/server/src/services/channel/README.md@@ -160,6 +160,14 @@ actions in place. A shared Agent's card keeps the visitor-safe error projectionrewrite. A stop through the Channel cancels the job and writes no card. The job's own`errorMessage` / `errorType` / `deviceId` stay in the detail view for older clients.+Each member answers a branch in message order, but not one run per message: when a job is+claimed, the same person's owed answers queued right behind it from that member in that branch+are merged into the run (`claim.ts`, `merge.ts`). The manifest's cutoff and `requestMessageId`+move to the newest of them and `requestMessageIds` lists them all; their jobs settle as `merged`,+and only the first opens a reply. Merging stops at someone else's request, a `followup` wake, a+relay or brought-back answer, or a message whose routing is still undecided, and never applies+to a shared Agent, whose visitors are metered per request. Retrying the run re-queues them.+`routing_decided` audit details record the model/provider, prompt version, scenario, probabilities,token count, latency, and each member's own rule verdicts (`wakeRules`). No raw provider errors are stored. Runtime hooks still receive`trigger: channel`, the message ID and attempt for billing/routing observability.diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 88438531f46..b78193d328c 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -283,6 +283,7 @@"status.completed": "Replied","status.failed": "Reply failed","status.idle": "Idle",+ "status.merged": "Answered with an earlier message","status.paused": "Paused","status.preparing": "Preparing…","status.running": "Replying…",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 013f544d584..4b472eb9a78 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -283,6 +283,7 @@"status.completed": "已回复","status.failed": "回复失败","status.idle": "空闲",+ "status.merged": "已与前面的消息合并回复","status.paused": "已暂停","status.preparing": "准备中…","status.running": "正在回复…",diff --git a/packages/database/src/repositories/channel/__tests__/asyncRouting.test.ts b/packages/database/src/repositories/channel/__tests__/asyncRouting.test.tsindex 2c34c2cffaf..6832e6062ab 100644--- a/packages/database/src/repositories/channel/__tests__/asyncRouting.test.ts+++ b/packages/database/src/repositories/channel/__tests__/asyncRouting.test.ts@@ -73,11 +73,15 @@ describe('asynchronous Channel routing', () => {});const [firstJob] = await jobsOf(db, root.id);expect(await execution.claim(channel.id, nextJob.id, lease)).toBeNull();+ // Once routed, the earlier request runs first and answers the same person's follow-up with it.const first = await execution.claim(channel.id, firstJob.id, lease);- expect(first).not.toBeNull();+ expect(first?.job.manifest).toMatchObject({+ requestMessageId: next.id,+ requestMessageIds: [root.id, next.id],+ });+ expect(await jobById(db, nextJob.id)).toMatchObject({ status: 'merged' });await finish(channel.id, firstJob.id);- const second = await execution.claim(channel.id, nextJob.id, lease);- expect(second?.topic.id).toBe(first?.topic.id);+ expect(await execution.claim(channel.id, nextJob.id, lease)).toBeNull();});it.each(['skipped', 'unassigned'] as const)(diff --git a/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts b/packages/database/src/repositories/channel/__tests__/deleteMessage.test.tsindex 771145b0c7b..d829a59325c 100644--- a/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts+++ b/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import { ChannelExecutionRepository } from '..';-import { createChannelFixture, jobsOf, lease } from './testUtils';+import { createChannelFixture, jobById, jobsOf, lease } from './testUtils';const db = await getTestDB();const fixture = createChannelFixture(db, 'channel-delete-message');@@ -67,6 +67,77 @@ describe('ChannelRepository.deleteMessage', () => {expect(stopped).toMatchObject({ publicationRevoked: true, status: 'cancelled' });});+ it('stops the run that already absorbed a deleted request into its batch', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Device Agent');+ const send = async (content: string) => {+ const message = await asOwner.send(channel.id, {+ content,+ requestKey: content,+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ return { job, message };+ };++ const first = await send('first');+ await execution.claim(channel.id, first.job.id, lease);+ const second = await send('second');+ const third = await send('third');+ await execution.accepted(channel.id, first.job.id);+ await execution.saveDraft(channel.id, first.job.id, 'First answer');+ await execution.publish(channel.id, first.job.id);+ await execution.releaseWriter(channel.id, first.job.id);++ const claim = await execution.claim(channel.id, second.job.id, lease);+ expect(claim?.job.manifest?.requestMessageIds).toEqual([second.message.id, third.message.id]);+ // The third request is answered by that run, so no job row points at it any more.+ expect((await jobById(db, third.job.id)).status).toBe('merged');++ const writers = await asOwner.deleteMessage(channel.id, third.message.id);++ expect(writers.map((writer) => writer.id)).toEqual([second.job.id]);+ expect(await jobById(db, second.job.id)).toMatchObject({+ publicationRevoked: true,+ status: 'cancelled',+ });+ });++ it('queues the other absorbed requests again when the run that owns them is deleted', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Device Agent');+ const send = async (content: string) => {+ const message = await asOwner.send(channel.id, {+ content,+ requestKey: content,+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ return { job, message };+ };++ const first = await send('first');+ await execution.claim(channel.id, first.job.id, lease);+ const second = await send('second');+ const third = await send('third');+ await execution.accepted(channel.id, first.job.id);+ await execution.saveDraft(channel.id, first.job.id, 'First answer');+ await execution.publish(channel.id, first.job.id);+ await execution.releaseWriter(channel.id, first.job.id);++ await execution.claim(channel.id, second.job.id, lease);+ expect((await jobById(db, third.job.id)).status).toBe('merged');++ await asOwner.deleteMessage(channel.id, second.message.id);++ expect(await jobById(db, second.job.id)).toMatchObject({+ publicationRevoked: true,+ status: 'cancelled',+ });+ // The withdrawn request takes only its own answer away: the other one still gets a run.+ expect((await jobById(db, third.job.id)).status).toBe('queued');+ });+it('refuses to edit a tombstone back into a message', async () => {const { asMember, asOwner, channel } = await fixture.createTeamChannel();const sent = await asMember.send(channel.id, {diff --git a/packages/database/src/repositories/channel/__tests__/execution.test.ts b/packages/database/src/repositories/channel/__tests__/execution.test.tsindex b302084691c..02e60b3f315 100644--- a/packages/database/src/repositories/channel/__tests__/execution.test.ts+++ b/packages/database/src/repositories/channel/__tests__/execution.test.ts@@ -213,8 +213,9 @@ describe('ChannelExecutionRepository', () => {});it('answers a branch in message order and holds one writer per member in it', async () => {- const { agent, asMember, channel, job } = await mentionAgent();- const next = await asMember.send(channel.id, {+ const { agent, asOwner, channel, job } = await mentionAgent();+ // Someone else asks next: the same person's next request would be merged into the first run.+ const next = await asOwner.send(channel.id, {content: 'Second',mentions: [agent.id],requestKey: 'req-2',@@ -249,9 +250,9 @@ describe('ChannelExecutionRepository', () => {threads.push(await team.asMember.createThread(team.channel.id, { rootMessageId: root.id }));}let sent = 0;- const ask = async (threadId: string | null) => {+ const ask = async (threadId: string | null, as = team.asMember) => {sent += 1;- const message = await team.asMember.send(team.channel.id, {+ const message = await as.send(team.channel.id, {content: `Request ${sent}`,mentions: [agent.id],requestKey: `ask-${sent}`,@@ -265,10 +266,11 @@ describe('ChannelExecutionRepository', () => {};it('runs one member in several branches at once, each in message order', async () => {- const { ask, channel, threads } = await threadsFor(nativeConfig, ['A', 'B']);+ const { ask, asOwner, channel, threads } = await threadsFor(nativeConfig, ['A', 'B']);const [threadA, threadB] = threads;const a1 = await ask(threadA.id);- const a2 = await ask(threadA.id);+ // From someone else, so it waits for its own run instead of being merged into a1's.+ const a2 = await ask(threadA.id, asOwner);const b1 = await ask(threadB.id);const main = await ask(null);diff --git a/packages/database/src/repositories/channel/__tests__/mergeRequests.test.ts b/packages/database/src/repositories/channel/__tests__/mergeRequests.test.tsnew file mode 100644index 00000000000..eba0e32166f--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/mergeRequests.test.ts@@ -0,0 +1,276 @@+// @vitest-environment node+import type { ChannelInputManifest } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentOperations, workspaceMembers } from '../../../schemas';+import type { ChannelRepository } from '..';+import { ChannelExecutionRepository, ChannelRoutingRepository } from '..';+import { readManifestMessages } from '../manifest';+import { createChannelFixture, jobById, jobsOf, lease } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-merge-requests');+beforeEach(fixture.setup);+afterEach(fixture.cleanup);++const execution = new ChannelExecutionRepository(db);+const routing = new ChannelRoutingRepository(db);++const send = async (+ as: ChannelRepository,+ channelId: string,+ content: string,+ extra: { replyToId?: string } = {},+) => {+ const message = await as.send(channelId, {+ content,+ requestKey: content,+ routing: 'fallback',+ ...extra,+ });+ const [job] = await jobsOf(db, message.id);+ return { job, message };+};++/** Finishes a claimed job with a published reply. */+const finish = async (channelId: string, jobId: string) => {+ await execution.accepted(channelId, jobId);+ await execution.saveDraft(channelId, jobId, 'Answer');+ await execution.publish(channelId, jobId);+ await execution.releaseWriter(channelId, jobId);+};++/** A team Channel whose one Agent is busy answering the owner's first message. */+const busyAgent = async () => {+ const team = await fixture.createTeamChannel();+ await fixture.addAgent(team.channel.id, 'Agent');+ const first = await send(team.asOwner, team.channel.id, 'first');+ await execution.claim(team.channel.id, first.job.id, lease);+ return { ...team, first };+};++describe('Requests one person sends in a row while the Agent is busy', () => {+ it('are answered together in the next run, not one run each', async () => {+ const { asOwner, channel, first } = await busyAgent();+ const second = await send(asOwner, channel.id, 'second');+ const third = await send(asOwner, channel.id, 'third');+ const fourth = await send(asOwner, channel.id, 'fourth');++ await finish(channel.id, first.job.id);+ const claim = await execution.claim(channel.id, second.job.id, lease);++ expect(claim?.job.manifest).toMatchObject({+ cutoffSequence: fourth.message.sequence,+ requestMessageId: fourth.message.id,+ requestMessageIds: [second.message.id, third.message.id, fourth.message.id],+ });+ expect((await jobById(db, third.job.id)).status).toBe('merged');+ expect((await jobById(db, fourth.job.id)).status).toBe('merged');+ expect(+ (await execution.input(channel.id, second.job.id)).map(({ content }) => content),+ ).toEqual(['second', 'third', 'fourth']);+ // Nothing is left queued behind the merged run.+ expect(+ (await asOwner.detail(channel.id)).jobs.filter((job) => job.status === 'queued'),+ ).toEqual([]);+ });++ it('stops merging at a request from someone else', async () => {+ const { asMember, asOwner, channel, first } = await busyAgent();+ const second = await send(asOwner, channel.id, 'second');+ const other = await send(asMember, channel.id, 'from the member');+ const third = await send(asOwner, channel.id, 'third');++ await finish(channel.id, first.job.id);+ const claim = await execution.claim(channel.id, second.job.id, lease);++ expect(claim?.job.manifest?.requestMessageId).toBe(second.message.id);+ expect(claim?.job.manifest?.requestMessageIds).toBeUndefined();+ expect((await jobById(db, other.job.id)).status).toBe('queued');+ expect((await jobById(db, third.job.id)).status).toBe('queued');+ });++ it('opens one reply for the batch, not one per request', async () => {+ const { asOwner, channel } = await busyAgent();+ const second = await send(asOwner, channel.id, 'second');+ const third = await send(asOwner, channel.id, 'third');++ expect(await execution.openingCandidate(channel.id, second.job.id)).toBeDefined();+ expect(await execution.openingCandidate(channel.id, third.job.id)).toBeUndefined();+ });++ it('queues the merged requests again when their run is retried', async () => {+ const team = await fixture.createTeamChannel();+ await fixture.addAgent(team.channel.id, 'Device Agent');+ const first = await send(team.asOwner, team.channel.id, 'first');+ const second = await send(team.asOwner, team.channel.id, 'second');+ const claim = await execution.claim(team.channel.id, first.job.id, lease);+ expect(claim?.job.manifest?.requestMessageIds).toEqual([first.message.id, second.message.id]);++ await db+ .update(agentOperations)+ .set({+ error: { message: 'offline', type: 'DeviceGatewayNotConfigured' },+ status: 'error',+ })+ .where(eq(agentOperations.id, claim!.job.operationId!));+ await execution.fail(team.channel.id, first.job.id, { message: 'Agent could not start' });+ await execution.releaseWriter(team.channel.id, first.job.id);+ await team.asOwner.retryJob(team.channel.id, first.job.id);++ expect((await jobById(db, second.job.id)).status).toBe('queued');+ const again = await execution.claim(team.channel.id, first.job.id, lease);+ expect(again?.job.manifest?.requestMessageIds).toEqual([first.message.id, second.message.id]);+ });+});++describe('a deferred follow-up whose request an earlier run answers', () => {+ it('waits for the merged answer and then reads it', async () => {+ const team = await fixture.createTeamChannel();+ // Routing asks the workspace who the sender is.+ await db.insert(workspaceMembers).values({+ role: 'owner',+ userId: fixture.ownerId,+ workspaceId: fixture.workspaceId,+ });+ const coder = await fixture.addAgent(team.channel.id, 'Coder');+ const reviewer = await fixture.addAgent(team.channel.id, 'Reviewer');++ /** One request routed by decision, with the reviewers it wakes. */+ const ask = async (content: string, deferredBehind?: string) => {+ const message = await team.asOwner.send(team.channel.id, {+ content,+ requestKey: content,+ routing: 'decision',+ });+ const input = await routing.claim(team.channel.id, message.id);+ await execution.resolveRouting(team.channel.id, message.id, input!.attempt, {+ memberIds: deferredBehind ? [coder.id, reviewer.id] : [coder.id],+ reason: 'test',+ status: 'assigned',+ ...(deferredBehind && {+ wakes: {+ [reviewer.id]: {+ afterMemberId: deferredBehind,+ kind: 'followup',+ reason: 'routing-deferred',+ },+ },+ }),+ });+ return message;+ };++ const first = await ask('first');+ // The reviewer is deferred behind the coder only for this later request.+ const second = await ask('second', coder.id);+ const secondJobs = await jobsOf(db, second.id);+ const secondPrimary = secondJobs.find((job) => job.memberId === coder.id)!;+ const secondFollowUp = secondJobs.find((job) => job.memberId === reviewer.id)!;++ const firstJob = (await jobsOf(db, first.id)).find((job) => job.memberId === coder.id)!;+ const claim = await execution.claim(team.channel.id, firstJob.id, lease);+ // The earlier run answers both requests, so the later primary settles as merged.+ expect(claim?.job.manifest?.requestMessageIds).toEqual([first.id, second.id]);+ expect((await jobById(db, secondPrimary.id)).status).toBe('merged');++ // Its request is still owed an answer — the batch's — so the follow-up keeps waiting.+ expect(await execution.claim(team.channel.id, secondFollowUp.id, lease)).toBeNull();+ expect((await jobById(db, secondFollowUp.id)).blockedCode).toBe('awaiting_primary');++ await finish(team.channel.id, claim!.job.id);++ // Then it runs, with the batch's answer in view.+ expect(await execution.claim(team.channel.id, secondFollowUp.id, lease)).not.toBeNull();+ expect(await execution.primaryReply(team.channel.id, secondFollowUp.id)).toMatchObject({+ content: 'Answer',+ });+ });+});++describe('a Thread whose root an earlier run merged', () => {+ it('starts only after that run answers the root', async () => {+ const team = await fixture.createTeamChannel();+ // Routing asks the workspace who the sender is.+ await db.insert(workspaceMembers).values({+ role: 'owner',+ userId: fixture.ownerId,+ workspaceId: fixture.workspaceId,+ });+ const agent = await fixture.addAgent(team.channel.id, 'Agent');++ /** One request on the given timeline, routed to the Agent by decision. */+ const ask = async (content: string, threadId?: string) => {+ const message = await team.asOwner.send(team.channel.id, {+ content,+ requestKey: content,+ routing: 'decision',+ ...(threadId && { threadId }),+ });+ const input = await routing.claim(team.channel.id, message.id);+ await execution.resolveRouting(team.channel.id, message.id, input!.attempt, {+ memberIds: [agent.id],+ reason: 'test',+ status: 'assigned',+ });+ return message;+ };++ const root = await ask('root');+ const later = await ask('later');+ const rootJob = (await jobsOf(db, root.id)).find((job) => job.memberId === agent.id)!;+ const laterJob = (await jobsOf(db, later.id)).find((job) => job.memberId === agent.id)!;++ // The Agent answers both main-timeline requests in one run, so the later one is merged.+ const claim = await execution.claim(team.channel.id, rootJob.id, lease);+ expect(claim?.job.manifest?.requestMessageIds).toEqual([root.id, later.id]);+ expect((await jobById(db, laterJob.id)).status).toBe('merged');++ // A Thread hangs off the merged request; that request is still owed the same run's answer.+ const thread = await team.asOwner.createThread(team.channel.id, { rootMessageId: later.id });+ const inThread = await ask('in the thread', thread.id);+ const threadJob = (await jobsOf(db, inThread.id)).find((job) => job.memberId === agent.id)!;++ expect(await execution.claim(team.channel.id, threadJob.id, lease)).toBeNull();+ expect((await jobById(db, threadJob.id)).blockedCode).toBe('member_busy');++ await finish(team.channel.id, claim!.job.id);++ expect(await execution.claim(team.channel.id, threadJob.id, lease)).not.toBeNull();+ });+});++describe('the scope of a batch continued into a Thread', () => {+ it('keeps what an earlier request of the batch quotes', async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Agent');+ const root = await send(team.asOwner, team.channel.id, 'thread root');+ // Quoted by the first request; posted on the main timeline after the Thread's root.+ const quote = await send(team.asOwner, team.channel.id, 'the log I mean');+ const first = await send(team.asOwner, team.channel.id, 'first request', {+ replyToId: quote.message.id,+ });+ const last = await send(team.asOwner, team.channel.id, 'last request');++ // The branch the two requests were continued into, as the merged run freezes it.+ const manifest: ChannelInputManifest = {+ cutoffSequence: last.message.sequence,+ requestMessageId: last.message.id,+ requestMessageIds: [first.message.id, last.message.id],+ requesterMemberId: agent.id,+ self: { agentId: agent.agentId!, memberId: agent.id, name: 'Agent' },+ threadId: 'thread-the-requests-were-continued-in',+ threadRootSequence: root.message.sequence,+ };++ expect(+ (+ await readManifestMessages(db, team.channel.id, manifest, {+ messageIds: [quote.message.id],+ })+ ).map(({ content }) => content),+ ).toEqual(['the log I mean']);+ });+});diff --git a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts b/packages/database/src/repositories/channel/__tests__/replyOpening.test.tsindex 770c774cdd5..d4370dba1dd 100644--- a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts+++ b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts@@ -696,7 +696,7 @@ describe('Channel reply opening', () => {});it('offers only where a quoted request was answered, and hands the opener the quote', async () => {- const { agent, asMember, channel, message, thread } = await answeredInThread();+ const { agent, asMember, asOwner, channel, message, thread } = await answeredInThread();// A second request answered in place, on the main timeline.const inPlace = await asMember.send(channel.id, {content: 'Should the member list match the personal space?',@@ -707,7 +707,9 @@ describe('Channel reply opening', () => {const [inPlaceJob] = await jobsOf(db, inPlace.id);await execution.open(channel.id, inPlaceJob.id, {});- const quoting = await asMember.send(channel.id, {+ // From someone else: the same person's request queued right behind theirs would be merged+ // into that run, which opens for both.+ const quoting = await asOwner.send(channel.id, {content: 'Why is this UI still unchanged?',mentions: [agent.id],replyToId: inPlace.id,diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex 6d34da41a49..ac89204f60f 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -1,6 +1,6 @@import type { ChannelExecutionConfig, ChannelJobBlockCode, LobeAgentConfig } from '@lobechat/types';import { channelMessageDeletedAt } from '@lobechat/types';-import { and, asc, eq, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';import type { ChannelItem, ChannelJobItem, ChannelMemberItem, TopicItem } from '../../schemas';@@ -18,6 +18,7 @@ import { resolveExecutionConfig } from './agent';import { AWAITING_PRIMARY_REASON, findThread } from './delivery';import { requestMissingGrant } from './grants';import { buildManifest } from './manifest';+import { findMergeableRequests, mergeJobs } from './merge';import type { ChannelTopicScope } from './topic';import { continuationTopic, resolveTopic, resumableTopic } from './topic';import { audit } from './transaction';@@ -214,6 +215,39 @@ const STUCK_BLOCKS = new Set<ChannelJobBlockCode>(['workspace_changed',]);+/**+ * The run that answers a request: the job whose manifest lists the message in its batch. A request+ * settled as `merged` has no writer and no queued row of its own — the run that merged it holds it.+ */+const answeringRun = async (+ tx: Transaction,+ channelId: string,+ memberId: string,+ messageId: string,+) => {+ const [owner] = await tx+ .select({+ blockedCode: channelJobs.blockedCode,+ isolatedAt: channelJobs.isolatedAt,+ publishedMessageId: channelJobs.publishedMessageId,+ status: channelJobs.status,+ writerHeld: channelJobs.writerHeld,+ })+ .from(channelJobs)+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.memberId, memberId),+ inArray(channelJobs.status, ['queued', 'running', 'completed']),+ sql`${channelJobs.manifest} -> 'requestMessageIds' @> ${JSON.stringify([messageId])}::jsonb`,+ ),+ )+ .orderBy(desc(channelJobs.claimedAt))+ .limit(1);++ return owner;+};+/** The job of the member a deferred follow-up waits for, on the same message. */const primaryJob = async (tx: Transaction, job: ChannelJobItem, memberId: string) => {const [primary] = await tx@@ -230,7 +264,14 @@ const primaryJob = async (tx: Transaction, job: ChannelJobItem, memberId: stringeq(channelJobs.memberId, memberId),),);- return primary;+ // The request was queued right behind an earlier one of the same person and answered by that+ // earlier request's run, which settles it as `merged`. Its answer is the batch's answer, so the+ // follow-up waits for, and reads the reply of, the run that merged it.+ if (primary?.status !== 'merged') return primary;++ const owner = await answeringRun(tx, job.channelId, memberId, job.messageId);++ return owner ?? primary;};/**@@ -342,24 +383,34 @@ export const claimJob = async (}// A Thread follows its root: the member answers the root on the main timeline first.- const [rootReply] = thread+ const [root] = thread? await tx- .select({ id: channelJobs.id })+ .select({+ isolatedAt: channelJobs.isolatedAt,+ status: channelJobs.status,+ writerHeld: channelJobs.writerHeld,+ }).from(channelJobs).where(and(eq(channelJobs.memberId, job.memberId),eq(channelJobs.messageId, thread.rootMessageId),isNull(channelJobs.threadId),- or(- eq(channelJobs.status, 'queued'),- and(eq(channelJobs.writerHeld, true), isNull(channelJobs.isolatedAt)),- ),),).limit(1): [];- if (rootReply) {+ // The root may have been settled as `merged` into an earlier run of the same batch: such a row+ // has no writer and no queued row of its own, yet that run still owes the root its answer. So+ // resolve it to the run that answers it before deciding, the way `primaryJob()` does.+ const rootReply =+ root?.status === 'merged'+ ? await answeringRun(tx, channel.id, job.memberId, thread!.rootMessageId)+ : root;+ if (+ rootReply &&+ (rootReply.status === 'queued' || (rootReply.writerHeld && rootReply.isolatedAt === null))+ ) {await block(tx, job, 'member_busy', 'Waiting for an earlier reply from this Agent');return null;}@@ -488,9 +539,13 @@ export const claimJob = async (const topic =resumed ??(await resolveTopic(tx, channel, job, member, scope, request.sequence, executionConfig));+ // The requester's next requests queued behind this one are answered in the same run. A shared+ // Agent's visitor is metered per request, so each of theirs stays its own run.+ const merged = share ? [] : await findMergeableRequests(tx, job, request);const manifest = buildManifest({job,member,+ merged: merged.map((next) => next.request),primaryReplyMessageId: primary?.publishedMessageId ?? undefined,request,resumed: !!resumed,@@ -530,6 +585,11 @@ export const claimJob = async (}).where(eq(channelJobs.id, job.id)).returning();+ await mergeJobs(+ tx,+ updated,+ merged.map((next) => next.job.id),+ );const claimed = { job: updated, topic };await audit(tx, channel.id, 'run_claimed', job.id, {diff --git a/packages/database/src/repositories/channel/delete.ts b/packages/database/src/repositories/channel/delete.tsindex 7443301f280..7618b1ae2b5 100644--- a/packages/database/src/repositories/channel/delete.ts+++ b/packages/database/src/repositories/channel/delete.ts@@ -53,7 +53,53 @@ export const deleteMessage = async (),);const writers: ChannelJobItem[] = [];- for (const job of open) writers.push(...(await stopScope(tx, channelId, { jobId: job.id })));+ const stopped = new Set<string>();+ const stop = async (jobId: string) => {+ if (stopped.has(jobId)) return;+ stopped.add(jobId);+ writers.push(...(await stopScope(tx, channelId, { jobId })));+ };++ // An earlier run may already answer this request as part of a batch (`requestMessageIds`), in+ // which case no job row points at it any more. That owner has to stop too, or it publishes an+ // answer over a withdrawn request; the requests it absorbed go back to the queue so their+ // senders still get one. Read the open batches before any job is cancelled below.+ const batches = await tx+ .select({+ id: channelJobs.id,+ manifest: channelJobs.manifest,+ memberId: channelJobs.memberId,+ messageId: channelJobs.messageId,+ })+ .from(channelJobs)+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ inArray(channelJobs.status, OPEN_JOB_STATUSES),+ sql`${channelJobs.manifest} IS NOT NULL`,+ ),+ );++ for (const job of open) await stop(job.id);++ for (const batch of batches) {+ const requested = batch.manifest?.requestMessageIds;+ if (!requested?.includes(messageId)) continue;+ const absorbed = requested.filter((id) => id !== messageId && id !== batch.messageId);+ if (absorbed.length)+ await tx+ .update(channelJobs)+ .set({ status: 'queued' })+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.memberId, batch.memberId),+ inArray(channelJobs.messageId, absorbed),+ eq(channelJobs.status, 'merged'),+ ),+ );+ await stop(batch.id);+ }await tx.update(channelMessages)diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex 1e304eab4de..d221f7d77c8 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -287,8 +287,9 @@ export class ChannelExecutionRepository {);/**- * The triggering request and its explicit quote; see `recentContext` for the rest. Reads- * without the channel lock, since nothing at or before the cutoff changes after the claim.+ * The triggering requests (one, or a merged batch oldest first) and the messages they quote;+ * see `recentContext` for the rest. Reads without the channel lock, since nothing at or+ * before the cutoff changes after the claim.*/input = async (channelId: string, jobId: string): Promise<ChannelContextMessage[]> => {const [job] = await this.db@@ -303,15 +304,19 @@ export class ChannelExecutionRepository {);if (!job?.manifest) throw new ChannelError('NOT_FOUND', 'Claimed job not found');- const request = await readManifestMessages(this.db, channelId, job.manifest, {- messageId: job.manifest.requestMessageId,+ const { manifest } = job;+ const requestIds = manifest.requestMessageIds ?? [manifest.requestMessageId];+ const requests = await readManifestMessages(this.db, channelId, manifest, {+ messageIds: requestIds,});- const replyToId = request[0]?.replyToId;- if (!replyToId) return request;- const quoted = await readManifestMessages(this.db, channelId, job.manifest, {- messageId: replyToId,+ const quotedIds = [+ ...new Set(requests.flatMap(({ replyToId }) => (replyToId ? [replyToId] : []))),+ ].filter((id) => !requestIds.includes(id));+ if (!quotedIds.length) return requests;+ const quoted = await readManifestMessages(this.db, channelId, manifest, {+ messageIds: quotedIds,});- return [...quoted, ...request];+ return [...quoted, ...requests];};/**diff --git a/packages/database/src/repositories/channel/manifest.ts b/packages/database/src/repositories/channel/manifest.tsindex 8ba26aa3ac9..007eb00ebef 100644--- a/packages/database/src/repositories/channel/manifest.ts+++ b/packages/database/src/repositories/channel/manifest.ts@@ -7,7 +7,21 @@ import {channelMessageReplyError,channelMessageVia,} from '@lobechat/types';-import { and, asc, count, desc, eq, gt, isNull, lt, lte, notInArray, or, sql } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ gt,+ inArray,+ isNull,+ lt,+ lte,+ notInArray,+ or,+ sql,+} from 'drizzle-orm';import type {ChannelJobItem,@@ -29,6 +43,8 @@ export const replyErrorNote = (agentName: string) => `${agentName} did not finisexport const buildManifest = (params: {job: ChannelJobItem;member: ChannelMemberItem;+ /** Later requests from the same requester answered in this run, oldest first. */+ merged?: ChannelMessageItem[];/** A deferred follow-up's view of the primary responder's published reply. */primaryReplyMessageId?: string;request: ChannelMessageItem;@@ -36,13 +52,17 @@ export const buildManifest = (params: {resumed?: boolean;thread: ChannelThreadItem | null;}): ChannelInputManifest => {- const { job, member, primaryReplyMessageId, request, resumed, thread } = params;+ const { job, member, merged = [], primaryReplyMessageId, request, resumed, thread } = params;+ const last = merged.at(-1) ?? request;return {- // Jobs inherit the request's branch, so the request itself always sorts last.- cutoffSequence: request.sequence,+ // Jobs inherit the request's branch, so the last request always sorts last.+ cutoffSequence: last.sequence,...(primaryReplyMessageId && { primaryReplyMessageId }),- requestMessageId: request.id,+ requestMessageId: last.id,+ ...(merged.length > 0 && {+ requestMessageIds: [request.id, ...merged.map((next) => next.id)],+ }),requesterMemberId: job.requesterMemberId,...(resumed && { resumed: true }),self: { agentId: member.agentId!, memberId: member.id, name: member.name ?? 'Agent' },@@ -54,6 +74,11 @@ export const buildManifest = (params: {/** The branch messages a manifest covers; see {@link buildManifest}. */const manifestScope = (channelId: string, manifest: ChannelInputManifest) => {const { threadId, threadRootSequence } = manifest;+ // Every request the run answers: a batch merges later requests into the first one's run, and+ // what each of them quotes is part of what it was asked.+ const requestIds = manifest.requestMessageIds?.length+ ? manifest.requestMessageIds+ : [manifest.requestMessageId];const mainPrefix =threadRootSequence === null? undefined@@ -71,14 +96,17 @@ const manifestScope = (channelId: string, manifest: ChannelInputManifest) => {or(eq(channelMessages.threadId, threadId),mainPrefix,- eq(channelMessages.id, manifest.requestMessageId),+ inArray(channelMessages.id, requestIds),and(isNull(channelMessages.threadId),sql`${channelMessages.id} IN (SELECT ${channelJobs.messageId} FROM ${channelJobs} WHERE ${channelJobs.channelId} = ${channelId} AND ${channelJobs.threadId} = ${threadId})`,),and(isNull(channelMessages.threadId),- sql`${channelMessages.id} = (SELECT request.reply_to_id FROM channel_messages AS request WHERE request.id = ${manifest.requestMessageId} AND request.thread_id IS NULL)`,+ sql`${channelMessages.id} IN (SELECT request.reply_to_id FROM channel_messages AS request WHERE request.id IN (${sql.join(+ requestIds.map((id) => sql`${id}`),+ sql`, `,+ )}) AND request.thread_id IS NULL AND request.reply_to_id IS NOT NULL)`,),): isNull(channelMessages.threadId),@@ -120,7 +148,13 @@ export const readManifestMessages = async (db: LobeChatDatabase | Transaction,channelId: string,manifest: ChannelInputManifest,- options: { beforeSequence?: number; limit?: number; messageId?: string } = {},+ options: {+ beforeSequence?: number;+ limit?: number;+ messageId?: string;+ /** Only these messages; an empty list reads none. */+ messageIds?: string[];+ } = {},): Promise<ChannelContextMessage[]> => {const scope = and(manifestScope(channelId, manifest),@@ -128,6 +162,7 @@ export const readManifestMessages = async (? undefined: lt(channelMessages.sequence, options.beforeSequence),options.messageId ? eq(channelMessages.id, options.messageId) : undefined,+ options.messageIds ? inArray(channelMessages.id, options.messageIds) : undefined,);const query = db.select({diff --git a/packages/database/src/repositories/channel/merge.ts b/packages/database/src/repositories/channel/merge.tsnew file mode 100644index 00000000000..d01903b622c--- /dev/null+++ b/packages/database/src/repositories/channel/merge.ts@@ -0,0 +1,131 @@+import { channelMessageDeletedAt, channelMessageReceipt, channelMessageVia } from '@lobechat/types';+import { and, asc, desc, eq, gt, inArray, isNull, lt, or } from 'drizzle-orm';++import type { ChannelJobItem, ChannelMessageItem } from '../../schemas';+import { channelJobs, channelMessages } from '../../schemas';+import type { LobeChatDatabase, Transaction } from '../../type';+import { isAgentAuthored } from './author';+import { audit } from './transaction';++/** Most requests one run answers together; the rest wait for the next run. */+export const MAX_MERGED_REQUESTS = 10;++/**+ * Whether a queued job owes an answer that may be merged with the requester's next ones: a+ * person's own message, not a `followup` wake (it may stay silent, and a deferred one waits for+ * another reply), an Agent's message, a relay for someone elsewhere or an answer brought back.+ */+const isMergeable = (job: Pick<ChannelJobItem, 'wake'>, request: ChannelMessageItem) =>+ !job.wake &&+ !isAgentAuthored(request) &&+ !channelMessageVia(request.metadata) &&+ !channelMessageReceipt(request.metadata) &&+ !channelMessageDeletedAt(request.metadata);++/**+ * The requests queued right behind a head job that one run can answer with it: the same+ * person's owed answers from this member in this branch, in message order. Stops at the first+ * one that is not, and at an undecided message, which could yet queue another request between+ * them. Messages from others in between stay context, not requests.+ */+export const findMergeableRequests = async (+ tx: Transaction,+ job: ChannelJobItem,+ request: ChannelMessageItem,+): Promise<{ job: ChannelJobItem; request: ChannelMessageItem }[]> => {+ if (!isMergeable(job, request)) return [];++ // A Thread's requests may also be main-timeline messages continued into it, so an undecided+ // main-timeline message holds a Thread's batch back too.+ const [pendingRoute] = await tx+ .select({ sequence: channelMessages.sequence })+ .from(channelMessages)+ .where(+ and(+ eq(channelMessages.channelId, job.channelId),+ gt(channelMessages.sequence, request.sequence),+ eq(channelMessages.routingStatus, 'pending'),+ job.threadId+ ? or(eq(channelMessages.threadId, job.threadId), isNull(channelMessages.threadId))+ : isNull(channelMessages.threadId),+ ),+ )+ .orderBy(asc(channelMessages.sequence))+ .limit(1);++ const queued = await tx+ .select({ job: channelJobs, request: channelMessages })+ .from(channelJobs)+ .innerJoin(channelMessages, eq(channelMessages.id, channelJobs.messageId))+ .where(+ and(+ eq(channelJobs.channelId, job.channelId),+ eq(channelJobs.memberId, job.memberId),+ eq(channelJobs.status, 'queued'),+ job.threadId ? eq(channelJobs.threadId, job.threadId) : isNull(channelJobs.threadId),+ gt(channelMessages.sequence, request.sequence),+ pendingRoute ? lt(channelMessages.sequence, pendingRoute.sequence) : undefined,+ ),+ )+ .orderBy(asc(channelMessages.sequence), asc(channelJobs.createdAt))+ .limit(MAX_MERGED_REQUESTS - 1);++ const mergeable: typeof queued = [];+ for (const next of queued) {+ if (+ next.job.requesterMemberId !== job.requesterMemberId ||+ next.request.userId !== request.userId ||+ !isMergeable(next.job, next.request)+ )+ break;+ mergeable.push(next);+ }+ return mergeable;+};++/**+ * Whether a queued job will be answered by an earlier one's run: the queued job right before it+ * from this member in this branch is the same person's owed answer. Such a job opens no reply+ * of its own; the run that answers it does.+ */+export const isMergedBehind = async (+ db: LobeChatDatabase | Transaction,+ job: ChannelJobItem,+ request: ChannelMessageItem,+) => {+ if (!isMergeable(job, request)) return false;++ const [previous] = await db+ .select({ job: channelJobs, request: channelMessages })+ .from(channelJobs)+ .innerJoin(channelMessages, eq(channelMessages.id, channelJobs.messageId))+ .where(+ and(+ eq(channelJobs.channelId, job.channelId),+ eq(channelJobs.memberId, job.memberId),+ eq(channelJobs.status, 'queued'),+ job.threadId ? eq(channelJobs.threadId, job.threadId) : isNull(channelJobs.threadId),+ lt(channelMessages.sequence, request.sequence),+ ),+ )+ .orderBy(desc(channelMessages.sequence))+ .limit(1);++ return (+ !!previous &&+ previous.job.requesterMemberId === job.requesterMemberId &&+ previous.request.userId === request.userId &&+ isMergeable(previous.job, previous.request)+ );+};++/** Settles queued jobs whose requests the claimed job answers in its own run. */+export const mergeJobs = async (tx: Transaction, into: ChannelJobItem, jobIds: string[]) => {+ if (!jobIds.length) return;++ await tx+ .update(channelJobs)+ .set({ blockedCode: null, blockedReason: null, deviceId: null, status: 'merged' })+ .where(and(inArray(channelJobs.id, jobIds), eq(channelJobs.status, 'queued')));+ await audit(tx, into.channelId, 'jobs_merged', into.id, { jobs: jobIds });+};diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.tsindex 4302831aea4..9df5e16d203 100644--- a/packages/database/src/repositories/channel/opening.ts+++ b/packages/database/src/repositories/channel/opening.ts@@ -19,6 +19,7 @@ import { notTrashed } from '../../utils/softDelete';import { channelReplyShare } from './agent';import { appendMessage } from './delivery';import { readManifestMessages } from './manifest';+import { isMergedBehind } from './merge';import type { OpeningFacts, OpeningLayout } from './openingLayout';import { chooseOpeningLayout } from './openingLayout';import { messageStands } from './tombstone';@@ -228,7 +229,7 @@ export const findOpeningCandidate = async (if (!requester?.userId) return;const [[request], [thread], [channel]] = await Promise.all([- db.select(requestColumns).from(channelMessages).where(eq(channelMessages.id, job.messageId)),+ db.select().from(channelMessages).where(eq(channelMessages.id, job.messageId)),job.threadId? db.select({ rootSequence: channelThreads.rootSequence })@@ -241,6 +242,10 @@ export const findOpeningCandidate = async (.where(eq(channels.id, channelId)),]);if (!request || !channel) return;+ const share = await channelReplyShare(db, channel, row.agentId, requester.userId);+ // Answered in the run of the same person's earlier request, which opens for both. A shared+ // Agent answers each of a visitor's requests in its own run.+ if (!share && (await isMergedBehind(db, job, request))) return;// The request's branch up to the request itself, as the run's manifest will freeze it.const manifest = {cutoffSequence: request.sequence,@@ -273,7 +278,7 @@ export const findOpeningCandidate = async (recent: messages.filter((message) => message.id !== job.messageId),request: requestMessage,requesterUserId: requester.userId,- share: await channelReplyShare(db, channel, row.agentId, requester.userId),+ share,// Agents asked together share one new Thread under the request instead.threads:job.threadId || coAddressed.lengthdiff --git a/packages/database/src/repositories/channel/retry.ts b/packages/database/src/repositories/channel/retry.tsindex 9971a4c79ad..12045da94ea 100644--- a/packages/database/src/repositories/channel/retry.ts+++ b/packages/database/src/repositories/channel/retry.ts@@ -1,5 +1,5 @@import { channelMessageDeletedAt } from '@lobechat/types';-import { and, eq } from 'drizzle-orm';+import { and, eq, inArray } from 'drizzle-orm';import type { ChannelJobItem } from '../../schemas';import { channelJobs, channelMessages } from '../../schemas';@@ -26,6 +26,7 @@ export type ChannelRetryMode = 'resume' | 'retry';* continues there when that topic is still usable for the same environment (see* `resumableTopic`), with a short continuation prompt.*+ * Requests merged into the failed run go back with it, so the next claim merges them again.* `requesterMemberId` limits the retry to that member's own request; admins pass none.*/export const retryJob = async (@@ -79,6 +80,20 @@ export const retryJob = async (}).where(eq(channelJobs.id, job.id)).returning();+ // Requests merged into the failed run go back too, so the next claim merges them again.+ const merged = job.manifest?.requestMessageIds?.filter((id) => id !== job.messageId) ?? [];+ if (merged.length)+ await tx+ .update(channelJobs)+ .set({ status: 'queued' })+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.memberId, job.memberId),+ inArray(channelJobs.messageId, merged),+ eq(channelJobs.status, 'merged'),+ ),+ );await audit(tx, channelId, resume ? 'job_resumed' : 'job_retried', job.id, {operationId: job.operationId,});diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 041759c35c4..4327dc26042 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -189,6 +189,7 @@ export default {'status.failed': 'Reply failed','status.cancelled': 'Stopped','status.silent': 'Stayed quiet',+ 'status.merged': 'Answered with an earlier message','blocked.awaiting_primary': 'Waiting for another Agent to reply first','blocked.device_approval_pending': 'Waiting for device approval','blocked.device_offline': 'Waiting for device to connect',diff --git a/packages/prompts/src/chains/channel.test.ts b/packages/prompts/src/chains/channel.test.tsindex e19194f3dcb..4851e4f5c8e 100644--- a/packages/prompts/src/chains/channel.test.ts+++ b/packages/prompts/src/chains/channel.test.ts@@ -37,6 +37,40 @@ describe('Channel request prompt', () => {const caller = { id: 'caller', name: 'Mia', type: 'user' } as const;const coder = { id: 'coder', name: 'Coder', type: 'agent' } as const;+ it('asks for one answer to requests the same person sent in a row', () => {+ const prompt = buildChannelPrompt(+ { ...manifest, requestMessageIds: ['first', 'current'] },+ [+ message('quoted', 'The plan', coder),+ message('first', 'Fix the list', caller, { replyToId: 'quoted' }),+ message('current', 'Only the queued items', caller),+ ],+ {+ boundary: 'b0',+ // The earlier request is also unseen context; it is shown once, as a request.+ context: [message('first', 'Fix the list', caller), message('theirs', 'Ok', coder)],+ },+ );++ expect(prompt.split('\n')).toEqual([+ '<channel_message from="Coder" type="agent" boundary="b0">',+ 'Ok',+ '</channel_message boundary="b0">',+ '<channel_quote from="Coder" type="agent" boundary="b0">',+ 'The plan',+ '</channel_quote boundary="b0">',+ '<channel_request from="Mia" type="user" to="Codex" boundary="b0">',+ 'Fix the list',+ '</channel_request boundary="b0">',+ '<channel_request from="Mia" type="user" to="Codex" boundary="b0">',+ 'Only the queued items',+ '</channel_request boundary="b0">',+ '<channel_merged boundary="b0">',+ 'The 2 `channel_request` blocks are requests the same person sent in a row while you were busy, oldest first. Answer them together in one reply. Where a later one corrects, narrows or replaces an earlier one, follow the later one.',+ '</channel_merged boundary="b0">',+ ]);+ });+it('marks the member’s own earlier replies and says how much unseen history is left out', () => {const self = { id: 'agent', name: 'Codex', type: 'agent' } as const;const prompt = buildChannelPrompt(manifest, [message('current', 'And now?', caller)], {diff --git a/packages/prompts/src/chains/channel.ts b/packages/prompts/src/chains/channel.tsindex 210988f8de2..e74a8ee3906 100644--- a/packages/prompts/src/chains/channel.ts+++ b/packages/prompts/src/chains/channel.ts@@ -40,6 +40,10 @@ const DEFERRED_WAKE_HINT = `Another participant was asked to answer this requestconst peersHint = (names: string[]) =>`This request also asked ${names.join(', ')} to answer. They answer it in parallel, in the same conversation, and the person reads all the answers together, so a second walk through the whole request is noise. Do not lay out the full picture end to end, even when the request asks for it: answer only the part your own role owns, in depth, and leave the rest to them. Do not describe this division or say what the others will do.`;+/** What a run answering several requests sent in a row is told. */+const mergedHint = (count: number) =>+ `The ${count} \`channel_request\` blocks are requests the same person sent in a row while you were busy, oldest first. Answer them together in one reply. Where a later one corrects, narrows or replaces an earlier one, follow the later one.`;+/** Longest context excerpt in the request; the history tools return the rest. */const CONTEXT_EXCERPT_LENGTH = 2000;const QUOTE_EXCERPT_LENGTH = 6000;@@ -97,12 +101,13 @@ const createBoundary = (contents: string[]) => {};/**- * The run's user message: unseen recent context, the explicit quote, then the request,- * attributed by display name. Ids appear only where a tool call is the way to read more;+ * The run's user message: unseen recent context, the explicit quotes, then the request (or the+ * requests one person sent in a row while the member was busy, oldest first), attributed by+ * display name. Ids appear only where a tool call is the way to read more;* older history stays behind the tools.*/export const buildChannelPrompt = (- manifest: Pick<ChannelInputManifest, 'requestMessageId' | 'self'>,+ manifest: Pick<ChannelInputManifest, 'requestMessageId' | 'requestMessageIds' | 'self'>,messages: ChannelContextMessage[],options: {boundary?: string;@@ -128,20 +133,22 @@ export const buildChannelPrompt = (const context = resume ? [] : (options.context ?? []);const omitted = resume ? 0 : omittedCount;const selfAgentId = manifest.self.agentId;- const request = messages.find(({ id }) => id === manifest.requestMessageId);- const quoted = messages.find(({ id }) => id === request?.replyToId);+ const requestIds = manifest.requestMessageIds ?? [manifest.requestMessageId];+ const requests = requestIds.flatMap((requestId) => messages.filter(({ id }) => id === requestId));+ const request = requests.find(({ id }) => id === manifest.requestMessageId);+ const quotes = messages.filter(+ ({ id }) => !requestIds.includes(id) && requests.some(({ replyToId }) => replyToId === id),+ );const recent = context.filter(- ({ id }) => id !== quoted?.id && id !== request?.id && id !== primaryReply?.id,+ ({ id }) =>+ !requestIds.includes(id) &&+ !quotes.some((quoted) => quoted.id === id) &&+ id !== primaryReply?.id,);const boundary =options.boundary ??createBoundary(- [- ...recent,- ...(quoted ? [quoted] : []),- ...(request ? [request] : []),- ...(primaryReply ? [primaryReply] : []),- ]+ [...recent, ...quotes, ...requests, ...(primaryReply ? [primaryReply] : [])].map(({ content }) => content).concat(opening ?? [], peers, resume?.reason ?? []),);@@ -167,22 +174,33 @@ export const buildChannelPrompt = (truncated ? message.content.slice(0, CONTEXT_EXCERPT_LENGTH) : message.content,);}),- ...(quoted- ? [- block(- 'channel_quote',- attribution(quoted, selfAgentId, quoted.content.length > QUOTE_EXCERPT_LENGTH),- boundary,- quoted.content.slice(0, QUOTE_EXCERPT_LENGTH),- ),- ]- : []),+ ...quotes.map((quoted) =>+ block(+ 'channel_quote',+ attribution(quoted, selfAgentId, quoted.content.length > QUOTE_EXCERPT_LENGTH),+ boundary,+ quoted.content.slice(0, QUOTE_EXCERPT_LENGTH),+ ),+ ),+ ...requests+ .filter((earlier) => earlier !== request)+ .map((earlier) =>+ block(+ 'channel_request',+ { ...attribution(earlier, selfAgentId), to: manifest.self.name },+ boundary,+ earlier.content,+ ),+ ),block('channel_request',{ ...(request && attribution(request, selfAgentId)), to: manifest.self.name },boundary,request?.content ?? '',),+ ...(requests.length > 1+ ? [block('channel_merged', {}, boundary, mergedHint(requests.length))]+ : []),...(primaryReply? [block(diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 8ccc6bd4817..d61cc6e06d9 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -389,9 +389,11 @@ export type ChannelRoutingMode = 'decision' | 'fallback';* - `failed`: ended without a publishable reply, or its execution failed or became unknown.* - `cancelled`: stopped, or it can never run (requester left, environment switched).* - `silent`: a `followup` wake the Agent chose not to answer (`NO_REPLY`). Settled, not failed.+ * - `merged`: queued behind an earlier request from the same person and answered in that run;+ * the run's manifest lists it in `requestMessageIds`.*/export type ChannelJobStatus =- 'cancelled' | 'completed' | 'failed' | 'queued' | 'running' | 'silent';+ 'cancelled' | 'completed' | 'failed' | 'merged' | 'queued' | 'running' | 'silent';/*** Why a job was woken, frozen when it is delivered.@@ -715,7 +717,15 @@ export interface ChannelInputManifest {primaryReplyMessageId?: string;/** The member that triggered this run; its user is the execution identity. */requesterMemberId: string;+ /** The last request this run answers; with a merged batch, the newest of them. */requestMessageId: string;+ /**+ /**+ * Every request this run answers, oldest first, when the requester sent several in a row+ * while the member was busy: their queued jobs settle as `merged` into this one. Absent for+ * a single request.+ */+ requestMessageIds?: string[];/*** Set when the run resumes a failed reply in the same topic (`resumeJob`), so the run gets a* short continuation prompt and the runtime resumes its session.diff --git a/src/features/Channels/jobStatus.test.ts b/src/features/Channels/jobStatus.test.tsindex 0f4b623e6ec..743f4707eed 100644--- a/src/features/Channels/jobStatus.test.ts+++ b/src/features/Channels/jobStatus.test.ts@@ -162,6 +162,13 @@ describe('Channel task tone', () => {];expect(unresolvedFailures(jobs).map((entry) => entry.id)).toEqual(['b-failed']);});+ it('keeps a failed run that requests merged into it are newer than', () => {+ const jobs = [+ job({ id: 'a-merged', memberId: 'a', status: 'merged' }),+ job({ id: 'a-failed', memberId: 'a', status: 'failed' }),+ ];+ expect(unresolvedFailures(jobs).map((entry) => entry.id)).toEqual(['a-failed']);+ });});describe('mainTimelineFailures', () => {diff --git a/src/features/Channels/jobStatus.ts b/src/features/Channels/jobStatus.tsindex 5f293b3e215..4d30a891118 100644--- a/src/features/Channels/jobStatus.ts+++ b/src/features/Channels/jobStatus.ts@@ -50,12 +50,13 @@ export const replyActivityJobs = <T extends ChannelReplyJob>(jobs: T[]) =>/*** Each member's newest job when it failed. A later reply, stop or retry by the same member- * settles the failure, so the header does not stay red forever. Jobs arrive newest first.+ * settles the failure, so the header does not stay red forever. Jobs arrive newest first. A+ * request merged into an earlier run settles with that run, so it settles nothing itself.*/export const unresolvedFailures = <T extends ChannelReplyJob>(jobs: T[]) => {const seen = new Set<string>();return jobs.filter((job) => {- if (seen.has(job.memberId)) return false;+ if (job.status === 'merged' || seen.has(job.memberId)) return false;seen.add(job.memberId);return job.status === 'failed';});