🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): show a failed reply as a card under its Agent, and skip the ack while its usage limit is hit (#23348)
Lobehub Coder1ce7bdcefb28
diff --git a/apps/server/src/services/channel/quotaReset.test.ts b/apps/server/src/services/channel/quotaReset.test.tsnew file mode 100644index 00000000000..0a7d85f4f13--- /dev/null+++ b/apps/server/src/services/channel/quotaReset.test.ts@@ -0,0 +1,132 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { knownQuotaReset } from './quotaReset';++const { executions, quota } = vi.hoisted(() => ({+ executions: { lastSettledReplyOnDevice: vi.fn() },+ quota: { construct: vi.fn(), planDeviceRouting: vi.fn(), resolveDeviceRowId: vi.fn() },+}));+vi.mock('@/database/repositories/channel', () => ({+ ChannelExecutionRepository: class {+ constructor() {+ return executions;+ }+ },+}));+vi.mock('@/server/services/agentQuota', () => ({+ AgentQuotaService: class {+ constructor(...args: unknown[]) {+ quota.construct(...args);+ return quota;+ }+ },+}));++const now = Date.parse('2026-11-18T04:41:00Z');+const resetsAt = Date.parse('2026-11-18T07:00:00Z');+const candidate = {+ agent: { id: 'agt-cook', name: 'Cook', title: null },+ deviceId: 'device-cloud-1',+ memberId: 'member-cook',+ requesterUserId: 'user-lijian',+ workspaceId: 'ws-1',+};++/** A reply whose Claude Code run its 5-hour window refused, as the job and operation store it. */+const refusal = (patch: { resetsAt?: number; status?: string } = {}) => ({+ error: {+ body: {+ agentType: 'claude-code',+ code: 'rate_limit',+ rateLimitInfo: {+ rateLimitType: 'five_hour',+ resetsAt: (patch.resetsAt ?? resetsAt) / 1000,+ status: patch.status ?? 'rejected',+ },+ },+ category: 'quota',+ message: "You've hit your 5-hour limit · resets 3pm (Asia/Shanghai)",+ type: 'AgentRuntimeError',+ },+ status: 'failed',+});++describe('knownQuotaReset', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ quota.resolveDeviceRowId.mockResolvedValue('device-row-1');+ quota.planDeviceRouting.mockResolvedValue(null);+ });++ it('returns the reset of a window that refused the last reply on the picked device', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValue(refusal());++ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBe(resetsAt);+ expect(executions.lastSettledReplyOnDevice).toHaveBeenCalledWith('channel', {+ deviceId: 'device-cloud-1',+ memberId: 'member-cook',+ since: new Date(now - 8 * 24 * 60 * 60 * 1000),+ });+ // The login is resolved the way the device dispatch resolves it, as the requester.+ expect(quota.construct).toHaveBeenCalledWith({}, 'user-lijian', 'ws-1');+ expect(quota.planDeviceRouting).toHaveBeenCalledWith('agt-cook', {+ deviceId: 'device-row-1',+ provider: 'claude-code',+ });+ });++ it('assumes nothing when no device is picked in the Channel, since only the claim resolves it', async () => {+ await expect(+ knownQuotaReset({} as never, 'channel', { ...candidate, deviceId: undefined }, now),+ ).resolves.toBeUndefined();+ expect(executions.lastSettledReplyOnDevice).not.toHaveBeenCalled();+ });++ it('says nothing when the Agent balances several logins on the device', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValue(refusal());+ quota.planDeviceRouting.mockResolvedValue({+ candidates: [{ externalAccountId: 'a' }, { externalAccountId: 'b' }],+ mode: 'balanced',+ });++ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();+ });++ it('keeps the refusal when the device runs one login, pinned or default', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValue(refusal());+ quota.planDeviceRouting.mockResolvedValue({+ candidates: [{ externalAccountId: 'a' }],+ mode: 'pinned',+ });++ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBe(resetsAt);+ });++ it('says nothing once the window has reopened', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValue(refusal({ resetsAt: now - 60_000 }));++ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();+ });++ it('says nothing after a reply that finished, or one that failed for another reason', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValueOnce({ error: null, status: 'completed' });+ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();++ executions.lastSettledReplyOnDevice.mockResolvedValueOnce({+ error: { message: 'Device is offline', type: 'DeviceUnreachable' },+ status: 'failed',+ });+ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();++ executions.lastSettledReplyOnDevice.mockResolvedValueOnce(undefined);+ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();+ expect(quota.planDeviceRouting).not.toHaveBeenCalled();+ });++ it('ignores window details stamped on a run the window allowed', async () => {+ executions.lastSettledReplyOnDevice.mockResolvedValue(refusal({ status: 'allowed' }));++ await expect(knownQuotaReset({} as never, 'channel', candidate, now)).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/channel/quotaReset.ts b/apps/server/src/services/channel/quotaReset.tsnew file mode 100644index 00000000000..fe2f9108bde--- /dev/null+++ b/apps/server/src/services/channel/quotaReset.ts@@ -0,0 +1,69 @@+import type { LobeChatDatabase } from '@lobechat/database';++import type { ChannelOpeningCandidate } from '@/database/repositories/channel';+import { ChannelExecutionRepository } from '@/database/repositories/channel';+import { AgentQuotaService } from '@/server/services/agentQuota';+import { classifyRunFailure } from '@/server/services/goal/recoveryPolicy';++/** The longest usage window a CLI reports (weekly), with a day to spare. */+const LOOKBACK_MS = 8 * 24 * 60 * 60 * 1000;++type QuotaCandidate = Pick<+ ChannelOpeningCandidate,+ 'agent' | 'deviceId' | 'memberId' | 'requesterUserId' | 'workspaceId'+>;++/**+ * Whether the run may land on one of several Claude Code logins: the Agent balances a pool on+ * this device, so a refusal of one login says nothing about the next run. Resolved the way the+ * device dispatch resolves it, as the requester.+ */+const balancesLogins = async (+ db: LobeChatDatabase,+ candidate: QuotaCandidate,+ deviceId: string,+) => {+ const quota = new AgentQuotaService(+ db,+ candidate.requesterUserId,+ candidate.workspaceId ?? undefined,+ );+ const routing = await quota.planDeviceRouting(candidate.agent.id, {+ deviceId: await quota.resolveDeviceRowId(deviceId),+ provider: 'claude-code',+ });+ return (routing?.candidates.length ?? 0) > 1;+};++/**+ * When the usage window that refused the Agent's last reply on its device reopens, if it is+ * still closed; undefined otherwise.+ *+ * A usage window belongs to the CLI login that runs the reply, so the refusal only says+ * something about this run when both run on the same login. Before the claim, that is known+ * only for a device picked in the Channel: every reply of the member runs there, for whoever+ * asked. On that device the member's newest finished reply decides, unless the Agent balances+ * several logins there. Without a picked device, only the claim resolves the device (the+ * requester's own setting, a pinned topic), so nothing is assumed.+ */+export const knownQuotaReset = async (+ db: LobeChatDatabase,+ channelId: string,+ candidate: QuotaCandidate,+ now = Date.now(),+): Promise<number | undefined> => {+ const { deviceId } = candidate;+ if (!deviceId) return;++ const latest = await new ChannelExecutionRepository(db).lastSettledReplyOnDevice(channelId, {+ deviceId,+ memberId: candidate.memberId,+ since: new Date(now - LOOKBACK_MS),+ });+ if (latest?.status !== 'failed') return;++ const failure = classifyRunFailure(latest.error);+ if (failure.kind !== 'quota_reset' || !failure.resetsAt || failure.resetsAt <= now) return;+ if (await balancesLogins(db, candidate, deviceId)) return;+ return failure.resetsAt;+};diff --git a/apps/server/src/services/channel/replyOpening.test.ts b/apps/server/src/services/channel/replyOpening.test.tsindex b0ac762a2bb..2a8360927eb 100644--- a/apps/server/src/services/channel/replyOpening.test.ts+++ b/apps/server/src/services/channel/replyOpening.test.ts@@ -17,6 +17,8 @@ vi.mock('./opener', () => ({CHANNEL_REPLY_OPENER_TIMEOUT_MS: 5000,createChannelReplyOpener: vi.fn(),}));+// Unknown by default: the Agent's last run was not refused by a usage window.+vi.mock('./quotaReset', () => ({ knownQuotaReset: vi.fn() }));const candidate = {addressed: true,@@ -180,6 +182,35 @@ describe('openChannelReply', () => {});});+ it('does not acknowledge when the Agent’s usage window is known to be closed', async () => {+ const opener = vi.fn();+ const quotaReset = vi.fn().mockResolvedValue(Date.parse('2026-11-18T07:00:00Z'));++ await openChannelReply({} as never, 'channel', 'job', {+ createOpener: () => opener,+ quotaReset,+ });++ expect(quotaReset).toHaveBeenCalledWith(candidate);+ expect(opener).not.toHaveBeenCalled();+ // Opened with nothing, so the run starts in place and its refusal is the reply's outcome.+ expect(executions.open).toHaveBeenCalledWith('channel', 'job', {});+ });++ it('acknowledges as usual when the usage check fails', async () => {+ const opener = vi.fn().mockResolvedValue({ ack: 'On it.', placement: 'channel' });++ await openChannelReply({} as never, 'channel', 'job', {+ createOpener: () => opener,+ quotaReset: vi.fn().mockRejectedValue(new Error('db down')),+ });++ expect(executions.open).toHaveBeenCalledWith('channel', 'job', {+ ack: 'On it.',+ threadTitle: undefined,+ });+ });+it('skips a job with nothing to open and never throws', async () => {const opener = vi.fn();executions.openingCandidate.mockResolvedValueOnce(undefined);diff --git a/apps/server/src/services/channel/replyOpening.ts b/apps/server/src/services/channel/replyOpening.tsindex 02ad0a67092..cd4366b36de 100644--- a/apps/server/src/services/channel/replyOpening.ts+++ b/apps/server/src/services/channel/replyOpening.ts@@ -8,18 +8,35 @@ import { ChannelExecutionRepository } from '@/database/repositories/channel';import type { ChannelReplyOpener } from './opener';import { CHANNEL_REPLY_OPENER_TIMEOUT_MS, createChannelReplyOpener } from './opener';+import { knownQuotaReset } from './quotaReset';const log = debug('lobe-server:channel:reply-opening');export interface OpenChannelReplyDeps {/** Builds the opener for a candidate; defaults to the Channel's, run as the requester. */createOpener?: (candidate: ChannelOpeningCandidate) => ChannelReplyOpener;+ /** When the Agent's usage window reopens, if a known one is still closed; see `knownQuotaReset`. */+ quotaReset?: (candidate: ChannelOpeningCandidate) => Promise<number | undefined>;timeoutMs?: number;}/** How much of a Thread's root and latest message the opener reads. */const THREAD_EXCERPT_LENGTH = 160;+/** A failed check is no reason to skip the acknowledgement. */+const closedQuotaWindow = async (+ db: LobeChatDatabase,+ channelId: string,+ candidate: ChannelOpeningCandidate,+ deps: OpenChannelReplyDeps,+) => {+ try {+ return await (deps.quotaReset ?? ((entry) => knownQuotaReset(db, channelId, entry)))(candidate);+ } catch (error) {+ log('quota check failed, opening as usual: %O', error);+ }+};+const describe = (message: ChannelContextMessage, agentId: string) =>`${message.author.type === 'agent' && message.author.id === agentId ? 'Assistant' : message.author.name}: ${message.content}`;@@ -94,7 +111,9 @@ const decide = async (* job, before the claim, so the run's topic, branch and worktree follow the Thread.** Never throws. A failed or slow opener is recorded as an opening that changed nothing, and the- * reply starts where it was asked.+ * reply starts where it was asked. So is a job whose Agent's last reply on the same CLI login was+ * refused by a usage window that has not reopened yet: the opener is not asked, so no+ * acknowledgement precedes the refusal.*/export const openChannelReply = async (db: LobeChatDatabase,@@ -107,6 +126,17 @@ export const openChannelReply = async (const candidate = await executions.openingCandidate(channelId, jobId);if (!candidate) return;+ // The Agent's last reply on the same login was refused by a usage window that is still+ // closed: an acknowledgement would promise work the run cannot do. It opens with nothing and+ // starts where it was asked, so the refusal shows as its failure instead; a window that+ // reopened early still answers.+ const resetsAt = await closedQuotaWindow(db, channelId, candidate, deps);+ if (resetsAt) {+ const opened = await executions.open(channelId, jobId, {});+ log('job %s opened=%s without ack: quota closed until %s', jobId, opened, resetsAt);+ return;+ }+const startedAt = Date.now();let opening: Awaited<ReturnType<ChannelReplyOpener>> | undefined;try {diff --git a/locales/ar/channel.json b/locales/ar/channel.jsonindex 134bb905578..48d588ccdda 100644--- a/locales/ar/channel.json+++ b/locales/ar/channel.json@@ -91,7 +91,6 @@"events.youInvited": "لقد دعوت {{names}} إلى القناة","events.youInvitedMembers": "لقد دعوت <members/> إلى القناة","failure.locate": "عرض الرسالة",- "failure.messageLabel": "فشل الرد: {{names}}","failure.title": "الردود الفاشلة · {{count}}","followers": "الردود من: {{names}}","invite.directHint": "الدعوة هنا تبدأ قناة جديدة مع {{name}} والأعضاء الذين تختارهم. تبقى هذه المحادثة مع {{name}} كما هي.",diff --git a/locales/bg-BG/channel.json b/locales/bg-BG/channel.jsonindex 4d5adb4fdd4..5da1afe937b 100644--- a/locales/bg-BG/channel.json+++ b/locales/bg-BG/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Вие поканихте {{names}} в канала","events.youInvitedMembers": "Вие поканихте <members/> в канала","failure.locate": "Показване на съобщението",- "failure.messageLabel": "Отговорът не успя: {{names}}","failure.title": "Неуспешни отговори · {{count}}","followers": "Отговори от: {{names}}","invite.directHint": "Поканването тук започва нов канал с {{name}} и избраните от вас членове. Този разговор с {{name}} остава както е.",diff --git a/locales/de-DE/channel.json b/locales/de-DE/channel.jsonindex cb62e756d1b..2ae8b4e5937 100644--- a/locales/de-DE/channel.json+++ b/locales/de-DE/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Sie haben {{names}} in den Kanal eingeladen","events.youInvitedMembers": "Sie haben <members/> in den Kanal eingeladen","failure.locate": "Nachricht anzeigen",- "failure.messageLabel": "Antwort fehlgeschlagen: {{names}}","failure.title": "Fehlgeschlagene Antworten · {{count}}","followers": "Antworten von: {{names}}","invite.directHint": "Wenn Sie hier einladen, wird ein neuer Kanal mit {{name}} und den von Ihnen ausgewählten Mitgliedern gestartet. Dieses Gespräch mit {{name}} bleibt unverändert.",diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 2e7dec55694..7f817eec3aa 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -109,7 +109,6 @@"events.youInvited": "You invited {{names}} to the channel","events.youInvitedMembers": "You invited <members/> to the channel","failure.locate": "Show message",- "failure.messageLabel": "Reply failed: {{names}}","failure.title": "Failed replies · {{count}}","followers": "Replies from: {{names}}","invite.directHint": "Inviting here starts a new channel with {{name}} and the members you choose. This conversation with {{name}} stays as it is.",diff --git a/locales/es-ES/channel.json b/locales/es-ES/channel.jsonindex 38c0e5490f1..45b6c22ce34 100644--- a/locales/es-ES/channel.json+++ b/locales/es-ES/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Invitaste a {{names}} al canal","events.youInvitedMembers": "Invitaste a <members/> al canal","failure.locate": "Mostrar mensaje",- "failure.messageLabel": "Respuesta fallida: {{names}}","failure.title": "Respuestas fallidas · {{count}}","followers": "Respuestas de: {{names}}","invite.directHint": "Invitar aquí inicia un canal nuevo con {{name}} y los miembros que elijas. Esta conversación con {{name}} se mantiene tal como está.",diff --git a/locales/fa-IR/channel.json b/locales/fa-IR/channel.jsonindex 42d8534e5ed..e8e476601a5 100644--- a/locales/fa-IR/channel.json+++ b/locales/fa-IR/channel.json@@ -91,7 +91,6 @@"events.youInvited": "شما {{names}} را به کانال دعوت کردید","events.youInvitedMembers": "شما <members/> را به کانال دعوت کردید","failure.locate": "نمایش پیام",- "failure.messageLabel": "پاسخ ناموفق: {{names}}","failure.title": "پاسخهای ناموفق · {{count}}","followers": "پاسخها از: {{names}}","invite.directHint": "دعوت در اینجا یک کانال جدید با {{name}} و اعضایی که انتخاب میکنید ایجاد میکند. این گفتوگو با {{name}} به همین شکل باقی میماند.",diff --git a/locales/fr-FR/channel.json b/locales/fr-FR/channel.jsonindex dec89c58f6a..42fa13c6325 100644--- a/locales/fr-FR/channel.json+++ b/locales/fr-FR/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Vous avez invité {{names}} au canal","events.youInvitedMembers": "Vous avez invité <members/> au canal","failure.locate": "Afficher le message",- "failure.messageLabel": "Échec de la réponse : {{names}}","failure.title": "Réponses échouées · {{count}}","followers": "Réponses de : {{names}}","invite.directHint": "Inviter ici démarre un nouveau canal avec {{name}} et les membres que vous choisissez. Cette conversation avec {{name}} reste telle quelle.",diff --git a/locales/it-IT/channel.json b/locales/it-IT/channel.jsonindex 90bf74241ed..ddbf88f60d2 100644--- a/locales/it-IT/channel.json+++ b/locales/it-IT/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Hai invitato {{names}} al canale","events.youInvitedMembers": "Hai invitato <members/> al canale","failure.locate": "Mostra messaggio",- "failure.messageLabel": "Risposta fallita: {{names}}","failure.title": "Risposte fallite · {{count}}","followers": "Risposte da: {{names}}","invite.directHint": "Invitare qui avvia un nuovo canale con {{name}} e i membri che scegli. Questa conversazione con {{name}} rimane invariata.",diff --git a/locales/ja-JP/channel.json b/locales/ja-JP/channel.jsonindex 43d0af1e7fc..10a46c51536 100644--- a/locales/ja-JP/channel.json+++ b/locales/ja-JP/channel.json@@ -91,7 +91,6 @@"events.youInvited": "あなたが {{names}} をチャンネルに招待しました","events.youInvitedMembers": "あなたが <members/> をチャンネルに招待しました","failure.locate": "メッセージを表示",- "failure.messageLabel": "返信失敗: {{names}}","failure.title": "失敗した返信 · {{count}}","followers": "返信元: {{names}}","invite.directHint": "ここで招待すると、{{name}} と選択したメンバーとの新しいチャンネルが始まります。{{name}} とのこの会話はそのまま残ります。",diff --git a/locales/ko-KR/channel.json b/locales/ko-KR/channel.jsonindex f2a55a3d8a9..6a853a373e5 100644--- a/locales/ko-KR/channel.json+++ b/locales/ko-KR/channel.json@@ -91,7 +91,6 @@"events.youInvited": "당신이 {{names}}을(를) 채널에 초대했습니다","events.youInvitedMembers": "당신이 <members/>을(를) 채널에 초대했습니다","failure.locate": "메시지 표시",- "failure.messageLabel": "응답 실패: {{names}}","failure.title": "실패한 응답 · {{count}}","followers": "응답자: {{names}}","invite.directHint": "여기에서 초대하면 {{name}} 및 선택한 멤버와 함께 새 채널이 시작됩니다. {{name}}과의 이 대화는 그대로 유지됩니다.",diff --git a/locales/nl-NL/channel.json b/locales/nl-NL/channel.jsonindex f6d4a487bcf..114dbe9d89f 100644--- a/locales/nl-NL/channel.json+++ b/locales/nl-NL/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Je hebt {{names}} uitgenodigd voor het kanaal","events.youInvitedMembers": "Je hebt <members/> uitgenodigd voor het kanaal","failure.locate": "Toon bericht",- "failure.messageLabel": "Reactie mislukt: {{names}}","failure.title": "Mislukte reacties · {{count}}","followers": "Reacties van: {{names}}","invite.directHint": "Als je hier uitnodigt, wordt een nieuw kanaal gestart met {{name}} en de leden die je kiest. Dit gesprek met {{name}} blijft zoals het is.",diff --git a/locales/pl-PL/channel.json b/locales/pl-PL/channel.jsonindex f23ca76aeb2..611d32b0528 100644--- a/locales/pl-PL/channel.json+++ b/locales/pl-PL/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Zaprosiłeś {{names}} do kanału","events.youInvitedMembers": "Zaprosiłeś <members/> do kanału","failure.locate": "Pokaż wiadomość",- "failure.messageLabel": "Odpowiedź nie powiodła się: {{names}}","failure.title": "Nieudane odpowiedzi · {{count}}","followers": "Odpowiedzi od: {{names}}","invite.directHint": "Zaproszenie tutaj rozpoczyna nowy kanał z {{name}} i wybranymi przez Ciebie członkami. Ta rozmowa z {{name}} pozostaje bez zmian.",diff --git a/locales/pt-BR/channel.json b/locales/pt-BR/channel.jsonindex c24670fce80..60cfb429863 100644--- a/locales/pt-BR/channel.json+++ b/locales/pt-BR/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Você convidou {{names}} para o canal","events.youInvitedMembers": "Você convidou <members/> para o canal","failure.locate": "Mostrar mensagem",- "failure.messageLabel": "Falha na resposta: {{names}}","failure.title": "Respostas com falha · {{count}}","followers": "Respostas de: {{names}}","invite.directHint": "Convidar aqui inicia um novo canal com {{name}} e os membros que você escolher. Esta conversa com {{name}} permanece como está.",diff --git a/locales/ru-RU/channel.json b/locales/ru-RU/channel.jsonindex d697360cdf4..716ed3ce059 100644--- a/locales/ru-RU/channel.json+++ b/locales/ru-RU/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Вы пригласили {{names}} в канал","events.youInvitedMembers": "Вы пригласили <members/> в канал","failure.locate": "Показать сообщение",- "failure.messageLabel": "Ответ не удался: {{names}}","failure.title": "Неудачные ответы · {{count}}","followers": "Ответы от: {{names}}","invite.directHint": "Приглашение здесь создаст новый канал с {{name}} и выбранными вами участниками. Эта беседа с {{name}} останется без изменений.",diff --git a/locales/tr-TR/channel.json b/locales/tr-TR/channel.jsonindex c2724e37cfe..ffa9b84c235 100644--- a/locales/tr-TR/channel.json+++ b/locales/tr-TR/channel.json@@ -91,7 +91,6 @@"events.youInvited": "{{names}} kişisini kanala davet ettiniz","events.youInvitedMembers": "<members/> kişisini kanala davet ettiniz","failure.locate": "Mesajı göster",- "failure.messageLabel": "Yanıt başarısız: {{names}}","failure.title": "Başarısız yanıtlar · {{count}}","followers": "Yanıtlayanlar: {{names}}","invite.directHint": "Buradan davet etmek, {{name}} ve seçtiğiniz üyelerle yeni bir kanal başlatır. {{name}} ile bu sohbet olduğu gibi kalır.",diff --git a/locales/vi-VN/channel.json b/locales/vi-VN/channel.jsonindex cf692c9e1dd..46de6929b54 100644--- a/locales/vi-VN/channel.json+++ b/locales/vi-VN/channel.json@@ -91,7 +91,6 @@"events.youInvited": "Bạn đã mời {{names}} vào kênh","events.youInvitedMembers": "Bạn đã mời <members/> vào kênh","failure.locate": "Hiển thị tin nhắn",- "failure.messageLabel": "Trả lời thất bại: {{names}}","failure.title": "Các trả lời thất bại · {{count}}","followers": "Trả lời từ: {{names}}","invite.directHint": "Mời tại đây sẽ bắt đầu một kênh mới với {{name}} và các thành viên bạn chọn. Cuộc trò chuyện này với {{name}} vẫn giữ nguyên.",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex fd8ce6b65fa..b5c102212ad 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -109,7 +109,6 @@"events.youInvited": "你邀请了 {{names}} 加入频道","events.youInvitedMembers": "你邀请了 <members/> 加入频道","failure.locate": "定位到消息",- "failure.messageLabel": "回复失败:{{names}}","failure.title": "回复失败 · {{count}}","followers": "参与回复:{{names}}","invite.directHint": "邀请后会新建一个频道,包含 {{name}} 和你选择的成员;你和 {{name}} 的这个对话保持不变。",diff --git a/locales/zh-TW/channel.json b/locales/zh-TW/channel.jsonindex 69c2319c3c6..7e644fa3cae 100644--- a/locales/zh-TW/channel.json+++ b/locales/zh-TW/channel.json@@ -91,7 +91,6 @@"events.youInvited": "您邀請了 {{names}} 加入頻道","events.youInvitedMembers": "您邀請了 <members/> 加入頻道","failure.locate": "顯示訊息",- "failure.messageLabel": "回覆失敗:{{names}}","failure.title": "回覆失敗 · {{count}}","followers": "回覆來自:{{names}}","invite.directHint": "在此邀請將建立一個包含 {{name}} 和您所選成員的新頻道。您與 {{name}} 的此對話保持不變。",diff --git a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts b/packages/database/src/repositories/channel/__tests__/replyOpening.test.tsindex 5e8f72414fb..b7e20deeac4 100644--- a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts+++ b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts@@ -3,7 +3,13 @@ import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { agents, channelJobs, channelMessages, channelThreads } from '../../../schemas';+import {+ agents,+ channelJobs,+ channelMembers,+ channelMessages,+ channelThreads,+} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { ChannelExecutionRepository, ChannelRepository } from '..';import { readManifestMessages } from '../manifest';@@ -76,6 +82,88 @@ describe('Channel reply opening', () => {expect((await jobById(db, job.id)).threadId).toBeNull();});+ it('names the acknowledgement on the job, so a failed run shows under it', async () => {+ const { channel, job } = await mentionAgent();+ await execution.open(channel.id, job.id, { ack: 'Got it, checking CI.' });+ const claimed = (await execution.claim(channel.id, job.id, lease))!;+ await execution.fail(channel.id, claimed.job.id, { message: "You've hit your 5-hour limit" });++ const ack = (await messagesOf(channel.id)).find((row) => row.routingStatus === 'reply');+ const repository = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ const { jobs } = await repository.detail(channel.id);+ expect(jobs).toEqual([+ expect.objectContaining({+ errorMessage: "You've hit your 5-hour limit",+ id: job.id,+ openingMessageId: ack!.id,+ status: 'failed',+ }),+ ]);+ });++ it('names the device picked for the Agent, and finds its newest finished reply on it', async () => {+ const { agent, asMember, channel, job } = await mentionAgent();+ const claimed = (await execution.claim(channel.id, job.id, lease))!;+ await execution.fail(channel.id, claimed.job.id, { message: "You've hit your 5-hour limit" });+ // The member runs on a device picked in the Channel; the claim records it on the job.+ await db.update(channelJobs).set({ deviceId: 'device-a' }).where(eq(channelJobs.id, job.id));+ await db+ .update(channelMembers)+ .set({ config: { deviceId: 'device-a' } })+ .where(eq(channelMembers.id, agent.id));+ const next = await asMember.send(channel.id, {+ content: 'Can you retry now?',+ mentions: [agent.id],+ requestKey: 'req-retry',+ routing: 'decision',+ });+ const [nextJob] = await jobsOf(db, next.id);+ const since = new Date(Date.now() - 60_000);++ expect(await execution.openingCandidate(channel.id, nextJob.id)).toMatchObject({+ deviceId: 'device-a',+ memberId: agent.id,+ });+ // The queued reply is not finished yet: the failed one is the newest on the device.+ expect(+ await execution.lastSettledReplyOnDevice(channel.id, {+ deviceId: 'device-a',+ memberId: agent.id,+ since,+ }),+ ).toMatchObject({ error: { message: "You've hit your 5-hour limit" }, status: 'failed' });+ // Another device has no history of its own.+ expect(+ await execution.lastSettledReplyOnDevice(channel.id, {+ deviceId: 'device-b',+ memberId: agent.id,+ since,+ }),+ ).toBeUndefined();++ // A newer reply that finished on the device takes over.+ await db+ .update(channelJobs)+ .set({ deviceId: 'device-a', status: 'completed' })+ .where(eq(channelJobs.id, nextJob.id));+ expect(+ await execution.lastSettledReplyOnDevice(channel.id, {+ deviceId: 'device-a',+ memberId: agent.id,+ since,+ }),+ ).toMatchObject({ status: 'completed' });+ });++ it('names no acknowledgement on a job that opened without one', async () => {+ const { channel, job } = await mentionAgent();+ await execution.open(channel.id, job.id, {});++ const repository = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ const { jobs } = await repository.detail(channel.id);+ expect(jobs).toEqual([expect.objectContaining({ id: job.id, openingMessageId: null })]);+ });+it('in a group with several people, opens the Thread under the request and acknowledges inside it', async () => {const { channel, job, member, message } = await mentionAgent();diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex 9852d5b78fe..53cf8d0bb9e 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -23,7 +23,13 @@ import { activeMembers, appendMessage, deliver } from './delivery';import { ChannelError } from './error';import { countManifestMessages, readManifestMessages } from './manifest';import type { ChannelOpeningDecision } from './opening';-import { applyOpening, findCoAddressed, findOpeningCandidate, findOpeningReply } from './opening';+import {+ applyOpening,+ findCoAddressed,+ findLastSettledReplyOnDevice,+ findOpeningCandidate,+ findOpeningReply,+} from './opening';import { findTextMentions, MAX_REPLY_MENTION_HOPS, replyMentionHops } from './replyMentions';import type { ChannelRoutingDecision } from './routing';import { resolveRouting } from './routing';@@ -406,6 +412,12 @@ export class ChannelExecutionRepository {openingCandidate = (channelId: string, jobId: string) =>findOpeningCandidate(this.db, channelId, jobId);+ /** A member's newest finished reply on a device. See {@link findLastSettledReplyOnDevice}. */+ lastSettledReplyOnDevice = (+ channelId: string,+ params: Parameters<typeof findLastSettledReplyOnDevice>[2],+ ) => findLastSettledReplyOnDevice(this.db, channelId, params);+/** Opens a queued job's reply once. See {@link applyOpening}. */open = (channelId: string, jobId: string, decision: ChannelOpeningDecision) =>applyOpening(this.db, channelId, jobId, decision);diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.tsindex acdd93f9a76..88aa7a23bcb 100644--- a/packages/database/src/repositories/channel/opening.ts+++ b/packages/database/src/repositories/channel/opening.ts@@ -1,9 +1,10 @@import type { ChannelContextMessage } from '@lobechat/types';-import { and, desc, eq, inArray, isNull, lt, ne } from 'drizzle-orm';+import { and, desc, eq, gte, inArray, isNull, lt, ne } from 'drizzle-orm';import pMap from 'p-map';import type { ChannelJobItem } from '../../schemas';import {+ agentOperations,agents,channelAudit,channelJobs,@@ -78,6 +79,13 @@ export interface ChannelOpeningCandidate {canOpenThread: boolean;/** The other Agents the request asked to answer; they share one Thread with this reply. */coAddressed: ChannelCoAddressedAgent[];+ /**+ * The device picked for the Agent in this Channel. Every reply of the member runs there, so+ * it names the run's target before the claim; without one only the claim resolves it.+ */+ deviceId?: string;+ /** The Agent's membership in this Channel, which its replies run as. */+ memberId: string;/** Public messages just before the request, oldest first. */recent: ChannelContextMessage[];request: ChannelContextMessage;@@ -180,6 +188,7 @@ export const findOpeningCandidate = async (agentId: channelMembers.agentId,agentName: agents.name,agentTitle: agentTitleSql(),+ memberConfig: channelMembers.config,}).from(channelJobs).innerJoin(channelMembers, eq(channelMembers.id, channelJobs.memberId))@@ -241,6 +250,8 @@ export const findOpeningCandidate = async (agent: { id: row.agentId, name: row.agentName, title: row.agentTitle },canOpenThread: !job.threadId,coAddressed,+ ...(row.memberConfig?.deviceId && { deviceId: row.memberConfig.deviceId }),+ memberId: job.memberId,recent: messages.filter((message) => message.id !== job.messageId),request: requestMessage,requesterUserId: requester.userId,@@ -641,3 +652,30 @@ export const findOpeningReply = async (.limit(1);return message;};++/**+ * The newest reply of `memberId` on `deviceId` since `since` that finished: answered, chose+ * silence, or failed, with its run's error. A stopped reply says nothing about the device.+ */+export const findLastSettledReplyOnDevice = async (+ db: LobeChatDatabase,+ channelId: string,+ { deviceId, memberId, since }: { deviceId: string; memberId: string; since: Date },+) => {+ const [row] = await db+ .select({ error: agentOperations.error, status: channelJobs.status })+ .from(channelJobs)+ .leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.memberId, memberId),+ eq(channelJobs.deviceId, deviceId),+ inArray(channelJobs.status, ['completed', 'failed', 'silent']),+ gte(channelJobs.createdAt, since),+ ),+ )+ .orderBy(desc(channelJobs.createdAt))+ .limit(1);+ return row;+};diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 8a7ccf918ba..d35b1b09dad 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -279,6 +279,10 @@ const publicJobColumns = {${channelJobs.executionConfig}->'agencyConfig'->>'boundDeviceId')`,writerHeld: channelJobs.writerHeld,+ // The acknowledgement posted before the run (`openingRequestKey`), so a failure shows under it.+ openingMessageId: sql<string | null>`(SELECT ${channelMessages.id} FROM ${channelMessages}+ WHERE ${channelMessages.channelId} = ${channelJobs.channelId}+ AND ${channelMessages.requestKey} = 'opening:' || ${channelJobs.id}::text)`,topicId: channelJobs.topicId,// A trashed topic has no owner here, so its link goes with it.topicOwnerId: sql<string | null>`CASE WHEN ${notTrashed(topics.isDeleted)}diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 9a6cf6493a8..f761efb50b7 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -213,7 +213,6 @@ export default {'events.joined': '{{names}} joined the channel','events.youInvited': 'You invited {{names}} to the channel','failure.locate': 'Show message',- 'failure.messageLabel': 'Reply failed: {{names}}','failure.title': 'Failed replies · {{count}}','nameOptional': 'Channel name (optional)','rename': 'Rename channel',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex c5714556448..fbb283af4ca 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -893,6 +893,8 @@ export interface ChannelPublicJob {id: string;memberId: string;messageId: string;+ /** The acknowledgement the reply posted before its run, so its outcome can show under it. */+ openingMessageId?: string | null;publicationRevoked: boolean;status: ChannelJobStatus;threadId: string | null;diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex 876f64c5d5f..44f5394fe67 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -20,7 +20,7 @@ import { ArchivedNotice } from './ArchivedNotice';import { visibleChannelDetail } from './channelAccess';import { ChannelMessage, ThreadRootMessage } from './ChannelMessage';import { Composer } from './Composer';-import { hasReplyActivity } from './jobStatus';+import { hasReplyActivity, replyFailurePlacement } from './jobStatus';import { JoinEventLine } from './JoinEventLine';import { channelJoinEvents, channelTimeline } from './joinEvents';import { isCurrentUserMember } from './memberName';@@ -29,6 +29,7 @@ import { presentOutgoingMessage, timelineTail } from './outgoing';import { OutgoingStatus } from './OutgoingStatus';import { ReadOnlyNotice } from './ReadOnlyNotice';import { ReplyActivity } from './ReplyActivity';+import { ReplyFailureRow } from './ReplyFailure';import type { ReplyTopic } from './ReplyTopicPanel';import { styles } from './styles';import type { ChannelThreadDraft } from './threadDraft';@@ -139,6 +140,19 @@ const Timeline = ({!detail.hasMore && before === undefined,): [];+ const failures = replyFailurePlacement(+ detail?.jobs ?? [],+ new Set([+ ...timeline.flatMap((item) => (item.kind === 'message' ? [item.message.id] : [])),+ ...(detail?.rootMessage ? [detail.rootMessage.id] : []),+ ]),+ threadId,+ );+ const failureRows = (messageId: string) =>+ detail &&+ failures.afterMessage+ .get(messageId)+ ?.map((job) => <ReplyFailureRow detail={detail} job={job} key={job.id} />);return (<Flexbox@@ -200,16 +214,18 @@ const Timeline = ({</Flexbox>)}{detail.rootMessage && (- <ThreadRootMessage- detail={detail}- highlighted={highlighted === detail.rootMessage.id}- root={detail.rootMessage}- onReply={- channelArchived || readOnly || thread?.status === 'archived'- ? undefined- : selectReply- }- />+ <>+ <ThreadRootMessage+ detail={detail}+ failures={failures.underMessage.get(detail.rootMessage.id)}+ highlighted={highlighted === detail.rootMessage.id}+ root={detail.rootMessage}+ onReply={+ channelArchived || readOnly || thread?.status === 'archived' ? undefined : selectReply+ }+ />+ {failureRows(detail.rootMessage.id)}+ </>)}{/* A new direct conversation starts blank, like an IM chat. */}{!timeline.length &&@@ -218,59 +234,63 @@ const Timeline = ({) : direct ? null : (<Empty icon={MessageSquare} title={t('conversationEmpty')} />))}- {presentChannelTimeline(timeline).map(({ item, date, startsDay, continuation }) => (- <Fragment key={item.kind === 'event' ? item.event.id : item.message.id}>- {startsDay && (- <div- aria-label={timeFormats.date.format(date)}- role="separator"- {...stylex.props(styles.dateDivider)}- >- <time dateTime={date.toISOString()} title={timeFormats.date.format(date)}>- {timeFormats.date.format(date)}- </time>- </div>- )}- {item.kind === 'event' ? (- <JoinEventLine event={item.event} />- ) : outgoingById.has(item.message.id) ? (- <ChannelMessage- continuation={continuation}- message={item.message}- pending={outgoingById.get(item.message.id)!.status === 'sending'}- threadId={threadId}- delivery={- <OutgoingStatus- message={outgoingById.get(item.message.id)!}- onRetry={(failed) => followSent(channelActions.retrySend(failed))}- />- }- detail={{- ...detail,- attachments: outgoingById.get(item.message.id)!.attachments,- }}- onJumpToMessage={jumpToMessage}- />- ) : (- <ChannelMessage- continuation={continuation}- detail={detail}- highlighted={highlighted === item.message.id}- message={item.message}- threadId={threadId}- onJumpToMessage={jumpToMessage}- onOpenThread={onOpenThread}- onOpenTopic={onOpenTopic}- onStartThread={channelArchived || readOnly ? undefined : onStartThread}- onReply={- channelArchived || readOnly || thread?.status === 'archived'- ? undefined- : selectReply- }- />- )}- </Fragment>- ))}+ {presentChannelTimeline(timeline, new Set(failures.afterMessage.keys())).map(+ ({ item, date, startsDay, continuation }) => (+ <Fragment key={item.kind === 'event' ? item.event.id : item.message.id}>+ {startsDay && (+ <div+ aria-label={timeFormats.date.format(date)}+ role="separator"+ {...stylex.props(styles.dateDivider)}+ >+ <time dateTime={date.toISOString()} title={timeFormats.date.format(date)}>+ {timeFormats.date.format(date)}+ </time>+ </div>+ )}+ {item.kind === 'event' ? (+ <JoinEventLine event={item.event} />+ ) : outgoingById.has(item.message.id) ? (+ <ChannelMessage+ continuation={continuation}+ message={item.message}+ pending={outgoingById.get(item.message.id)!.status === 'sending'}+ threadId={threadId}+ delivery={+ <OutgoingStatus+ message={outgoingById.get(item.message.id)!}+ onRetry={(failed) => followSent(channelActions.retrySend(failed))}+ />+ }+ detail={{+ ...detail,+ attachments: outgoingById.get(item.message.id)!.attachments,+ }}+ onJumpToMessage={jumpToMessage}+ />+ ) : (+ <ChannelMessage+ continuation={continuation}+ detail={detail}+ failures={failures.underMessage.get(item.message.id)}+ highlighted={highlighted === item.message.id}+ message={item.message}+ threadId={threadId}+ onJumpToMessage={jumpToMessage}+ onOpenThread={onOpenThread}+ onOpenTopic={onOpenTopic}+ onStartThread={channelArchived || readOnly ? undefined : onStartThread}+ onReply={+ channelArchived || readOnly || thread?.status === 'archived'+ ? undefined+ : selectReply+ }+ />+ )}+ {item.kind === 'message' && failureRows(item.message.id)}+ </Fragment>+ ),+ )}</WideScreenContainer></Flexbox>{readOnly ? (diff --git a/src/features/Channels/ChannelMessage.test.tsx b/src/features/Channels/ChannelMessage.test.tsxindex e33d57acf9d..f8807cc9bcd 100644--- a/src/features/Channels/ChannelMessage.test.tsx+++ b/src/features/Channels/ChannelMessage.test.tsx@@ -1,7 +1,12 @@/*** @vitest-environment happy-dom*/-import type { ChannelDetail, ChannelPublicMessage, ExternalWorkSummaryItem } from '@lobechat/types';+import type {+ ChannelDetail,+ ChannelPublicJob,+ ChannelPublicMessage,+ ExternalWorkSummaryItem,+} from '@lobechat/types';import { fireEvent, render, screen } from '@testing-library/react';import { act, createElement, type ReactNode } from 'react';import { describe, expect, it, vi } from 'vitest';@@ -96,9 +101,12 @@ vi.mock('@/store/user/selectors', () => ({}));vi.mock('./MessageAttachments', () => ({ MessageAttachments: () => null }));vi.mock('./MessageReceipts', () => ({- MessageFailureMark: () => null,MessageRoutingStatus: () => null,}));+vi.mock('./ReplyFailure', () => ({+ ReplyFailureCard: ({ job }: { job: { id: string } }) =>+ createElement('div', { 'data-testid': 'reply-failure' }, job.id),+}));const detail = {attachments: [],@@ -337,3 +345,20 @@ describe('ChannelMessage thread card', () => {expect(screen.queryByText('threadCard.messages')).toBeNull();});});++describe('ChannelMessage reply failures', () => {+ it('mounts the failure card of a reply under the acknowledgement it posted', () => {+ render(+ <ChannelMessage+ detail={detail}+ failures={[{ id: 'job_1' } as ChannelPublicJob]}+ message={{+ ...message({ avatar: null, id: 'agt_1', name: 'Sanjo', type: 'agent' }),+ content: 'On it, checking CI first.',+ }}+ />,+ );++ expect(screen.getByTestId('reply-failure').textContent).toBe('job_1');+ });+});diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsxindex 8f53cd3c5fb..45dfad86c1c 100644--- a/src/features/Channels/ChannelMessage.tsx+++ b/src/features/Channels/ChannelMessage.tsx@@ -1,4 +1,4 @@-import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';+import type { ChannelDetail, ChannelPublicJob, ChannelPublicMessage } from '@lobechat/types';import {ActionIcon,Button,@@ -39,7 +39,8 @@ import { authorAvatar, isCurrentUserAuthor, memberName } from './memberName';import { CHANNEL_MENTION_TAG, remarkChannelMentions } from './mentionMarkdown';import { MessageAttachments } from './MessageAttachments';import { channelMessageTime, channelTimeFormatters } from './messagePresentation';-import { MessageFailureMark, MessageRoutingStatus } from './MessageReceipts';+import { MessageRoutingStatus } from './MessageReceipts';+import { ReplyFailureCard } from './ReplyFailure';import { showsReplyQuote } from './replyQuote';import type { ReplyTopic } from './ReplyTopicPanel';import { ReplyWorks } from './ReplyWorks';@@ -79,6 +80,7 @@ export const ChannelMessage = ({delivery,detail,continuation = false,+ failures,message,isRoot,highlighted,@@ -94,6 +96,8 @@ export const ChannelMessage = ({/** For a message the server has not confirmed: its send status, in place of routing. */delivery?: ReactNode;detail: ChannelDetail;+ /** Replies that acknowledged with this message and then failed; their cards mount under it. */+ failures?: ChannelPublicJob[];isRoot?: boolean;highlighted?: boolean;message: ChannelPublicMessage;@@ -110,12 +114,8 @@ export const ChannelMessage = ({const { t, i18n } = useTranslation('channel');const timeFormats = useMemo(() => channelTimeFormatters(i18n.language), [i18n.language]);const date = new Date(message.createdAt);- // Failed/unassigned requests keep their identity row and recovery affordance.- const compact =- continuation &&- !isRoot &&- message.routingStatus !== 'unassigned' &&- !detail.jobs.some((job) => job.messageId === message.id && job.status === 'failed');+ // Unassigned requests keep their identity row and recovery affordance.+ const compact = continuation && !isRoot && message.routingStatus !== 'unassigned';// A continuation sits under its header, so its hover stamp only needs the clock.const timestamp = (<time@@ -226,6 +226,7 @@ export const ChannelMessage = ({placement="left"showHeader={!compact}style={{ paddingInlineStart: 48 }}+ titleAddon={timestamp}avatar={{avatar: authorAvatar(message.author),title: message.author.name || t('deletedMember'),@@ -331,6 +332,9 @@ export const ChannelMessage = ({<MessageText content={message.content} names={mentionNames} />))}{!!message.works?.length && <ReplyWorks works={message.works} />}+ {failures?.map((job) => (+ <ReplyFailureCard job={job} key={job.id} />+ ))}{thread && (<ThreadPreviewCardroot={message}@@ -340,12 +344,6 @@ export const ChannelMessage = ({)}</Flexbox>}- titleAddon={- <>- {timestamp}- {isRequest && !delivery && <MessageFailureMark detail={detail} message={message} />}- </>- }/>{hasToolbar && (// Icon-only, like a chat app's hover toolbar; rarer actions sit behind "more".@@ -386,11 +384,13 @@ export const ChannelMessage = ({export function ThreadRootMessage({detail,+ failures,root,onReply,highlighted,}: {detail: ChannelDetail;+ failures?: ChannelPublicJob[];root: ChannelPublicMessage;onReply?: (message: ChannelPublicMessage) => void;highlighted?: boolean;@@ -401,6 +401,7 @@ export function ThreadRootMessage({<ChannelMessageisRootdetail={detail}+ failures={failures}highlighted={highlighted}message={root}onReply={onReply}diff --git a/src/features/Channels/FailureIndicator.tsx b/src/features/Channels/FailureIndicator.tsxindex cb59264c0e1..6207051ee42 100644--- a/src/features/Channels/FailureIndicator.tsx+++ b/src/features/Channels/FailureIndicator.tsx@@ -7,10 +7,17 @@ import { useTranslation } from 'react-i18next';import { mainTimelineFailures } from './jobStatus';import type { ReplyEntry } from './MessageReceipts';import { ReplyDetail, replyEntries } from './MessageReceipts';+import { REPLY_FAILURE_ATTRIBUTE } from './ReplyFailure';import { statusStyles, toneStyles } from './styles';-/** Scrolls the main conversation to a message, if it is in the loaded page. */-const findMessage = (messageId: string) =>+/**+ * The failure's card in the main conversation, else the request it answered, if either is in+ * the loaded page.+ */+const findFailure = ({ id, messageId }: ReplyEntry['job']) =>+ document.querySelector<HTMLElement>(+ `[data-channel-conversation="main"] [${REPLY_FAILURE_ATTRIBUTE}="${CSS.escape(id)}"]`,+ ) ??document.querySelector<HTMLElement>(`[data-channel-conversation="main"] [data-message-id="${CSS.escape(messageId)}"]`,);@@ -28,7 +35,7 @@ function FailureRow({ channelId, entry }: { channelId: string; entry: ReplyEntrytype="text"onClick={() => {close();- findMessage(entry.job.messageId)?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ findFailure(entry.job)?.scrollIntoView({ behavior: 'smooth', block: 'center' });}}>{t('failure.locate')}@@ -38,8 +45,8 @@ function FailureRow({ channelId, entry }: { channelId: string; entry: ReplyEntry}/**- * Replies that failed and were not settled by a newer reply from the same Agent. Lives in- * the header so the timeline stays readable; each message keeps a small marker.+ * Replies that failed and were not settled by a newer reply from the same Agent. The header+ * gathers them; each one's card sits under the Agent's message in the timeline.*/export function FailureIndicator({ detail }: { detail: ChannelDetail }) {const { t } = useTranslation('channel');diff --git a/src/features/Channels/MessageReceipts.tsx b/src/features/Channels/MessageReceipts.tsxindex b6119077623..b37e3c7340e 100644--- a/src/features/Channels/MessageReceipts.tsx+++ b/src/features/Channels/MessageReceipts.tsx@@ -1,6 +1,6 @@import type { ChannelDetail, ChannelPublicJob, ChannelPublicMessage } from '@lobechat/types';import { ChatErrorType } from '@lobechat/types';-import { Button, Flexbox, Popover, Text, usePopoverContext } from '@lobehub/ui';+import { Button, Flexbox, Text, usePopoverContext } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import { ExternalLink, Square } from 'lucide-react';import { useState } from 'react';@@ -171,46 +171,6 @@ export function ReplyList({ channelId, entries }: { channelId: string; entries:);}-/**- * A text-less marker beside a message whose reply failed, so the failure flagged in the- * header can be traced to its message. The reason is one click away.- */-export function MessageFailureMark({- detail,- message,-}: {- detail: ChannelDetail;- message: ChannelPublicMessage;-}) {- const { t, i18n } = useTranslation('channel');- const failed = (detail.jobs ?? []).filter(- (job) => job.messageId === message.id && job.status === 'failed',- );- if (!failed.length) return null;- const entries = replyEntries(detail, failed, t('unnamedAgent'));- const label = t('failure.messageLabel', {- names: new Intl.ListFormat(i18n.language, { type: 'conjunction' }).format(- entries.map((entry) => entry.name),- ),- });- return (- <Popover- content={<ReplyList channelId={detail.channel.id} entries={entries} />}- placement="bottomLeft"- trigger="click"- >- <button- aria-label={label}- title={label}- type="button"- {...stylex.props(statusStyles.failureMark)}- >- <span aria-hidden {...stylex.props(statusStyles.dot)} />- </button>- </Popover>- );-}-/** A message that no Agent picked up; the routing outcome stays with the message. */export function MessageRoutingStatus({ message }: { message: ChannelPublicMessage }) {const { t } = useTranslation('channel');diff --git a/src/features/Channels/ReplyFailure.tsx b/src/features/Channels/ReplyFailure.tsxnew file mode 100644index 00000000000..3861f69e136--- /dev/null+++ b/src/features/Channels/ReplyFailure.tsx@@ -0,0 +1,71 @@+import type { ChannelDetail, ChannelPublicJob } from '@lobechat/types';+import { Alert, Flexbox, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';+import { ChatItem } from '@/features/Conversation/ChatItem';++import { receiptErrorText, replyEntries } from './MessageReceipts';+import { styles } from './styles';++/** Marks a failure card, so the header's failure list can scroll to it. */+export const REPLY_FAILURE_ATTRIBUTE = 'data-channel-reply-failure';++/** Why a reply failed, mounted under the Agent's message like a chat's error card. */+export function ReplyFailureCard({ job }: { job: ChannelPublicJob }) {+ const { t } = useTranslation('channel');+ return (+ <Alert+ showIcon+ data-channel-reply-failure={job.id}+ role="status"+ style={{ alignSelf: 'stretch' }}+ title={t('status.failed')}+ type="error"+ variant="outlined"+ description={+ <Flexbox gap={4}>+ <Text style={{ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' }}>+ {receiptErrorText(job, t)}+ </Text>+ <Text fontSize={12} type="secondary">+ {t('receipt.failedHint')}+ </Text>+ </Flexbox>+ }+ />+ );+}++/**+ * A failed reply that posted nothing, as the Agent's own row after the request: the card in+ * place of the answer that never came.+ */+export function ReplyFailureRow({ detail, job }: { detail: ChannelDetail; job: ChannelPublicJob }) {+ const { t } = useTranslation('channel');+ const [{ agentId, avatar, name }] = replyEntries(detail, [job], t('unnamedAgent'));+ return (+ <div aria-label={name} role="article" {...stylex.props(styles.messageRow)}>+ <ChatItem+ quietHeader+ showAvatar+ showTitle+ agentId={agentId}+ avatar={{ avatar, title: name }}+ avatarProps={{ shape: 'circle', size: 36 }}+ gap={4}+ id={`reply-failure-${job.id}`}+ message={<ReplyFailureCard job={job} />}+ paddingBlock={8}+ placement="left"+ style={{ paddingInlineStart: 48 }}+ customAvatarRender={() => (+ <Flexbox {...stylex.props(styles.messageAvatar)}>+ <AgentAvatar agentId={agentId} avatar={avatar} name={name} shape={'circle'} size={36} />+ </Flexbox>+ )}+ />+ </div>+ );+}diff --git a/src/features/Channels/jobStatus.test.ts b/src/features/Channels/jobStatus.test.tsindex 97e988a8560..0f4b623e6ec 100644--- a/src/features/Channels/jobStatus.test.ts+++ b/src/features/Channels/jobStatus.test.ts@@ -11,6 +11,7 @@ import {memberJobStatus,replyActivityJobs,replyAvatarState,+ replyFailurePlacement,unresolvedFailures,} from './jobStatus';@@ -273,3 +274,58 @@ describe('hasReplyActivity', () => {expect(hasReplyActivity(running, null)).toBe(false);});});++describe('replyFailurePlacement', () => {+ const failed = (patch: Partial<ChannelPublicJob>) =>+ ({+ messageId: 'request',+ openingMessageId: null,+ status: 'failed',+ threadId: null,+ ...patch,+ }) as ChannelPublicJob;+ const ids = (jobs: ChannelPublicJob[] | undefined) => jobs?.map((job) => job.id);++ it('mounts a failure under the acknowledgement it posted, and after the request otherwise', () => {+ const { afterMessage, underMessage } = replyFailurePlacement(+ [+ failed({ id: 'no-ack' }),+ failed({ id: 'acked', openingMessageId: 'ack' }),+ // Its acknowledgement is on an older page: the request is where it still shows.+ failed({ id: 'ack-unloaded', openingMessageId: 'old-ack' }),+ ],+ new Set(['request', 'ack']),+ null,+ );++ expect(ids(underMessage.get('ack'))).toEqual(['acked']);+ // Oldest first, though jobs arrive newest first.+ expect(ids(afterMessage.get('request'))).toEqual(['ack-unloaded', 'no-ack']);+ });++ it('leaves out replies still at work, other conversations, and requests not loaded', () => {+ const { afterMessage, underMessage } = replyFailurePlacement(+ [+ failed({ id: 'running', status: 'running' }),+ failed({ id: 'completed', openingMessageId: 'ack', status: 'completed' }),+ failed({ id: 'in-thread', threadId: 'thread-a' }),+ failed({ id: 'older-page', messageId: 'older' }),+ ],+ new Set(['request', 'ack']),+ null,+ );++ expect(afterMessage.size).toBe(0);+ expect(underMessage.size).toBe(0);+ });++ it('places a thread reply in its thread, after the root it answered', () => {+ const { afterMessage } = replyFailurePlacement(+ [failed({ id: 'in-thread', messageId: 'root', threadId: 'thread-a' })],+ new Set(['root']),+ 'thread-a',+ );++ expect(ids(afterMessage.get('root'))).toEqual(['in-thread']);+ });+});diff --git a/src/features/Channels/jobStatus.ts b/src/features/Channels/jobStatus.tsindex 46cc41b8567..5f293b3e215 100644--- a/src/features/Channels/jobStatus.ts+++ b/src/features/Channels/jobStatus.ts@@ -1,4 +1,4 @@-import type { ChannelDetail, ChannelReplyJob } from '@lobechat/types';+import type { ChannelDetail, ChannelPublicJob, ChannelReplyJob } from '@lobechat/types';import type { AgentAvatarState } from '@lobehub/ui';export const channelJobStatus = (job: ChannelReplyJob) =>@@ -68,6 +68,34 @@ export const unresolvedFailures = <T extends ChannelReplyJob>(jobs: T[]) => {export const mainTimelineFailures = <T extends ChannelReplyJob>(jobs: T[]) =>unresolvedFailures(jobs.filter((job) => !job.threadId));+type FailedReply = Pick<ChannelPublicJob, 'messageId' | 'openingMessageId' | 'status' | 'threadId'>;++const append = <T>(map: Map<string, T[]>, key: string, value: T) =>+ map.set(key, [...(map.get(key) ?? []), value]);++/**+ * Where a conversation's failed replies show, keyed by message id, oldest first: under the+ * acknowledgement the reply posted before its run (`underMessage`), or, when it posted none or+ * that is not loaded, as the Agent's own row after the request (`afterMessage`). A reply whose+ * request is not loaded either shows only in the header.+ */+export const replyFailurePlacement = <T extends FailedReply>(+ jobs: T[],+ loadedMessageIds: ReadonlySet<string>,+ threadId: string | null,+) => {+ const underMessage = new Map<string, T[]>();+ const afterMessage = new Map<string, T[]>();+ // Jobs arrive newest first; a message lists its failures in the order they happened.+ for (const job of [...jobs].reverse()) {+ if (job.status !== 'failed' || (job.threadId ?? null) !== threadId) continue;+ if (job.openingMessageId && loadedMessageIds.has(job.openingMessageId))+ append(underMessage, job.openingMessageId, job);+ else if (loadedMessageIds.has(job.messageId)) append(afterMessage, job.messageId, job);+ }+ return { afterMessage, underMessage };+};+/** What a member is busy with now: a running reply first, then the next queued one. */export const memberCurrentJob = <T extends ChannelReplyJob>(jobs: T[], memberId: string) => {const own = jobs.filter((job) => job.memberId === memberId);diff --git a/src/features/Channels/messagePresentation.test.ts b/src/features/Channels/messagePresentation.test.tsindex 9a03a9b811b..18464f6699b 100644--- a/src/features/Channels/messagePresentation.test.ts+++ b/src/features/Channels/messagePresentation.test.ts@@ -59,6 +59,15 @@ describe('channel reading groups', () => {expect(midnight[1]).toMatchObject({ continuation: false, startsDay: true });});+ it('starts a fresh group after a row shown between two messages', () => {+ const request = message(at, { id: 'request' });+ const rows = presentChannelTimeline(+ [request, message(later(1), { id: 'next' })],+ new Set(['request']),+ );+ expect(rows.map((row) => row.continuation)).toEqual([false, false]);+ });+it('does not group out-of-order messages or a first message on an older page', () => {expect(presentChannelTimeline([message(later(1)), message(at)])[1].continuation).toBe(false);expect(presentChannelTimeline([message(at)])[0].continuation).toBe(false);diff --git a/src/features/Channels/messagePresentation.ts b/src/features/Channels/messagePresentation.tsindex b7e2738d6bd..82fa673bbaf 100644--- a/src/features/Channels/messagePresentation.ts+++ b/src/features/Channels/messagePresentation.ts@@ -10,8 +10,15 @@ const itemDate = (item: TimelineItem) =>const sameAuthor = (a: ChannelPublicMessage, b: ChannelPublicMessage) =>!!a.author.id && a.author.id === b.author.id && a.author.type === b.author.type;-/** Group only adjacent speech; system events, dates and reply contexts break a group. */-export const presentChannelTimeline = (items: TimelineItem[]) =>+/**+ * Group only adjacent speech; system events, dates and reply contexts break a group. So does a+ * row shown between two messages (`breaksAfter`, by the message it follows), or the second one+ * would read as said by whoever wrote that row.+ */+export const presentChannelTimeline = (+ items: TimelineItem[],+ breaksAfter: ReadonlySet<string> = new Set(),+) =>items.map((item, index) => {const previous = items[index - 1];const date = itemDate(item);@@ -24,6 +31,7 @@ export const presentChannelTimeline = (items: TimelineItem[]) =>elapsed <= GROUP_WINDOW_MS &&item.kind === 'message' &&previous?.kind === 'message' &&+ !breaksAfter.has(previous.message.id) &&sameAuthor(item.message, previous.message) &&item.message.threadId === previous.message.threadId &&item.message.replyToId === previous.message.replyToId;diff --git a/src/features/Channels/styles.ts b/src/features/Channels/styles.tsindex e7fb575f83e..1730d2484e7 100644--- a/src/features/Channels/styles.ts+++ b/src/features/Channels/styles.ts@@ -311,20 +311,6 @@ export const statusStyles = stylex.create({borderRadius: '50%',backgroundColor: 'currentcolor',},- /** A bare red dot beside a message whose reply failed. */- failureMark: {- display: 'inline-flex',- alignItems: 'center',- justifyContent: 'center',- width: 18,- height: 18,- padding: 0,- borderWidth: 0,- borderRadius: '50%',- color: cssVar.colorError,- cursor: 'pointer',- backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorErrorBg },- },failureButton: {flex: 'none',gap: 4,