diff --git a/docs/fixture.md b/docs/fixture.md index c83f9e9a..8f24239c 100644 --- a/docs/fixture.md +++ b/docs/fixture.md @@ -8,8 +8,9 @@ - Linux 无显示器:先起 `Xvfb :99 &`,再 `DISPLAY=:99 npm run fixture -- all`。缺 libgtk-3 时 `sudo apt-get install -y libgtk-3-0 libnss3 libgbm1 libasound2`。 - 每次用临时 `--user-data-dir`,跑完删掉;不读写任何 BotArk 数据目录。 - 假平台只在 `?e2e=1`(或 localStorage `BOTHUB_E2E=1`)且有 `BOTARK_FAKE_SCRIPT` 时注册,正常使用不会出现(`src/adapters/fake/FakeAdapter.ts`)。 -- 剧本:`bots`(名字、账号)、`script.accounts[].steps`(`text` 回复;`kind: silent | abort | error`;`delayMs`)、`rounds`(`say` 发消息或 `retry` 再发一次,`expect` 见 `scripts/fixture/check.mjs`)。 +- 剧本:`bots`(名字、账号)、`script.accounts[].steps`(`text` 回复;`kind: silent | abort | error | lost`;`delayMs`;`error` = 没发出去,`lost` = 发出后确认前超时,记「可能已送达,未确认」,PR #61)、`rounds`(`say` 发消息或 `retry` 再发一次,`expect` 见 `scripts/fixture/check.mjs`)。 - 每步输出 `<剧本>-<步>.png` 和 `.json`(消息、错误条、平台收到的原文)。退出码 0 = 全过。 +- 剧本 uncertain-delivery:确认前超时显示「可能已送达,未确认」而不是「未送达」(PR #61)。 - 剧本 route-by-description 需要「谁来答」(PR #48)。 - 「谁来答」第 1 步剧本:coordinator-no-pick(选不出→总控,总控派给成员)、coordinator-quota-backup(总控额度不足→备用)、coordinator-error-best(总控、备用都报错→打分最高的在线成员)、mention-direct(@成员直达、@总控、成员答不上→总控)。 - 剧本可选字段:`prefs`(并入 bothub-prefs-v1,如 `roomCoordinatorId`、`roomBackupCoordinatorId`)、`roomBots`(进群的 bot id,默认全部;总控可以不在群里,需要时自动加入);`expect` 新增 `routeReasons`、`sentIncludes`、`members`(见 scripts/fixture/check.mjs)。 diff --git a/scripts/fixture/uncertain-delivery.json b/scripts/fixture/uncertain-delivery.json new file mode 100644 index 00000000..33360e8f --- /dev/null +++ b/scripts/fixture/uncertain-delivery.json @@ -0,0 +1,54 @@ +{ + "title": "确认前超时:可能已送达,不算未送达", + "mode": "auto", + "limit": 4, + "bots": [ + { + "id": "bot-a", + "name": "甲", + "account": "fa" + }, + { + "id": "bot-b", + "name": "乙", + "account": "fb" + } + ], + "script": { + "platform": "meta-muse", + "accounts": [ + { + "id": "fa", + "displayName": "甲", + "steps": [ + { + "kind": "lost", + "delayMs": 800 + } + ] + }, + { + "id": "fb", + "displayName": "乙", + "steps": [] + } + ] + }, + "rounds": [ + { + "say": "@甲 在吗", + "expect": { + "order": [], + "includes": [ + "甲 本轮可能已送达,未确认。" + ], + "excludes": [ + "甲 本轮未送达。" + ], + "sentTo": { + "fa": 1 + } + } + } + ] +} diff --git a/src/adapters/fake/FakeAdapter.ts b/src/adapters/fake/FakeAdapter.ts index 336f6002..f0b3e5cd 100644 --- a/src/adapters/fake/FakeAdapter.ts +++ b/src/adapters/fake/FakeAdapter.ts @@ -28,6 +28,8 @@ export type FakeStep = | { kind: 'abort'; text?: string; delayMs?: number } /** The send fails before the platform takes it. */ | { kind: 'error'; text: string; delayMs?: number } + /** The send goes out but times out before the platform confirms it; `text`, if any, arrives later as a late reply. */ + | { kind: 'lost'; text?: string; delayMs?: number; lateMs?: number } export interface FakeAccount { id: string @@ -95,7 +97,16 @@ export class FakeAdapter implements PlatformAdapter { const step: FakeStep = this.queues.get(accountId)?.shift() ?? { text: OUT_OF_SCRIPT } if (step.kind === 'error') { await wait(step.delayMs ?? 0, signal) - throw new AdapterError('network', step.text) + throw new AdapterError('not-connected', step.text) + } + if (step.kind === 'lost') { + await wait(step.delayMs ?? 500, signal) + const late = step.text + if (late) setTimeout(() => this.emit({ + type: 'message', + message: { id: createId('fake_in'), conversationId, accountId, text: late, createdAt: Date.now() } + }), step.lateMs ?? 1_000) + throw new AdapterError('timeout', '等待确认超时') } const receipt: SendReceipt = { messageId: createId('fake_out'), acceptedAt: Date.now() } message.onAccepted?.() diff --git a/src/renderer/src/lib/desktopCopy.test.ts b/src/renderer/src/lib/desktopCopy.test.ts index 99d81e91..a63a6e80 100644 --- a/src/renderer/src/lib/desktopCopy.test.ts +++ b/src/renderer/src/lib/desktopCopy.test.ts @@ -27,6 +27,8 @@ describe('desktop localization', () => { usePrefsStore.getState().setLocale('en') expect(desktopNotice('已达 1 轮上限,待回复:@成员 A')).toBe('Round limit reached (1). Still awaiting: @成员 A') expect(desktopNotice('成员 A 本轮未送达。')).toBe('The message wasn’t delivered to 成员 A.') + expect(desktopNotice('成员 A 本轮可能已送达,未确认。')).toBe('成员 A may have received the message, but it wasn’t confirmed.') + expect(desktopNotice('可能已送达,未确认(超时)')).toBe('May have been delivered, not confirmed (超时).') expect(desktopNotice('目录:项目 A')).toBe('目录:项目 A') const unknown = "Error invoking remote method 'bothub:grok:rpc': Error: 自定义错误" expect(desktopNotice(unknown)).toBe(unknown) diff --git a/src/renderer/src/lib/desktopNotices.ts b/src/renderer/src/lib/desktopNotices.ts index 1e4ccc0c..28ad17a3 100644 --- a/src/renderer/src/lib/desktopNotices.ts +++ b/src/renderer/src/lib/desktopNotices.ts @@ -7,6 +7,7 @@ export const desktopNotices: Record = { "{0} 中未包含任何 MCP 服务": "{0} does not contain any MCP services", "{0} 已收到消息,本轮还没有回复。": "{0} received the message but hasn’t replied yet.", "{0} 必须为对象": "{0} must be an object.", + "{0} 本轮可能已送达,未确认。": "{0} may have received the message, but it wasn’t confirmed.", "{0} 本轮未送达。": "The message wasn’t delivered to {0}.", "@{0} 正忙或已断开连接": "@{0} is busy or disconnected.", "⚠️ **Grok Bot 执行中断 ({0})**:{1}": "⚠️ **Grok Bot stopped ({0})**: {1}", @@ -220,6 +221,7 @@ export const desktopNotices: Record = { "已退出 Grok Bot": "Exited Grok Bot", "已送达,但应用关闭时回复还没收完": "Delivered, but the app closed before the reply finished.", "已送达,但没有回复({0})": "Delivered, but no reply was received ({0}).", + "可能已送达,未确认({0})": "May have been delivered, not confirmed ({0}).", "已送达,但没有收到回复": "Delivered, but no reply received", "已送达,但等待回复时出错;重发前先确认对方是否已回复": "Delivered, but waiting for the reply failed. Check for a reply before sending again.", "已送达,后续新消息已接替等待": "Delivered. A newer message is now being tracked.", diff --git a/src/renderer/src/mock/mocks/v34-room-uncertain.tsx b/src/renderer/src/mock/mocks/v34-room-uncertain.tsx new file mode 100644 index 00000000..c4d90c2c --- /dev/null +++ b/src/renderer/src/mock/mocks/v34-room-uncertain.tsx @@ -0,0 +1,86 @@ +import type { ReactNode } from 'react' +import { AlertCircle, CircleHelp, Quote, RotateCw, Undo2 } from 'lucide-react' +import { Button } from '@/components/ui/Button' +import { cn } from '@/lib/cn' + +/** + * v34:发出后、平台确认前超时或断线(PR #61)。 + * 左 = 现在:记成「未送达」,红字 + 重试,点了 Bot 可能收到两遍。 + * 右 = 方案:灰字「可能已送达,未确认」+ 问号图标;点重试先弹一句确认;迟到的回复照样补进群。 + */ +const metaButton = 'press inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[11.5px] text-ink-muted hover:bg-hover hover:text-ink' +const retryButton = 'inline-flex items-center gap-1 rounded-full px-1 text-[11px] font-medium underline-offset-2 hover:underline' + +function Column({ title, children }: { title: string; children: ReactNode }) { + return ( +
+
{title}
+
{children}
+
+ ) +} + +function Notice({ text, retry }: { text: string; retry: string }) { + return ( +
+ {text} + 重试 +
+ ) +} + +function Human({ plan }: { plan: boolean }) { + return ( +
+
@Muse 把上周的周报整理成三段
+
+ 20:14 + 引用 + 撤回 + {plan ? ( + + 可能已送达,未确认(等待确认超时) + 重试 + + ) : ( + + 未送达:等待确认超时 + 重试 + + )} +
+
+ ) +} + +function Confirm() { + return ( +
+
再发一次给 @Muse?
+

这条可能已经发出,只是平台没确认。再发一次,Muse 可能收到两遍。它的回复如果晚到,会自动补进群里。

+
+ + +
+
+ ) +} + +export function V34RoomUncertainMock() { + return ( +
+
+ + + + + + + + + +
+

右下是点「重试」后弹出的确认。真没发出去(未连接、账号不存在)仍显示原来的「未送达」,不弹确认。

+
+ ) +} diff --git a/src/renderer/src/mock/mocks/v34b-room-uncertain-real.tsx b/src/renderer/src/mock/mocks/v34b-room-uncertain-real.tsx new file mode 100644 index 00000000..2724f294 --- /dev/null +++ b/src/renderer/src/mock/mocks/v34b-room-uncertain-real.tsx @@ -0,0 +1,32 @@ +import { useEffect } from 'react' +import type { CollabRoom, RoomMember, RoomMessage } from '@/rooms/model' +import { RoomTranscript } from '@/rooms/RoomTranscript' +import { useRooms } from '@/rooms/roomStore' + +/** v34 真实组件:可能已送达 / 未送达 两种失败,并自动点开「可能已送达」那条的重试确认。 */ +const member = (botId: string, name: string): RoomMember => ({ botId, name, accountId: `acc-${botId}`, platform: 'meta-muse' } as RoomMember) +const MEMBERS = [member('m', 'Muse'), member('d', 'Dot')] +const at = new Date(2026, 11, 3, 20, 14).getTime() +const MESSAGES: RoomMessage[] = [ + { id: 'h1', author: 'User', text: '@Muse 把上周的周报整理成三段', createdAt: at, + failures: [{ botId: 'm', name: 'Muse', error: '等待确认超时', delivered: false, uncertain: true, noticeId: 'n1' }] }, + { id: 'n1', author: 'BotArk', notice: true, text: 'Muse 本轮可能已送达,未确认。', createdAt: at }, + { id: 'h2', author: 'User', text: '@Dot 也看一下', createdAt: at, + failures: [{ botId: 'd', name: 'Dot', error: '未连接', delivered: false, noticeId: 'n2' }] }, + { id: 'n2', author: 'BotArk', notice: true, text: 'Dot 本轮未送达。', createdAt: at } +] +useRooms.setState({ rooms: [{ id: 'mock', title: '周报', members: MEMBERS, messages: MESSAGES, mode: 'manual', limit: 8, brief: '' } as CollabRoom] }) + +export function V34bRoomUncertainRealMock() { + useEffect(() => { + const button = [...document.querySelectorAll('p button')].find((b) => b.parentElement?.textContent?.includes('可能已送达')) + ;(button as HTMLButtonElement | undefined)?.click() + }, []) + return ( +
+
+ {}} onExport={() => {}} /> +
+
+ ) +} diff --git a/src/renderer/src/mock/registry.ts b/src/renderer/src/mock/registry.ts index 491c4345..da3001d1 100644 --- a/src/renderer/src/mock/registry.ts +++ b/src/renderer/src/mock/registry.ts @@ -17,6 +17,8 @@ import { V30RoomRoutedMock } from './mocks/v30-room-routed' import { V31ProjectRowMock } from './mocks/v31-project-row' import { V33ExternalConfirmMock, V33ExternalFormsMock } from './mocks/v33-external-agents' import { V33bExternalRealMock } from './mocks/v33b-external-real' +import { V34RoomUncertainMock } from './mocks/v34-room-uncertain' +import { V34bRoomUncertainRealMock } from './mocks/v34b-room-uncertain-real' import { V32RoomContextMock } from './mocks/v32-room-context' import { V32bRoomContextLiveMock } from './mocks/v32b-room-context-live' import { V32RoomWorkflowMock } from './mocks/v32-room-workflow' @@ -46,6 +48,8 @@ export const MOCKS: Record = { 'v33-external-forms': V33ExternalFormsMock, 'v33-external-confirm': V33ExternalConfirmMock, 'v33b-external-real': V33bExternalRealMock, + 'v34-room-uncertain': V34RoomUncertainMock, + 'v34b-room-uncertain-real': V34bRoomUncertainRealMock, 'v32-room-context': V32RoomContextMock, 'v32b-room-context-live': V32bRoomContextLiveMock, 'v32-room-workflow': V32RoomWorkflowMock, diff --git a/src/renderer/src/rooms/RoomMessageStatus.tsx b/src/renderer/src/rooms/RoomMessageStatus.tsx index e89d9493..e6b817ff 100644 --- a/src/renderer/src/rooms/RoomMessageStatus.tsx +++ b/src/renderer/src/rooms/RoomMessageStatus.tsx @@ -1,10 +1,12 @@ import { desktopCopy, desktopNotice, useDesktopLocale } from '@/lib/desktopCopy' -import { AlertCircle, Check, CheckCheck, Loader2, RotateCw, Route } from 'lucide-react' +import { AlertCircle, Check, CheckCheck, CircleHelp, Loader2, RotateCw, Route } from 'lucide-react' import { cn } from '@/lib/cn' import type { RoomMember, RoomMessage } from './model' import { NO_REPLY_ERROR, resendRoomMessage, useRooms } from './roomStore' import { messageRouteSteps, routeLineText } from './roomCoordinator' import { findRetryTarget, retryRoomMember, roomDeliveryState } from './roomRetry' +import { failureKind, UNCERTAIN_NOTICE } from './roomDeliveryKind' +import { useUncertainRetry } from './RoomRetryConfirm' const retryButton = 'inline-flex items-center gap-1 rounded-full px-1 text-[11px] font-medium underline-offset-2 hover:underline disabled:opacity-50 disabled:no-underline' @@ -24,8 +26,10 @@ export function RoomDeliveryState({ roomId, message, members }: { const speaking = useRooms((s) => Boolean(s.speakers[roomId])) const state = useRooms((s) => roomDeliveryState(s.rooms.find((r) => r.id === roomId)?.messages ?? [], message.id, speaking)) const failures = message.failures ?? [] + const confirm = useUncertainRetry() return ( <> + {confirm.dialog} {state === 'replying' && ( {desktopCopy("已发出 · 回复中", "Delivered · replying")} @@ -37,24 +41,28 @@ export function RoomDeliveryState({ roomId, message, members }: { )} {failures.map((raw) => { - const delivered = raw.delivered ?? (raw.error === NO_REPLY_ERROR || /送达|已收到/.test(raw.error)) - // A delivered message never reads as undelivered. + const kind = failureKind(raw, NO_REPLY_ERROR) + const delivered = kind === 'received' + // A delivered message never reads as undelivered; one that may have arrived says so. const text = delivered ? raw.error === NO_REPLY_ERROR ? NO_REPLY_ERROR : `已送达,但没有回复(${raw.error})` - : `未送达:${raw.error}` + : kind === 'uncertain' ? `可能已送达,未确认(${raw.error})` : `未送达:${raw.error}` + const tone = kind === 'not-sent' ? 'text-status-attention-ink' : kind === 'uncertain' ? 'text-ink-secondary' : 'text-ink-muted' + const Icon = delivered ? CheckCheck : kind === 'uncertain' ? CircleHelp : AlertCircle const member = members.find((m) => m.botId === raw.botId) return ( - {delivered ? : } + className={cn('inline-flex items-center gap-1.5 px-1 text-[11px]', tone)}> + {desktopNotice(failures.length > 1 ? `@${raw.name}:${text}` : text)} {member && ( @@ -66,7 +74,10 @@ export function RoomDeliveryState({ roomId, message, members }: { + + + } + > +

+ {desktopCopy( + "这条可能已经发出,只是平台没确认。再发一次,{0} 可能收到两遍。它的回复如果晚到,会自动补进群里。", + "This may have gone out; the platform just didn’t confirm it. Sending again could reach {0} twice. A late reply is added to the group on its own.", + [pending?.name ?? ''] + )} +

+ + ) + return { ask, dialog } +} diff --git a/src/renderer/src/rooms/model.ts b/src/renderer/src/rooms/model.ts index 327d7995..a6c39a60 100644 --- a/src/renderer/src/rooms/model.ts +++ b/src/renderer/src/rooms/model.ts @@ -66,6 +66,8 @@ export interface RoomMessage { error: string /** The platform took the message; only the reply is missing, so this is not "not delivered". */ delivered?: boolean + /** It went out but the platform never confirmed it: it may have arrived (roomDeliveryKind.ts). */ + uncertain?: boolean /** The 本轮… notice posted for this failure, removed with it. */ noticeId?: string }> diff --git a/src/renderer/src/rooms/roomActions.test.ts b/src/renderer/src/rooms/roomActions.test.ts index a460439d..c5d69b37 100644 --- a/src/renderer/src/rooms/roomActions.test.ts +++ b/src/renderer/src/rooms/roomActions.test.ts @@ -42,12 +42,14 @@ it('finds which member a failure notice retries, and for which message', () => { msg('n1', { author: 'BotArk', notice: true, text: 'Dot 本轮未送达。' }), msg('post', { author: 'Muse', authorBotId: 'Muse', text: '@Dot 看看' }), msg('n2', { author: 'BotArk', notice: true, text: 'Dot 已收到消息,本轮还没有回复。' }), - msg('n3', { author: 'BotArk', notice: true, text: '群聊没有可对话的成员' }) + msg('n3', { author: 'BotArk', notice: true, text: '群聊没有可对话的成员' }), + msg('n4', { author: 'BotArk', notice: true, text: 'Dot 本轮可能已送达,未确认。' }) ] } expect(findRetryTarget(room, 'n1')).toEqual({ messageId: 'ask', botId: 'Dot', noticeId: 'n1' }) expect(findRetryTarget(room, 'n2')).toEqual({ messageId: 'post', botId: 'Dot', noticeId: 'n2' }) expect(findRetryTarget(room, 'n3')).toBeUndefined() + expect(findRetryTarget(room, 'n4')).toEqual({ messageId: 'post', botId: 'Dot', noticeId: 'n4' }) expect(findRetryTarget(room, 'ask')).toBeUndefined() }) @@ -59,6 +61,10 @@ it('says whether a human message got there', () => { expect(roomDeliveryState([msg('a'), msg('b')], 'a', true)).toBeUndefined() expect(roomDeliveryState([msg('a', { failures: [{ botId: 'D', name: 'D', error: 'offline' }] })], 'a', false)).toBe('failed') expect(roomDeliveryState([msg('a', { failures: [{ botId: 'D', name: 'D', error: 'x', delivered: true }] })], 'a', false)).toBe('no-reply') + expect(roomDeliveryState([msg('a', { failures: [{ botId: 'D', name: 'D', error: 'x', uncertain: true }] })], 'a', false)).toBe('uncertain') + expect(roomDeliveryState([msg('a', { failures: [ + { botId: 'D', name: 'D', error: 'x', uncertain: true }, { botId: 'E', name: 'E', error: 'offline' } + ] })], 'a', false)).toBe('failed') expect(roomDeliveryState([msg('a', { failures: [{ botId: 'D', name: 'D', error: 'x' }] }), reply], 'a', false)).toBe('partial') expect(roomDeliveryState([reply], 'r', false)).toBeUndefined() }) diff --git a/src/renderer/src/rooms/roomDeliveryKind.test.ts b/src/renderer/src/rooms/roomDeliveryKind.test.ts new file mode 100644 index 00000000..1972ab55 --- /dev/null +++ b/src/renderer/src/rooms/roomDeliveryKind.test.ts @@ -0,0 +1,30 @@ +import { expect, it } from 'vitest' +import { AdapterError } from '@adapters/types' +import { failedSendKind, failureKind, roomFailureNotice } from './roomDeliveryKind' + +it('calls a send uncertain only when it may have gone out', () => { + expect(failedSendKind(new AdapterError('not-connected', 'x'))).toBe('not-sent') + expect(failedSendKind(new AdapterError('unknown-account', 'x'))).toBe('not-sent') + expect(failedSendKind(new AdapterError('unsupported', 'x'))).toBe('not-sent') + expect(failedSendKind(new AdapterError('timeout', 'x'))).toBe('uncertain') + expect(failedSendKind(new AdapterError('network', 'x'))).toBe('uncertain') + expect(failedSendKind(new Error('request aborted'))).toBe('uncertain') + expect(failedSendKind(new Error('Hark 发送超时,消息可能已经送达'))).toBe('uncertain') + expect(failedSendKind(new Error('socket hang up'))).toBe('uncertain') + expect(failedSendKind(new Error('HTTP 401 未登录'))).toBe('not-sent') +}) + +it('writes one notice per kind, and still takes the old boolean', () => { + expect(roomFailureNotice('Dot', 'received')).toBe('Dot 已收到消息,本轮还没有回复。') + expect(roomFailureNotice('Dot', 'uncertain')).toBe('Dot 本轮可能已送达,未确认。') + expect(roomFailureNotice('Dot', 'not-sent')).toBe('Dot 本轮未送达。') + expect(roomFailureNotice('Dot', true)).toBe('Dot 已收到消息,本轮还没有回复。') + expect(roomFailureNotice('Dot', false)).toBe('Dot 本轮未送达。') +}) + +it('reads failures saved before the uncertain mark', () => { + expect(failureKind({ error: '已送达,但没有收到回复' }, '已送达,但没有收到回复')).toBe('received') + expect(failureKind({ error: 'offline' }, '')).toBe('not-sent') + expect(failureKind({ error: 'x', delivered: true }, '')).toBe('received') + expect(failureKind({ error: 'x', delivered: false, uncertain: true }, '')).toBe('uncertain') +}) diff --git a/src/renderer/src/rooms/roomDeliveryKind.ts b/src/renderer/src/rooms/roomDeliveryKind.ts new file mode 100644 index 00000000..2672e03f --- /dev/null +++ b/src/renderer/src/rooms/roomDeliveryKind.ts @@ -0,0 +1,43 @@ +import { AdapterError } from '@adapters/types' +import { looksLikeAbort } from './unaskedStop' + +/** + * GOXF: what a failed group turn knows about its message. + * - received: the platform took it (only the reply is missing) + * - not-sent: it never left BotArk (not connected, no such account, unsupported) + * - uncertain: it went out but the platform never confirmed (timed out, connection + * dropped, cut off on the platform's side). It may have arrived, so a retry can + * reach the member twice. Idea from Agent HUD's "uncertain" receipts (Apache-2.0). + */ +export type RoomDeliveryKind = 'received' | 'not-sent' | 'uncertain' + +const NEVER_SENT: ReadonlySet = new Set(['not-connected', 'unknown-account', 'unsupported']) +const LOST_WORDS = /time(?:d)?\s*out|timeout|超时|network|网络|ECONNRESET|ECONNREFUSED|ETIMEDOUT|socket hang up|fetch failed|disconnect|断开|连接已关闭/iu + +/** A turn's error once the message was handed to the adapter, before the platform said it took it. */ +export function failedSendKind(error: unknown): Exclude { + if (error instanceof AdapterError) { + if (NEVER_SENT.has(error.code)) return 'not-sent' + if (error.code === 'timeout' || error.code === 'network') return 'uncertain' + } + if (looksLikeAbort(error)) return 'uncertain' + const text = error instanceof Error ? error.message : String(error ?? '') + return LOST_WORDS.test(text) ? 'uncertain' : 'not-sent' +} + +/** The tail of the group notice for an uncertain turn: 「 本轮可能已送达,未确认。」 */ +export const UNCERTAIN_NOTICE = '本轮可能已送达,未确认。' + +/** The line posted in the group when a member did not answer. */ +export function roomFailureNotice(name: string, kind: RoomDeliveryKind | boolean): string { + const k = typeof kind === 'boolean' ? (kind ? 'received' : 'not-sent') : kind + if (k === 'received') return `${name} 已收到消息,本轮还没有回复。` + if (k === 'uncertain') return `${name} ${UNCERTAIN_NOTICE}` + return `${name} 本轮未送达。` +} + +/** A stored failure's kind; failures saved before this field read from `delivered`. */ +export function failureKind(f: { delivered?: boolean; uncertain?: boolean; error: string }, noReplyError: string): RoomDeliveryKind { + if (f.delivered ?? (f.error === noReplyError || /送达|已收到/.test(f.error))) return 'received' + return f.uncertain ? 'uncertain' : 'not-sent' +} diff --git a/src/renderer/src/rooms/roomRetry.ts b/src/renderer/src/rooms/roomRetry.ts index d008588d..60d73df8 100644 --- a/src/renderer/src/rooms/roomRetry.ts +++ b/src/renderer/src/rooms/roomRetry.ts @@ -1,4 +1,5 @@ import { isHumanRoomMessage, type CollabRoom, type RoomMember, type RoomMessage } from './model' +import { failureKind } from './roomDeliveryKind' import { NO_REPLY_ERROR, removeMessages, submitBrief, useRooms } from './roomStore' /** GOXF: one member to ask again about one message. */ @@ -10,7 +11,7 @@ export interface RetryTarget { } // The notice texts roomFailureNotice writes, plus the older 未取得回复 wording. -const NOTICE_NAME = /^(.+?) (?:已收到消息,本轮还没有回复|本轮未送达|本轮未取得回复)。$/u +const NOTICE_NAME = /^(.+?) (?:已收到消息,本轮还没有回复|本轮未送达|本轮未取得回复|本轮可能已送达,未确认)。$/u /** Which member a 「X 本轮…」 notice is about, and which message it should answer again. */ export function findRetryTarget(room: Pick, noticeId: string): RetryTarget | undefined { @@ -60,7 +61,7 @@ function withoutFailure(message: RoomMessage, botId: string): RoomMessage { } /** GOXF: the state shown under a human message, like a one-to-one bubble's DeliveryState. */ -export type RoomDelivery = 'replying' | 'sent' | 'failed' | 'no-reply' | 'partial' | undefined +export type RoomDelivery = 'replying' | 'sent' | 'failed' | 'uncertain' | 'no-reply' | 'partial' | undefined export function roomDeliveryState( messages: ReadonlyArray, @@ -76,8 +77,9 @@ export function roomDeliveryState( const failures = message.failures ?? [] if (failures.length) { if (replied) return 'partial' - const delivered = failures.every((f) => f.delivered ?? (f.error === NO_REPLY_ERROR || /送达|已收到/.test(f.error))) - return delivered ? 'no-reply' : 'failed' + const kinds = failures.map((f) => failureKind(f, NO_REPLY_ERROR)) + if (kinds.every((k) => k === 'received')) return 'no-reply' + return kinds.includes('not-sent') ? 'failed' : 'uncertain' } if (isLatest && speaking) return 'replying' return replied ? 'sent' : undefined diff --git a/src/renderer/src/rooms/roomStore.ts b/src/renderer/src/rooms/roomStore.ts index 2ba27238..392836e3 100644 --- a/src/renderer/src/rooms/roomStore.ts +++ b/src/renderer/src/rooms/roomStore.ts @@ -38,6 +38,7 @@ import { normalizeMemberRoles, normalizeSharedContext, normalizeSharedSkills, ro import { clampRelayHops, storedWorkflow, workflowOf } from './roomWorkflow' import { runRoomWorkflow, type WorkflowDeps, type WorkflowTurn } from './roomWorkflowRun' import { selectRoomsBacking, type RoomsBacking } from './roomFileBacking' +import { failedSendKind, roomFailureNotice, type RoomDeliveryKind } from './roomDeliveryKind' export interface RoomTurnProgress { turn: number @@ -701,15 +702,26 @@ const LATE_REPLY_WINDOW_MS = 20 * 60_000 /** GOXF: a turn that failed, and whether the member had already taken the message. */ export class RoomTurnError extends Error { - constructor(message: string, readonly delivered: boolean) { + readonly delivered: boolean + constructor(message: string, readonly kind: RoomDeliveryKind) { super(message) this.name = 'RoomTurnError' + this.delivered = kind === 'received' } } -/** The line posted in the group when a member did not answer: delivered and silent reads differently from not delivered. */ -export function roomFailureNotice(name: string, delivered: boolean): string { - return delivered ? `${name} 已收到消息,本轮还没有回复。` : `${name} 本轮未送达。` +export { roomFailureNotice } + +/** A failed turn's kind: a RoomTurnError says; anything else failed before the send. */ +function turnKind(error: unknown): RoomDeliveryKind { + return error instanceof RoomTurnError ? error.kind : 'not-sent' +} + +function failureRecord(member: Pick, error: string, kind: RoomDeliveryKind, noticeId: string) { + return { + botId: member.botId, name: member.name, error, delivered: kind === 'received', + ...(kind === 'uncertain' ? { uncertain: true } : {}), noticeId + } } /** @@ -987,7 +999,7 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe const text = joinReplyParts([...replies.values()], postedBodies(roomById(room.id)?.messages ?? [], member.botId)) if (!text && !media.length && widgets.empty) { watchLateReply(room.id, member, adapter, conversationId, trigger.id) - throw new RoomTurnError(NO_REPLY_ERROR, true) + throw new RoomTurnError(NO_REPLY_ERROR, 'received') } const resolvedSessionId = receipt.sessionId || sessionId // Upstream #89: a Grok [FINAL] in its own last bubble still ends the round, keeping the bubbles before it. @@ -1002,9 +1014,10 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe } catch (error) { if (signal.aborted || error instanceof RoomTurnError) throw error // An adapter's 'no-reply' means the platform took the message even when onAccepted never fired. - const delivered = accepted || (error instanceof AdapterError && error.code === 'no-reply') - if (delivered) watchLateReply(room.id, member, adapter, conversationId, trigger.id) - throw new RoomTurnError(turnErrorText(error, signal.aborted), delivered) + const kind = accepted || (error instanceof AdapterError && error.code === 'no-reply') ? 'received' : failedSendKind(error) + // A message that may have arrived can still be answered: keep listening for it too. + if (kind !== 'not-sent') watchLateReply(room.id, member, adapter, conversationId, trigger.id) + throw new RoomTurnError(turnErrorText(error, signal.aborted), kind) } finally { unsubscribe() clearRoomLive(room.id, member.botId) @@ -1169,11 +1182,11 @@ function workflowDeps(id: string, trigger: RoomMessage, signal: AbortSignal): Wo fail: (member, error) => { if (signal.aborted) return const detail = error instanceof Error ? error.message : String(error) - const delivered = error instanceof RoomTurnError && error.delivered + const kind = turnKind(error) const notice: RoomMessage = { - id: createId('post'), author: 'BotArk', notice: true, text: roomFailureNotice(member.name, delivered), createdAt: Date.now() + id: createId('post'), author: 'BotArk', notice: true, text: roomFailureNotice(member.name, kind), createdAt: Date.now() } - const failure = { botId: member.botId, name: member.name, error: detail, delivered, noticeId: notice.id } + const failure = failureRecord(member, detail, kind, notice.id) update(id, (r) => ({ ...r, messages: [...r.messages.map((m) => m.id === trigger.id @@ -1335,14 +1348,15 @@ export async function submitBrief( if (isCoordinator) throw error failed.add(member.botId) const detail = error instanceof Error ? error.message : String(error) - const delivered = error instanceof RoomTurnError && error.delivered + const kind = turnKind(error) + const delivered = kind === 'received' const notice: RoomMessage = { id: createId('post'), author: 'BotArk', notice: true, - text: roomFailureNotice(member.name, delivered), createdAt: Date.now() + text: roomFailureNotice(member.name, kind), createdAt: Date.now() } // GOXF: a human message shows who did not answer under itself, with 再发一次. if (isHumanRoomMessage(next.trigger)) { - const failure = { botId: member.botId, name: member.name, error: detail, delivered, noticeId: notice.id } + const failure = failureRecord(member, detail, kind, notice.id) update(id, (r) => ({ ...r, messages: r.messages.map((m) => m.id === next.trigger.id diff --git a/src/renderer/src/rooms/rooms.test.ts b/src/renderer/src/rooms/rooms.test.ts index ee7381f3..f75e7aa6 100644 --- a/src/renderer/src/rooms/rooms.test.ts +++ b/src/renderer/src/rooms/rooms.test.ts @@ -524,14 +524,15 @@ it('continues queued participants after a failed turn without retrying the faile fixture('auto', async (msg) => { calls.push(msg.accountId) if (msg.accountId === 'Muse') throw new Error('transport timeout') - expect(msg.text).toContain('Muse 本轮未送达。') + // GOXF: a timeout after the send may have reached Muse, so it is not called undelivered. + expect(msg.text).toContain('Muse 本轮可能已送达,未确认。') return '@Muse retry' }) await submitBrief('room', '@Muse @Dot review') expect(calls).toEqual(['Muse', 'Dot']) // GOXF: the failure sits on the human message (with 再发一次), not as a red room error. const brief = useRooms.getState().rooms[0]!.messages[0]! - expect(brief.failures).toEqual([expect.objectContaining({ botId: 'Muse', name: 'Muse', error: 'transport timeout', delivered: false })]) + expect(brief.failures).toEqual([expect.objectContaining({ botId: 'Muse', name: 'Muse', error: 'transport timeout', delivered: false, uncertain: true })]) expect(useRooms.getState().errors.room).toBeUndefined() }) @@ -600,6 +601,46 @@ it('says a delivered turn without a reply was delivered instead of not sent', as expect(useRooms.getState().errors.room).toBeUndefined() }) +it('says a message that never left was not delivered, and keeps no uncertain mark', async () => { + fixture('manual', async () => '') + vi.spyOn(adapterRegistry, 'get').mockReturnValue({ getStatus: () => 'online', + onMessage: () => () => {}, + sendMessage: async (): Promise => { throw new AdapterError('not-connected', '未连接') } + } as unknown as PlatformAdapter) + await submitBrief('room', '@Muse review') + const room = useRooms.getState().rooms[0]! + expect(room.messages.at(-1)?.text).toBe('Muse 本轮未送达。') + expect(room.messages[0]!.failures).toEqual([expect.objectContaining({ botId: 'Muse', delivered: false })]) + expect(room.messages[0]!.failures![0]).not.toHaveProperty('uncertain') +}) + +it('says a send that timed out before the platform confirmed may have arrived, and still posts a late reply', async () => { + vi.useFakeTimers() + try { + fixture('manual', async () => '') + const listeners = new Set<(msg: IncomingMessage) => void>() + let turn = '' + vi.spyOn(adapterRegistry, 'get').mockReturnValue({ getStatus: () => 'online', + onMessage: (listener: (msg: IncomingMessage) => void) => { listeners.add(listener); return () => listeners.delete(listener) }, + sendMessage: async (m: OutgoingMessage): Promise => { + turn = m.conversationId + throw new AdapterError('timeout', '等待确认超时') + } + } as unknown as PlatformAdapter) + await submitBrief('room', '@Muse review') + let state = useRooms.getState().rooms[0]! + expect(state.messages.at(-1)?.text).toBe('Muse 本轮可能已送达,未确认。') + expect(state.messages[0]!.failures).toEqual([expect.objectContaining({ botId: 'Muse', delivered: false, uncertain: true })]) + for (const listener of listeners) listener({ id: 'late', accountId: 'Muse', conversationId: turn, text: 'late answer', createdAt: 2 } as IncomingMessage) + vi.advanceTimersByTime(3_000) + state = useRooms.getState().rooms[0]! + expect(state.messages[0]!.failures).toEqual([]) + expect(state.messages.map((m) => m.text)).toEqual(['@Muse review', 'late answer']) + } finally { + vi.useRealTimers() + } +}) + it('treats an adapter no-reply error as delivered', async () => { fixture('manual', async () => '') vi.spyOn(adapterRegistry, 'get').mockReturnValue({ getStatus: () => 'online',