diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fb6626ee3..229774de30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ WeChat original voice can be prepared for playback, native quotes and retained l ### Added +- An app's conversation list in **Edit identity** is now manageable: conversations sort into **Waiting**, **Active**, **Muted** and **Blocked**. **Mute** keeps messages in the Inbox without waking the Bot, **Rules** edits one group's collection and wake, and **Block** (confirmed) cancels unsent replies and keeps the conversation out even after restart or unbinding and rebinding; **Allow again** starts fresh with no backfill. A new **New conversations** setting chooses **Admit automatically** or **Ask me first**; waiting conversations keep only names and counts, never message text. At most 20 new conversations per app join automatically each hour and 500 stay active; beyond that they wait with the reason shown ([#1109](https://github.com/BotHarness/BotHarness/issues/1109), [External identities guide](docs/channel-sidebar/external-identities.md)). + - Slack, Discord and personal WeChat bind in one step too: after **Bind app**, DMs to a Slack or Discord app and @mentions of it in channels go straight to the Bot's Inbox with replies in the same thread; personal WeChat admits only DMs from the person who scanned it, never other contacts or groups. The bind dialog shows the real receiving state on every platform, and recorded group conversations follow the platform's global group intake and wake defaults ([#1112](https://github.com/BotHarness/BotHarness/issues/1112), [External identities guide](docs/channel-sidebar/external-identities.md)). - Binding a Lark app is now enough to send and receive: **Bind identity** under External identities becomes **Bind app**, and once bound, DMs to the app and @mentions of it in groups go straight to this Bot’s Inbox, with the Bot replying in place. No saved delivery target, conversation authorization or reception switch is needed. The first message records its conversation; the app row shows a conversation count and opens a read-only conversation list, and the bind dialog shows the real receiving state. `/pair` still goes to pairing, existing authorizations behave as before, and every bound app upgrades to admitting new conversations automatically ([#1108](https://github.com/BotHarness/BotHarness/issues/1108), [ADR-0142](docs/adr/0142-a-bound-app-admits-its-direct-messages-and-mentions.md), [External identities guide](docs/channel-sidebar/external-identities.md)). diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 8913b7e6e0..433a8d34fa 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -9,6 +9,8 @@ ### Added +- **编辑外部身份** 里的会话列表现在可以管理:会话分为 **等待处理**、**活跃**、**已静音**、**已屏蔽**。**静音** 后消息照常进入收件箱但不唤醒 Bot,**规则** 单独调整一个群的收件和唤醒,**屏蔽**(需确认)会取消未发出的回复,重启、解绑再绑定后依然有效;**再次允许** 从下一条消息重新开始,不补收。新增 **新会话** 设置,可选 **自动接收** 或 **先问我**;等待中的会话只记录名称和次数,不保存消息内容。每个应用每小时最多自动加入 20 个新会话、最多 500 个活跃会话,超出时进入等待并显示原因([#1109](https://github.com/BotHarness/BotHarness/issues/1109),[外部身份教程](docs/channel-sidebar/external-identities.md))。 + - Slack、Discord 和个人微信也能一步绑定:**绑定应用** 后,私聊 Slack 或 Discord 应用、或在频道里 @ 它,消息直接进入 Bot 收件箱并在原话题回复;个人微信只接收扫码者本人的私聊,其他联系人和群不会进入。绑定弹窗对所有平台显示真实接收状态,已记下的群会话跟随平台全局默认的群收件和唤醒设置([#1112](https://github.com/BotHarness/BotHarness/issues/1112),[外部身份教程](docs/channel-sidebar/external-identities.md))。 - 绑定飞书应用就能收发:外部身份里的 **绑定身份** 改为 **绑定应用**,绑定后私聊这个应用、或在群里 @ 它,消息直接进入这个 Bot 的收件箱,Bot 在原会话回复,不需要保存投递目标、授权会话或打开收件开关。第一条消息会自动记下会话,应用行显示会话数,点开可查看只读会话列表;绑定后弹窗显示真实的接收状态。`/pair` 仍由配对处理,已有授权的行为不变,所有已绑定应用升级后都默认自动接收新会话([#1108](https://github.com/BotHarness/BotHarness/issues/1108),[ADR-0142](docs/adr/0142-a-bound-app-admits-its-direct-messages-and-mentions.md),[外部身份教程](docs/channel-sidebar/external-identities.md))。 diff --git a/apps/docs/public/guides/channel-sidebar/19b-app-conversations-en.webp b/apps/docs/public/guides/channel-sidebar/19b-app-conversations-en.webp deleted file mode 100644 index 42960c0b92..0000000000 Binary files a/apps/docs/public/guides/channel-sidebar/19b-app-conversations-en.webp and /dev/null differ diff --git a/apps/docs/public/guides/channel-sidebar/19b-app-conversations-zh.webp b/apps/docs/public/guides/channel-sidebar/19b-app-conversations-zh.webp deleted file mode 100644 index 7dd4022e27..0000000000 Binary files a/apps/docs/public/guides/channel-sidebar/19b-app-conversations-zh.webp and /dev/null differ diff --git a/apps/docs/public/guides/channel-sidebar/19c-app-conversations-en.webp b/apps/docs/public/guides/channel-sidebar/19c-app-conversations-en.webp new file mode 100644 index 0000000000..7c0200ca94 Binary files /dev/null and b/apps/docs/public/guides/channel-sidebar/19c-app-conversations-en.webp differ diff --git a/apps/docs/public/guides/channel-sidebar/19c-app-conversations-zh.webp b/apps/docs/public/guides/channel-sidebar/19c-app-conversations-zh.webp new file mode 100644 index 0000000000..443db10b44 Binary files /dev/null and b/apps/docs/public/guides/channel-sidebar/19c-app-conversations-zh.webp differ diff --git a/docs/assets/pr/1109-conversation-list/README.md b/docs/assets/pr/1109-conversation-list/README.md new file mode 100644 index 0000000000..3611b1079f --- /dev/null +++ b/docs/assets/pr/1109-conversation-list/README.md @@ -0,0 +1,17 @@ +# #1109 Conversation list: mute, rules, block, allow again + +Captured from a real DSH Host (0.2.0-rc.1) with the simulated Lark provider and the real OpenCode Go model. Each state was produced through the Host commands, not injected client data. + +## Before + +The app's **Conversations** list was read-only. A conversation could not be muted, given its own rules or blocked, and every new DM or @mention was admitted. + +## After + +| | zh light | en dark | +| ----------------- | -------------------------------- | ------------------------------- | +| Four groups | ![](conversations-zh-light.webp) | ![](conversations-en-dark.webp) | +| Block confirm | ![](block-confirm-zh-light.webp) | ![](block-confirm-en-dark.webp) | +| Rules for a group | ![](rules-zh-light.webp) | ![](rules-en-dark.webp) | + +The remaining light/dark and zh/en variants are in this folder. diff --git a/docs/assets/pr/1109-conversation-list/block-confirm-en-dark.webp b/docs/assets/pr/1109-conversation-list/block-confirm-en-dark.webp new file mode 100644 index 0000000000..3883b3df6f Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/block-confirm-en-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/block-confirm-en-light.webp b/docs/assets/pr/1109-conversation-list/block-confirm-en-light.webp new file mode 100644 index 0000000000..d01a8ca999 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/block-confirm-en-light.webp differ diff --git a/docs/assets/pr/1109-conversation-list/block-confirm-zh-dark.webp b/docs/assets/pr/1109-conversation-list/block-confirm-zh-dark.webp new file mode 100644 index 0000000000..d9eb01836b Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/block-confirm-zh-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/block-confirm-zh-light.webp b/docs/assets/pr/1109-conversation-list/block-confirm-zh-light.webp new file mode 100644 index 0000000000..0fec1e5224 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/block-confirm-zh-light.webp differ diff --git a/docs/assets/pr/1109-conversation-list/conversations-en-dark.webp b/docs/assets/pr/1109-conversation-list/conversations-en-dark.webp new file mode 100644 index 0000000000..a185c4c96d Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/conversations-en-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/conversations-en-light.webp b/docs/assets/pr/1109-conversation-list/conversations-en-light.webp new file mode 100644 index 0000000000..7c0200ca94 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/conversations-en-light.webp differ diff --git a/docs/assets/pr/1109-conversation-list/conversations-zh-dark.webp b/docs/assets/pr/1109-conversation-list/conversations-zh-dark.webp new file mode 100644 index 0000000000..578d8b400e Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/conversations-zh-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/conversations-zh-light.webp b/docs/assets/pr/1109-conversation-list/conversations-zh-light.webp new file mode 100644 index 0000000000..443db10b44 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/conversations-zh-light.webp differ diff --git a/docs/assets/pr/1109-conversation-list/rules-en-dark.webp b/docs/assets/pr/1109-conversation-list/rules-en-dark.webp new file mode 100644 index 0000000000..9aa53afc78 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/rules-en-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/rules-en-light.webp b/docs/assets/pr/1109-conversation-list/rules-en-light.webp new file mode 100644 index 0000000000..9b929a5126 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/rules-en-light.webp differ diff --git a/docs/assets/pr/1109-conversation-list/rules-zh-dark.webp b/docs/assets/pr/1109-conversation-list/rules-zh-dark.webp new file mode 100644 index 0000000000..a82fb22091 Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/rules-zh-dark.webp differ diff --git a/docs/assets/pr/1109-conversation-list/rules-zh-light.webp b/docs/assets/pr/1109-conversation-list/rules-zh-light.webp new file mode 100644 index 0000000000..740be75dcb Binary files /dev/null and b/docs/assets/pr/1109-conversation-list/rules-zh-light.webp differ diff --git a/docs/channel-sidebar/external-identities.md b/docs/channel-sidebar/external-identities.md index c6d5844808..7d05677710 100644 --- a/docs/channel-sidebar/external-identities.md +++ b/docs/channel-sidebar/external-identities.md @@ -33,17 +33,37 @@ A `/pair` command doesn’t enter the Inbox. [IM administrator pairing](/docs/la ![Ready state after binding an app](/guides/channel-sidebar/18b-bind-app-ready-en.webp) -## See the conversations +## Manage the conversations -The first DM or @mention that reaches the Inbox records its conversation. Click the app row and look under **Conversations** in the **Edit identity** dialog: each conversation shows its name (the person’s name for a DM, the group ID for a group), DM or Group, and the last message time. The list is read-only for now; mute, reception rules and block come in a later release. +The first DM or @mention that reaches the Inbox records its conversation. Click the app row and look under **Conversations** in the **Edit identity** dialog. Each conversation shows its name (the person’s name for a DM, the group ID for a group), DM or Group, and the last message time, sorted into four groups: -![The app’s conversation list](/guides/channel-sidebar/19b-app-conversations-en.webp) +| Group | What it means | Actions | +| ----------- | ------------------------------------------------------------------------------------- | ----------------------------------------- | +| **Waiting** | A new conversation that hasn’t been let in yet, with the reason and its message count | **Allow**, **Block** | +| **Active** | Messages reach the Inbox and wake the Bot | **Mute**, **Rules** (groups), **Block** | +| **Muted** | Messages still reach the Inbox but never wake the Bot; you can still reply | **Unmute**, **Rules** (groups), **Block** | +| **Blocked** | Messages are dropped and the conversation never comes back on its own | **Allow again** | + +- **Rules** opens the same collection and wake settings as a group in External connectors, for this one group. +- **Block** asks for confirmation. Replies that haven’t been sent yet are cancelled, and old messages can no longer be replied to. The block stays across restarts and even after you unbind and bind the same app to this Bot again. +- **Allow again** starts a fresh conversation from the next message. Messages sent while it was blocked are not backfilled, and its old rules are not restored. + +### New conversations + +**New conversations** in the same dialog decides what happens the first time someone DMs the app or @mentions it in a new group (personal WeChat only has its owner, so it has no such setting): + +- **Admit automatically** (default): the message goes straight to the Inbox. +- **Ask me first**: the conversation waits under **Waiting**. Only its name, first and last seen time and message count are kept, never the message text. After **Allow**, the next message is admitted. + +To keep a busy app from flooding the Inbox, at most 20 new conversations per app join automatically each hour, and an app holds at most 500 active conversations. Past either limit, new conversations wait under **Waiting** and the row says which limit was hit. **Waiting** keeps the 200 most recent conversations per app. + +![The app’s conversation list](/guides/channel-sidebar/19c-app-conversations-en.webp) ## Edit, reconnect or unbind Click an app row to open **Edit identity**. -1. Change the **Local display name** or the identity’s default behavior after binding: inherit the global default, or choose a custom value. +1. Change the **Local display name**, the identity’s default behavior after binding (inherit the global default, or choose a custom value), or **New conversations**. 2. Click **Save identity**. 3. **Reconnect** revalidates the same app and its existing conversations. A changed app requires unbinding and binding again. 4. **Unbind** (red) asks for confirmation and lists the conversations it invalidates. After unbinding, the app stops delivering to this Bot and old conversations can no longer be replied to. Accepted messages and source history are retained; the shared app and its credentials are not removed. diff --git a/docs/channel-sidebar/external-identities.zh.md b/docs/channel-sidebar/external-identities.zh.md index d5b40fb59b..4f5b4b74ba 100644 --- a/docs/channel-sidebar/external-identities.zh.md +++ b/docs/channel-sidebar/external-identities.zh.md @@ -33,17 +33,37 @@ Slack 和 Discord 同样适用:私聊应用、或在它所在的频道里 @ ![绑定应用后的就绪状态](/guides/channel-sidebar/18b-bind-app-ready-zh.webp) -## 查看会话 +## 管理会话 -第一条进入收件箱的私聊或 @ 消息会自动记下这个会话。点击应用行,在 **编辑外部身份** 弹窗的 **会话** 中可以看到这个应用的全部会话:名称(私聊显示对方名字,群聊显示群 ID)、私聊或群聊、最近消息时间。这个列表目前只读;静音、调整接收规则和屏蔽会在后续版本加入。 +第一条进入收件箱的私聊或 @ 消息会自动记下这个会话。点击应用行,在 **编辑外部身份** 弹窗的 **会话** 中可以看到这个应用的全部会话:名称(私聊显示对方名字,群聊显示群 ID)、私聊或群聊、最近消息时间,分成四组: -![应用的会话列表](/guides/channel-sidebar/19b-app-conversations-zh.webp) +| 分组 | 含义 | 操作 | +| ------------ | ------------------------------------------ | -------------------------------------- | +| **等待处理** | 还没放行的新会话,显示原因和消息次数 | **允许**、**屏蔽** | +| **活跃** | 消息进入收件箱并唤醒 Bot | **静音**、**规则**(群)、**屏蔽** | +| **已静音** | 消息照常进入收件箱,但不唤醒 Bot;仍可回复 | **取消静音**、**规则**(群)、**屏蔽** | +| **已屏蔽** | 消息直接丢弃,会话不会自己回来 | **再次允许** | + +- **规则** 打开与「外部连接器」中群相同的收件和唤醒设置,只作用于这一个群。 +- **屏蔽** 需要确认。尚未发出的回复会取消,旧消息也不能再回复。屏蔽在重启后仍然有效,即使解绑后把同一个应用重新绑定到这个 Bot 也一样。 +- **再次允许** 从下一条消息开始重新接收。屏蔽期间的消息不会补收,旧的规则也不会恢复。 + +### 新会话 + +同一弹窗里的 **新会话** 决定有人第一次私聊这个应用、或在新群里 @ 它时怎么处理(个人微信只有扫码者本人,没有这个设置): + +- **自动接收**(默认):消息直接进入收件箱。 +- **先问我**:会话先放在 **等待处理**,只记录名称、首次和最近出现时间以及消息次数,不保存消息内容;点 **允许** 后,从下一条消息开始接收。 + +为防止繁忙的应用刷屏,每个应用每小时最多自动加入 20 个新会话,活跃会话最多 500 个。超过任一上限,新会话进入 **等待处理**,并在行内说明是哪一个上限。**等待处理** 每个应用最多保留最近的 200 个会话。 + +![应用的会话列表](/guides/channel-sidebar/19c-app-conversations-zh.webp) ## 编辑、重新连接或解绑 点击应用行,打开 **编辑外部身份**。 -1. 修改 **本地显示名称**,或修改 **绑定后的身份默认行为**:继承全局默认,或自定义。 +1. 修改 **本地显示名称**、**绑定后的身份默认行为**(继承全局默认,或自定义),或 **新会话**。 2. 点击 **保存身份**。 3. **重新连接** 会重新验证同一应用与已有会话。应用已变更时,需要解绑后重新绑定。 4. **解绑**(红色)需要确认,并列出将失效的会话。解绑后这个应用不再给 Bot 送消息,旧会话也不能再回复;已收消息和来源历史保留,不会删除共享应用或凭据。 diff --git a/packages/client/src/client/actions.ts b/packages/client/src/client/actions.ts index 35cc216b7c..b388df7fa5 100644 --- a/packages/client/src/client/actions.ts +++ b/packages/client/src/client/actions.ts @@ -38,6 +38,7 @@ import { } from './last-view.js'; import { defaultStorage, type ConfigStorage } from './roster-config.js'; import type { GroupReceptionInput } from '../../../core/src/messaging/group-policy.js'; +import type { MessagingConversationInput } from '../../../core/src/messaging/conversations.js'; import { publishWorkspaceGrantChange } from './workspace-grant-events.js'; import type { ExternalSource } from '../../../core/src/messaging/inbound.js'; import type { @@ -51,6 +52,7 @@ import { manageChannelBridge, loadMessagingSnapshot, manageMessagingIdentity, + manageMessagingConversation, loadMessagingTargets, authorizeMessaging, revokeMessaging, @@ -269,6 +271,7 @@ export interface BridgeActions { approvalRetry(slug: string, id: string): Promise; pairingReview(slug: string, input: PairingReviewInput): Promise; messagingIdentity(slug: string, input: MessagingIdentityInput): Promise; + messagingConversation(slug: string, input: MessagingConversationInput): Promise; messagingSnapshot(slug: string): Promise; messagingTargets(providerId: string, accountRef: string): Promise; messagingAuthorize(input: { @@ -1807,6 +1810,7 @@ export function createActions( approvalRetry: (slug, id) => retryApprovalNotification(call, slug, id), pairingReview: (slug, input) => reviewPairing(call, slug, input), messagingIdentity: (slug, input) => manageMessagingIdentity(call, slug, input), + messagingConversation: (slug, input) => manageMessagingConversation(call, slug, input), messagingSnapshot: (slug) => loadMessagingSnapshot(call, slug), messagingTargets: (providerId, accountRef) => loadMessagingTargets(call, providerId, accountRef), diff --git a/packages/client/src/client/bridge.ts b/packages/client/src/client/bridge.ts index 852130eedb..dd6d0f9964 100644 --- a/packages/client/src/client/bridge.ts +++ b/packages/client/src/client/bridge.ts @@ -49,6 +49,7 @@ import type { OverviewUsage } from '../../../core/src/bridge/methods.js'; import type { UsageOverviewPeriod } from '../../../core/src/usage/overview.js'; import type { ChannelActivityToday } from '../../../core/src/channels/activity-today.js'; import type { GroupReceptionInput } from '../../../core/src/messaging/group-policy.js'; +import type { MessagingConversationInput } from '../../../core/src/messaging/conversations.js'; import type { ActivityOverview } from '../../../core/src/bridge/methods.js'; import type { ExternalSource } from '../../../core/src/messaging/inbound.js'; import type { HumanAssignmentContext } from '../../../core/src/runtime/assignment-human-context.js'; @@ -3651,6 +3652,13 @@ export async function setMessagingGroupPolicy( ): Promise { await unwrap(call, 'messagingGroupPolicy', { slug, grantId, policy }); } +export async function manageMessagingConversation( + call: BridgeCall, + slug: string, + input: MessagingConversationInput, +): Promise { + await unwrap(call, 'messagingConversation', { slug, input }); +} export async function setMessagingReceive( call: BridgeCall, slug: string, diff --git a/packages/client/src/client/external-conversations.tsx b/packages/client/src/client/external-conversations.tsx new file mode 100644 index 0000000000..25067258b4 --- /dev/null +++ b/packages/client/src/client/external-conversations.tsx @@ -0,0 +1,233 @@ +import { useState, type ReactElement, type ReactNode } from 'react'; +import { Button } from '@deepseek-ai/dsh-client-ui-primitives'; +import type { MessagingConversationInput } from '../../../core/src/messaging/conversations.js'; +import type { GroupReceptionInput } from '../../../core/src/messaging/group-policy.js'; +import type { MessagingIdentityView } from '../../../core/src/messaging/identity.js'; +import type { MessagingSnapshot } from '../../../core/src/messaging/outbound.js'; +import type { BotHarnessTranslate } from './locale.js'; +import { GroupReceptionSettings } from './messaging-grant.js'; +import { SidebarCardList, SidebarCardRow } from './sidebar-card.js'; + +type Grant = MessagingSnapshot['grants'][number]; +type Held = NonNullable[number]; +type Blocked = NonNullable[number]; + +const LIMITS = { 'hourly-limit': 20, 'active-limit': 500 } as const; + +export function ExternalConversations({ + identity, + snapshot, + busy, + t, + change, + rules, +}: { + identity: MessagingIdentityView; + snapshot: MessagingSnapshot | undefined; + busy: boolean; + t: BotHarnessTranslate; + change(input: MessagingConversationInput): Promise; + rules(grantId: string, input: GroupReceptionInput): Promise; +}): ReactElement { + const [open, setOpen] = useState(); + const [confirm, setConfirm] = useState(); + const time = (value: string) => new Date(value).toLocaleString(); + const entries = (snapshot?.grants ?? []).filter( + (g) => g.bindingId === identity.id && !g.revokedAt && g.receiveScope !== undefined, + ); + const active = entries.filter((g) => !g.muted); + const muted = entries.filter((g) => g.muted); + const waiting = (snapshot?.heldConversations ?? []).filter((h) => h.bindingId === identity.id); + const blocked = (snapshot?.blockedConversations ?? []).filter((b) => b.bindingId === identity.id); + const kind = (value: 'dm' | 'group') => + t(value === 'dm' ? 'identity.kind.dm' : 'identity.kind.group'); + const icon = (value: 'dm' | 'group') => (value === 'dm' ? 'user' : 'users'); + const small = (label: string, onClick: () => void, danger = false, pressed?: boolean) => ( + + ); + const confirmBlock = (key: string, name: string, block: () => void): ReactNode => + confirm === key ? ( +
+

{t('conversation.blockConfirm', { name })}

+
+ + +
+
+ ) : undefined; + const entryRow = (grant: Grant) => { + const scope = grant.receiveScope!; + const name = grant.targetName || scope.conversationId; + const detail = + confirmBlock( + grant.id, + name, + () => void change({ kind: 'block', grantId: grant.id, expectedRevision: grant.revision }), + ) ?? + (open === grant.id && grant.groupPolicy ? ( + rules(grant.id, input)} + /> + ) : undefined); + return ( + + {small( + t(grant.muted ? 'conversation.unmute' : 'conversation.mute'), + () => + void change({ + kind: 'mute', + grantId: grant.id, + expectedRevision: grant.preferenceRevision ?? 0, + muted: !grant.muted, + }), + )} + {grant.groupPolicy + ? small( + t('conversation.rules'), + () => { + setConfirm(undefined); + setOpen(open === grant.id ? undefined : grant.id); + }, + false, + open === grant.id, + ) + : null} + {small(t('conversation.block'), () => setConfirm(grant.id), true)} + + } + detail={detail} + /> + ); + }; + const heldRow = (held: Held) => { + const key = `held:${held.conversation.kind}:${held.conversation.id}`; + const reason = + held.reason === 'ask' + ? t('conversation.reason.ask') + : t(`conversation.reason.${held.reason}`, { count: LIMITS[held.reason] }); + return ( + {reason}} + meta={[ + kind(held.conversation.kind), + t('conversation.seen', { count: held.count, time: time(held.lastSeenAt) }), + ].join(' · ')} + trailing={ + <> + {small( + t('conversation.allow'), + () => + void change({ + kind: 'allow', + bindingId: identity.id, + conversation: held.conversation, + from: 'held', + expectedRevision: held.revision, + }), + )} + {small(t('conversation.block'), () => setConfirm(key), true)} + + } + detail={confirmBlock( + key, + held.name, + () => + void change({ + kind: 'block-held', + bindingId: identity.id, + conversation: held.conversation, + expectedRevision: held.revision, + }), + )} + /> + ); + }; + const blockedRow = (block: Blocked) => ( + + void change({ + kind: 'allow', + bindingId: identity.id, + conversation: block.conversation, + from: 'blocked', + expectedRevision: block.revision, + }), + )} + /> + ); + const group = (label: string, rows: ReactElement[]) => + rows.length ? ( +
+ + {label} {rows.length} + + {rows} +
+ ) : null; + if (!entries.length && !waiting.length && !blocked.length) + return

{t('identity.conversationsEmpty')}

; + return ( + <> + {group(t('conversation.waiting'), waiting.map(heldRow))} + {group(t('conversation.active'), active.map(entryRow))} + {group(t('conversation.muted'), muted.map(entryRow))} + {group(t('conversation.blocked'), blocked.map(blockedRow))} + + ); +} diff --git a/packages/client/src/client/external-entries.tsx b/packages/client/src/client/external-entries.tsx index 33ca83f238..4f21c70020 100644 --- a/packages/client/src/client/external-entries.tsx +++ b/packages/client/src/client/external-entries.tsx @@ -60,6 +60,14 @@ function IdentitiesForBot({ await actions.messagingIdentity(slug, input); await refresh(); }} + conversation={async (input) => { + await actions.messagingConversation(slug, input); + await refresh(); + }} + rules={async (grantId, input) => { + await actions.messagingGroupPolicy(slug, grantId, input); + await refresh(); + }} /> ; + conversation(input: MessagingConversationInput): Promise; + rules(grantId: string, input: GroupReceptionInput): Promise; }): ReactElement { const [mode, setMode] = useState<'bind' | 'bound' | 'edit' | 'reconnect' | 'unbind'>(); const [selected, setSelected] = useState(); const [accountKey, setAccountKey] = useState(''); const [name, setName] = useState(''); const [inheritEnabled, setInheritEnabled] = useState(false); + const [newConversations, setNewConversations] = useState<'auto' | 'ask'>('auto'); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const identities = snapshot?.identities ?? []; @@ -52,6 +60,7 @@ export function ExternalIdentityList({ setSelected(row); setName(row?.name ?? ''); setInheritEnabled(row?.enabledInheritance === 'inherit'); + setNewConversations(row?.newConversations ?? 'auto'); setAccountKey(''); }; const close = () => { @@ -71,9 +80,11 @@ export function ExternalIdentityList({ : ''; setError( t( - code === 'identity-stale' || code === 'identity-changed' + code === 'identity-stale' || code === 'identity-changed' || code === 'conversation-stale' ? 'identity.stale' - : 'identity.failed', + : code === 'conversation-limit' + ? 'conversation.limit' + : 'identity.failed', ), ); } finally { @@ -99,6 +110,7 @@ export function ExternalIdentityList({ name, enabled: selected.enabled, inheritEnabled, + newConversations, ...(selected.defaultRevision !== undefined ? { expectedDefaultRevision: selected.defaultRevision } : {}), @@ -322,38 +334,43 @@ export function ExternalIdentityList({ ]} /> + {selected.platform === 'weixin' ? null : ( +
+ + {t('identity.newConversations')} + + + setNewConversations(value === 'ask' ? 'ask' : 'auto')} + options={[ + { value: 'auto', label: t('identity.newConversations.auto') }, + { value: 'ask', label: t('identity.newConversations.ask') }, + ]} + /> +
+ )} ) : null} {mode === 'edit' ? (
{t('identity.conversations')} - {conversations(selected).length ? ( - - {conversations(selected).map((entry) => ( - - ))} - - ) : ( -

{t('identity.conversationsEmpty')}

- )} + operate(() => conversation(input))} + rules={(grantId, input) => operate(() => rules(grantId, input))} + />
) : null} {mode === 'reconnect' ?

{t('identity.reconnectHint')}

: null} diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index 82f5b5651c..a995282ec4 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -817,6 +817,30 @@ export const zh = { 'identity.kind.dm': '私聊', 'identity.kind.group': '群聊', 'identity.lastMessage': '最近消息 {time}', + 'identity.newConversations': '新会话', + 'identity.newConversations.auto': '自动接收', + 'identity.newConversations.ask': '先问我', + 'identity.newConversationsHint': + '自动接收:新的私聊或 @ 直接进入收件箱。先问我:新会话先出现在「等待处理」,只记录会话名称和次数,不保存消息内容;允许后从下一条消息开始接收。', + 'conversation.active': '活跃', + 'conversation.muted': '已静音', + 'conversation.waiting': '等待处理', + 'conversation.blocked': '已屏蔽', + 'conversation.mute': '静音', + 'conversation.unmute': '取消静音', + 'conversation.rules': '规则', + 'conversation.block': '屏蔽', + 'conversation.allow': '允许', + 'conversation.allowAgain': '再次允许', + 'conversation.confirmBlock': '确认屏蔽', + 'conversation.blockConfirm': + '屏蔽「{name}」后,它的新消息不会进入收件箱,也不会自动重新加入,解绑再绑定也一样;尚未发出的回复会取消。之后可以「再次允许」,但屏蔽期间的消息不会补收。', + 'conversation.reason.ask': '等你允许', + 'conversation.reason.hourly-limit': '已达每小时 {count} 个新会话上限', + 'conversation.reason.active-limit': '已达 {count} 个活跃会话上限', + 'conversation.seen': '{count} 条消息 · 最近 {time}', + 'conversation.blockedAt': '屏蔽于 {time}', + 'conversation.limit': '活跃会话已达上限。请先屏蔽不再需要的会话,再允许新的会话。', 'identity.ready': '已就绪:发给 {app} 的私聊和群里 @ 它的消息,现在会进入这个 Bot 的收件箱。', 'identity.connecting': '正在连接 {app}…', 'identity.offline': '{app} 暂时收不到消息。请在 IM 设置中检查它的连接状态。', @@ -2932,6 +2956,31 @@ My relationship with the Human, established lore and topics to avoid: [fill in]. 'identity.kind.dm': 'DM', 'identity.kind.group': 'Group', 'identity.lastMessage': 'Last message {time}', + 'identity.newConversations': 'New conversations', + 'identity.newConversations.auto': 'Admit automatically', + 'identity.newConversations.ask': 'Ask me first', + 'identity.newConversationsHint': + 'Admit automatically: new DMs and @mentions go straight to the Inbox. Ask me first: a new conversation waits under Waiting with only its name and message count, never the message text; once allowed, the next message is admitted.', + 'conversation.active': 'Active', + 'conversation.muted': 'Muted', + 'conversation.waiting': 'Waiting', + 'conversation.blocked': 'Blocked', + 'conversation.mute': 'Mute', + 'conversation.unmute': 'Unmute', + 'conversation.rules': 'Rules', + 'conversation.block': 'Block', + 'conversation.allow': 'Allow', + 'conversation.allowAgain': 'Allow again', + 'conversation.confirmBlock': 'Block conversation', + 'conversation.blockConfirm': + 'After blocking “{name}”, its new messages won’t reach the Inbox and it won’t come back on its own, even after unbinding and rebinding. Unsent replies are cancelled. You can Allow again later, but messages sent while blocked are not backfilled.', + 'conversation.reason.ask': 'Waiting for you', + 'conversation.reason.hourly-limit': 'Hit the limit of {count} new conversations per hour', + 'conversation.reason.active-limit': 'Hit the limit of {count} active conversations', + 'conversation.seen': '{count} message(s) · last {time}', + 'conversation.blockedAt': 'Blocked {time}', + 'conversation.limit': + 'Too many active conversations. Block ones you no longer need, then allow new ones.', 'identity.ready': 'Ready: DMs and @mentions to {app} now reach this Bot’s Inbox.', 'identity.connecting': 'Connecting {app}…', 'identity.offline': diff --git a/packages/client/src/client/messaging-grant.tsx b/packages/client/src/client/messaging-grant.tsx index 30cf59e15a..243928a8c5 100644 --- a/packages/client/src/client/messaging-grant.tsx +++ b/packages/client/src/client/messaging-grant.tsx @@ -530,7 +530,7 @@ export function MessagingGrantRow({ ); } -function GroupReceptionSettings({ +export function GroupReceptionSettings({ policy, verified, busy, diff --git a/packages/client/src/client/styles.ts b/packages/client/src/client/styles.ts index be5e80863c..08937866a5 100644 --- a/packages/client/src/client/styles.ts +++ b/packages/client/src/client/styles.ts @@ -2553,6 +2553,14 @@ html[data-botharness-motion='full'] .bh-skeleton-line { .bh-im-grant-body .bh-im-group-policy { grid-template-columns: minmax(0,1fr); } } .bh-im-danger-outline.bh-im-danger-outline { color: var(--dsw-alias-state-error-primary); } +.bh-im-danger-text.bh-im-danger-text { color: var(--dsw-alias-state-error-primary); } +.bh-conversation-group { display: grid; gap: 4px; } +.bh-conversation-group + .bh-conversation-group { margin-top: 8px; } +.bh-conversation-group-title { font-size: 12px; font-weight: 600; color: var(--dsw-alias-label-secondary); } +.bh-conversation-group-title small { font-weight: 400; margin-left: 2px; } +.bh-conversation-reason { font-size: 12px; color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary)); } +.bh-conversation-confirm { display: grid; gap: 8px; } +.bh-conversation-confirm p { margin: 0; } .bh-modal-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; width: 100%; justify-content: flex-end; } .bh-modal-footer > button { white-space: nowrap; } .bh-modal-footer-gap { flex: 1; } diff --git a/packages/client/test/bot-sidebar.test.ts b/packages/client/test/bot-sidebar.test.ts index 9770ff1a47..7bf156d161 100644 --- a/packages/client/test/bot-sidebar.test.ts +++ b/packages/client/test/bot-sidebar.test.ts @@ -144,6 +144,7 @@ function stubActions(): BridgeActions { approvalRetry: vi.fn(async () => {}), pairingReview: vi.fn(), messagingIdentity: vi.fn(), + messagingConversation: vi.fn(), messagingSnapshot: vi.fn(async () => ({ accounts: [], grants: [], intents: [] })), messagingTargets: vi.fn(async () => []), resolveWorkspaceGrantRequest: vi.fn(async () => undefined), diff --git a/packages/client/test/external-conversations.test.ts b/packages/client/test/external-conversations.test.ts new file mode 100644 index 0000000000..6c22203764 --- /dev/null +++ b/packages/client/test/external-conversations.test.ts @@ -0,0 +1,138 @@ +// @vitest-environment jsdom +import { act, createElement, type ButtonHTMLAttributes, type PropsWithChildren } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; +import type { MessagingSnapshot } from '../../core/src/messaging/outbound.js'; +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ + ...(await import('./primitive-mocks.js')).comboboxPrimitives(), + IconInfoOutlineRegular: () => null, + Tooltip: ({ children }: PropsWithChildren) => children, + Button: (props: ButtonHTMLAttributes) => createElement('button', props), + Input: (props: Record) => createElement('input', props), + Tag: ({ children }: PropsWithChildren) => createElement('span', null, children), + Modal: () => null, +})); +import { ExternalConversations } from '../src/client/external-conversations.js'; +import { zhTranslate } from '../src/client/locale.js'; + +const identity = { + id: 'binding', + botSlug: 'ada', + providerId: 'dsh-im/feishu', + platform: 'feishu', + accountRef: 'app', + fingerprint: 'a'.repeat(64), + name: 'QA Bot', + enabled: true, + revision: 2, + createdAt: '2026-10-07T00:00:00Z', + availability: 'available' as const, + newConversations: 'ask' as const, + grantCount: 2, + scopes: [], +}; + +const entry = (id: string, name: string, muted: boolean) => + ({ + id, + bindingId: 'binding', + targetName: name, + revision: 3, + preferenceRevision: muted ? 1 : undefined, + muted, + receiveScope: { kind: 'group', conversationId: `oc_${id}` }, + }) as unknown as MessagingSnapshot['grants'][number]; + +const snapshot: MessagingSnapshot = { + accounts: [], + identities: [identity], + grants: [entry('g1', 'Team', false), entry('g2', 'Noisy', true)], + intents: [], + heldConversations: [ + { + bindingId: 'binding', + conversation: { kind: 'dm', id: 'oc_new' }, + name: 'Stranger', + reason: 'hourly-limit', + firstSeenAt: '2026-10-07T00:00:00Z', + lastSeenAt: '2026-10-07T00:01:00Z', + count: 3, + revision: 1, + }, + ], + blockedConversations: [ + { + botSlug: 'ada', + fingerprint: 'a'.repeat(64), + bindingId: 'binding', + conversation: { kind: 'group', id: 'oc_spam' }, + name: 'Spam', + blockedAt: '2026-10-07T00:00:00Z', + revision: 2, + }, + ], +}; + +it('groups conversations, confirms Block before sending it, and sends revision-checked commands', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const change = vi.fn(async () => undefined); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + await act(async () => + root.render( + createElement(ExternalConversations, { + identity, + snapshot, + busy: false, + t: zhTranslate, + change, + rules: vi.fn(), + }), + ), + ); + const groups = [...container.querySelectorAll('section')].map((s) => [ + s.getAttribute('aria-label'), + [...s.querySelectorAll('.bh-card-title')].map((n) => n.textContent), + ]); + expect(groups).toEqual([ + ['等待处理', ['Stranger']], + ['活跃', ['Team']], + ['已静音', ['Noisy']], + ['已屏蔽', ['Spam']], + ]); + expect(container.textContent).toContain('已达每小时 20 个新会话上限'); + const button = (section: number, label: string) => + [...container.querySelectorAll('section')[section]!.querySelectorAll('button')].find( + (b) => b.textContent === label, + )!; + await act(async () => button(1, '屏蔽').click()); + expect(change).not.toHaveBeenCalled(); + await act(async () => button(1, '确认屏蔽').click()); + expect(change).toHaveBeenLastCalledWith({ kind: 'block', grantId: 'g1', expectedRevision: 3 }); + await act(async () => button(2, '取消静音').click()); + expect(change).toHaveBeenLastCalledWith({ + kind: 'mute', + grantId: 'g2', + expectedRevision: 1, + muted: false, + }); + await act(async () => button(0, '允许').click()); + expect(change).toHaveBeenLastCalledWith({ + kind: 'allow', + bindingId: 'binding', + conversation: { kind: 'dm', id: 'oc_new' }, + from: 'held', + expectedRevision: 1, + }); + await act(async () => button(3, '再次允许').click()); + expect(change).toHaveBeenLastCalledWith({ + kind: 'allow', + bindingId: 'binding', + conversation: { kind: 'group', id: 'oc_spam' }, + from: 'blocked', + expectedRevision: 2, + }); + await act(async () => root.unmount()); + container.remove(); +}); diff --git a/packages/client/test/external-identity-list.test.ts b/packages/client/test/external-identity-list.test.ts index 64d486f0ea..1cbb8dbe16 100644 --- a/packages/client/test/external-identity-list.test.ts +++ b/packages/client/test/external-identity-list.test.ts @@ -82,6 +82,8 @@ it('failed Switch writes retain the committed preference; stale Modal edits reta snapshot, t: zhTranslate, mutate, + conversation: vi.fn(), + rules: vi.fn(), }), ), ); @@ -120,6 +122,7 @@ it('failed Switch writes retain the committed preference; stale Modal edits reta expectedRevision: 7, name: 'Retained edit', inheritEnabled: false, + newConversations: 'auto', enabled: true, }); } finally { @@ -128,7 +131,7 @@ it('failed Switch writes retain the committed preference; stale Modal edits reta } }); -it('Bind app shows real readiness after the commit and the app row lists its conversations read-only', async () => { +it('Bind app shows real readiness after the commit and the app row lists its conversations with their actions', async () => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); const account = { providerId: 'dsh-im/feishu', @@ -184,7 +187,15 @@ it('Bind app shows real readiness after the commit and the app row lists its con document.body.append(container); const root = createRoot(container); const render = () => - root.render(createElement(ExternalIdentityList, { snapshot, t: zhTranslate, mutate })); + root.render( + createElement(ExternalIdentityList, { + snapshot, + t: zhTranslate, + mutate, + conversation: vi.fn(), + rules: vi.fn(), + }), + ); const mutate = vi.fn(async () => { snapshot = { ...snapshot, @@ -227,11 +238,14 @@ it('Bind app shows real readiness after the commit and the app row lists its con expect(container.textContent).toContain('飞书 · 1 个会话'); const edit = container.querySelector('[title="编辑身份:Support app"]')!; await act(async () => edit.click()); - const list = container.querySelector('[role="dialog"] [aria-label="会话"]')!; + const list = container.querySelector('[role="dialog"] section[aria-label="活跃"]')!; expect(list.textContent).toContain('Owner'); expect(list.textContent).toContain('私聊'); expect(list.textContent).toContain('最近消息'); - expect(list.querySelector('button')).toBeNull(); + expect([...list.querySelectorAll('button')].map((b) => b.textContent)).toEqual([ + '静音', + '屏蔽', + ]); } finally { await act(async () => root.unmount()); container.remove(); diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index bcd7618edc..d34345ccad 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -335,6 +335,7 @@ export interface BridgeMethods { messagingTargets(payload: unknown): Promise>; messagingAuthorize(payload: unknown): Promise>; messagingRevoke(payload: unknown): Promise>; + messagingConversation(payload: unknown): Promise>; messagingSend(payload: unknown): Promise>; modelCatalog(payload: unknown): Promise>; @@ -1200,6 +1201,57 @@ export function createBridgeMethods(deps: BridgeMethodsDeps): BridgeMethods { return { revoked: true as const }; }); }, + messagingConversation(payload) { + const conversation = z + .object({ kind: z.enum(['dm', 'group']), id: z.string().min(1).max(512) }) + .strict(); + const revision = z.number().int().min(0); + const input = z + .object({ + slug: z.string().min(1), + input: z.discriminatedUnion('kind', [ + z + .object({ + kind: z.literal('mute'), + grantId: z.string().uuid(), + expectedRevision: revision, + muted: z.boolean(), + }) + .strict(), + z + .object({ + kind: z.literal('block'), + grantId: z.string().uuid(), + expectedRevision: revision, + }) + .strict(), + z + .object({ + kind: z.literal('block-held'), + bindingId: z.string().uuid(), + conversation, + expectedRevision: revision, + }) + .strict(), + z + .object({ + kind: z.literal('allow'), + bindingId: z.string().uuid(), + conversation, + from: z.enum(['held', 'blocked']), + expectedRevision: revision, + }) + .strict(), + ]), + }) + .strict() + .safeParse(payload); + if (!input.success) return Promise.resolve(invalidInput('Invalid conversation change')); + return messagingCall(async (service) => { + await service.conversation(input.data.slug, input.data.input); + return { updated: true as const }; + }); + }, messagingSend(payload) { const input = z .object({ diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index f56a8031f4..068d663fd7 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -8,6 +8,7 @@ import type { MessagingDefaultsPlatform, } from '../messaging/defaults.js'; import type { MessagingIdentity, MessagingIdentityInput } from '../messaging/identity.js'; +import type { MessagingConversationInput } from '../messaging/conversations.js'; import type { ChannelBridgeInput, ChannelBridgeSnapshot } from '../messaging/channel-bridge.js'; import type { UsageOverviewPeriod } from '../usage/overview.js'; import type { @@ -259,6 +260,12 @@ export class BotharnessBridgeService extends TypertRemoteService { messagingRevoke(slug: string, grantId: string): Promise<{ revoked: true }> { return unwrapAsync(this.methods.messagingRevoke({ slug, grantId })); } + messagingConversation( + slug: string, + input: MessagingConversationInput, + ): Promise<{ updated: true }> { + return unwrapAsync(this.methods.messagingConversation({ slug, input })); + } messagingSend( slug: string, grantId: string, @@ -1016,6 +1023,7 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'messagingTargets', 'messagingAuthorize', 'messagingRevoke', + 'messagingConversation', 'messagingSend', 'modelCatalog', 'modelPresets', diff --git a/packages/core/src/database/schema-plan.ts b/packages/core/src/database/schema-plan.ts index b2f3f58aba..6428b33a6b 100644 --- a/packages/core/src/database/schema-plan.ts +++ b/packages/core/src/database/schema-plan.ts @@ -1613,6 +1613,61 @@ const BOUND_APP_ADMISSION_MIGRATION: SchemaMigration = { }, }; +const CONVERSATION_LIST_MIGRATION: SchemaMigration = { + generation: 62, + module: 'messaging', + description: + 'Keep durable conversation blocks per Bot and app fingerprint, and held conversations waiting for a decision', + migrate(database) { + database.exec(` + CREATE TABLE messaging_conversation_blocks ( + bot_slug TEXT NOT NULL, + fingerprint TEXT NOT NULL, + conversation_kind TEXT NOT NULL CHECK (conversation_kind IN ('dm', 'group')), + conversation_id TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision > 0), + body TEXT NOT NULL CHECK (json_valid(body)), + PRIMARY KEY (bot_slug, fingerprint, conversation_kind, conversation_id) + ); + CREATE TABLE messaging_held_conversations ( + binding_id TEXT NOT NULL, + conversation_kind TEXT NOT NULL CHECK (conversation_kind IN ('dm', 'group')), + conversation_id TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + body TEXT NOT NULL CHECK (json_valid(body)), + PRIMARY KEY (binding_id, conversation_kind, conversation_id) + ); + CREATE INDEX messaging_held_conversations_seen + ON messaging_held_conversations(binding_id, last_seen_at); + INSERT OR IGNORE INTO messaging_conversation_blocks + (bot_slug, fingerprint, conversation_kind, conversation_id, revision, body) + SELECT g.bot_slug, json_extract(g.body, '$.fingerprint'), + json_extract(g.body, '$.receiveScope.kind'), + json_extract(g.body, '$.receiveScope.conversationId'), 1, + json_object( + 'botSlug', g.bot_slug, + 'fingerprint', json_extract(g.body, '$.fingerprint'), + 'conversation', json_object( + 'kind', json_extract(g.body, '$.receiveScope.kind'), + 'id', json_extract(g.body, '$.receiveScope.conversationId')), + 'name', json_extract(g.body, '$.targetName'), + 'blockedAt', g.revoked_at, + 'revision', 1) + FROM messaging_grants g + WHERE g.revoked_at IS NOT NULL + AND json_extract(g.body, '$.origin') = 'explicit' + AND json_extract(g.body, '$.receiveScope.kind') IN ('dm', 'group') + AND NOT EXISTS ( + SELECT 1 FROM messaging_grants a + WHERE a.revoked_at IS NULL AND a.bot_slug = g.bot_slug + AND json_extract(a.body, '$.fingerprint') = json_extract(g.body, '$.fingerprint') + AND json_extract(a.body, '$.receiveScope.kind') = json_extract(g.body, '$.receiveScope.kind') + AND json_extract(a.body, '$.receiveScope.conversationId') = + json_extract(g.body, '$.receiveScope.conversationId')); + `); + }, +}; + export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ SESSION_OWNERSHIP_MIGRATION, MESSAGING_TRACER_MIGRATION, @@ -1674,4 +1729,5 @@ export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ BOT_PAIRING_MIGRATION, APPROVAL_MESSAGING_MIGRATION, BOUND_APP_ADMISSION_MIGRATION, + CONVERSATION_LIST_MIGRATION, ]); diff --git a/packages/core/src/messaging/conversations.ts b/packages/core/src/messaging/conversations.ts new file mode 100644 index 0000000000..37a0995a9c --- /dev/null +++ b/packages/core/src/messaging/conversations.ts @@ -0,0 +1,205 @@ +import type { DatabaseSync } from 'node:sqlite'; +import type { MessagingInboundEvent } from './provider.js'; + +export const NEW_ENTRIES_PER_HOUR = 20; +export const ACTIVE_ENTRIES_PER_APP = 500; +export const HELD_ENTRIES_PER_APP = 200; +const HELD_COUNT_LIMIT = 9999; + +export type ConversationKind = 'dm' | 'group'; +export type HeldReason = 'ask' | 'hourly-limit' | 'active-limit'; + +export interface ConversationRef { + kind: ConversationKind; + id: string; +} + +export interface HeldConversation { + bindingId: string; + conversation: ConversationRef; + name: string; + reason: HeldReason; + firstSeenAt: string; + lastSeenAt: string; + count: number; + revision: number; +} + +export interface BlockedConversation { + botSlug: string; + fingerprint: string; + bindingId?: string; + conversation: ConversationRef; + name: string; + blockedAt: string; + revision: number; +} + +export type MessagingConversationInput = + | { kind: 'mute'; grantId: string; expectedRevision: number; muted: boolean } + | { kind: 'block'; grantId: string; expectedRevision: number } + | { + kind: 'block-held'; + bindingId: string; + conversation: ConversationRef; + expectedRevision: number; + } + | { + kind: 'allow'; + bindingId: string; + conversation: ConversationRef; + from: 'held' | 'blocked'; + expectedRevision: number; + }; + +export function conversationName(event: MessagingInboundEvent): string { + return event.conversation.kind === 'dm' + ? event.actor.name || event.actor.id + : event.conversation.id; +} + +export function readBlock( + db: DatabaseSync, + botSlug: string, + fingerprint: string, + conversation: ConversationRef, +): BlockedConversation | undefined { + const row = db + .prepare( + `SELECT body FROM messaging_conversation_blocks + WHERE bot_slug = ? AND fingerprint = ? AND conversation_kind = ? AND conversation_id = ?`, + ) + .get(botSlug, fingerprint, conversation.kind, conversation.id) as { body: string } | undefined; + return row ? (JSON.parse(row.body) as BlockedConversation) : undefined; +} + +export function writeBlock( + db: DatabaseSync, + value: Omit, +): BlockedConversation { + const revision = + (readBlock(db, value.botSlug, value.fingerprint, value.conversation)?.revision ?? 0) + 1; + const block: BlockedConversation = { ...value, revision }; + db.prepare( + `INSERT INTO messaging_conversation_blocks + (bot_slug, fingerprint, conversation_kind, conversation_id, revision, body) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (bot_slug, fingerprint, conversation_kind, conversation_id) + DO UPDATE SET revision = excluded.revision, body = excluded.body`, + ).run( + value.botSlug, + value.fingerprint, + value.conversation.kind, + value.conversation.id, + revision, + JSON.stringify(block), + ); + return block; +} + +export function removeBlock( + db: DatabaseSync, + botSlug: string, + fingerprint: string, + conversation: ConversationRef, +): void { + db.prepare( + `DELETE FROM messaging_conversation_blocks + WHERE bot_slug = ? AND fingerprint = ? AND conversation_kind = ? AND conversation_id = ?`, + ).run(botSlug, fingerprint, conversation.kind, conversation.id); +} + +export function listBlocks(db: DatabaseSync, botSlug: string): BlockedConversation[] { + return ( + db + .prepare( + "SELECT body FROM messaging_conversation_blocks WHERE bot_slug = ? ORDER BY json_extract(body, '$.blockedAt') DESC", + ) + .all(botSlug) as { body: string }[] + ).map((row) => JSON.parse(row.body) as BlockedConversation); +} + +export function readHeld( + db: DatabaseSync, + bindingId: string, + conversation: ConversationRef, +): HeldConversation | undefined { + const row = db + .prepare( + `SELECT body FROM messaging_held_conversations + WHERE binding_id = ? AND conversation_kind = ? AND conversation_id = ?`, + ) + .get(bindingId, conversation.kind, conversation.id) as { body: string } | undefined; + return row ? (JSON.parse(row.body) as HeldConversation) : undefined; +} + +export function removeHeld( + db: DatabaseSync, + bindingId: string, + conversation: ConversationRef, +): void { + db.prepare( + `DELETE FROM messaging_held_conversations + WHERE binding_id = ? AND conversation_kind = ? AND conversation_id = ?`, + ).run(bindingId, conversation.kind, conversation.id); +} + +export function hold( + db: DatabaseSync, + bindingId: string, + event: MessagingInboundEvent, + reason: HeldReason, + at: string, +): HeldConversation { + const conversation = { kind: event.conversation.kind, id: event.conversation.id }; + const previous = readHeld(db, bindingId, conversation); + const value: HeldConversation = { + bindingId, + conversation, + name: conversationName(event), + reason, + firstSeenAt: previous?.firstSeenAt ?? at, + lastSeenAt: at, + count: Math.min(HELD_COUNT_LIMIT, (previous?.count ?? 0) + 1), + revision: previous?.revision ?? 1, + }; + db.prepare( + `INSERT INTO messaging_held_conversations + (binding_id, conversation_kind, conversation_id, last_seen_at, body) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT (binding_id, conversation_kind, conversation_id) + DO UPDATE SET last_seen_at = excluded.last_seen_at, body = excluded.body`, + ).run(bindingId, conversation.kind, conversation.id, at, JSON.stringify(value)); + db.prepare( + `DELETE FROM messaging_held_conversations WHERE binding_id = ? AND rowid NOT IN ( + SELECT rowid FROM messaging_held_conversations WHERE binding_id = ? + ORDER BY last_seen_at DESC LIMIT ?)`, + ).run(bindingId, bindingId, HELD_ENTRIES_PER_APP); + return value; +} + +export function listHeld(db: DatabaseSync, bindingId: string): HeldConversation[] { + return ( + db + .prepare( + 'SELECT body FROM messaging_held_conversations WHERE binding_id = ? ORDER BY last_seen_at DESC', + ) + .all(bindingId) as { body: string }[] + ).map((row) => JSON.parse(row.body) as HeldConversation); +} + +export function admissionBound( + db: DatabaseSync, + bindingId: string, + now: Date, +): 'hourly-limit' | 'active-limit' | undefined { + const implicit = `binding_id = ? AND json_extract(body, '$.origin') = 'implicit'`; + const active = db + .prepare(`SELECT count(*) AS n FROM messaging_grants WHERE ${implicit} AND revoked_at IS NULL`) + .get(bindingId) as { n: number }; + if (active.n >= ACTIVE_ENTRIES_PER_APP) return 'active-limit'; + const recent = db + .prepare(`SELECT count(*) AS n FROM messaging_grants WHERE ${implicit} AND created_at > ?`) + .get(bindingId, new Date(now.getTime() - 3_600_000).toISOString()) as { n: number }; + return recent.n >= NEW_ENTRIES_PER_HOUR ? 'hourly-limit' : undefined; +} diff --git a/packages/core/src/messaging/inbound.ts b/packages/core/src/messaging/inbound.ts index 6fcfd07cc3..dce462745e 100644 --- a/packages/core/src/messaging/inbound.ts +++ b/packages/core/src/messaging/inbound.ts @@ -1,3 +1,4 @@ +import { admissionBound, conversationName, hold, readBlock, removeHeld } from './conversations.js'; import type { BotPairing } from './pairing.js'; import { readMessagingIdentity } from './identity.js'; import { @@ -178,6 +179,7 @@ export interface InboundMessaging { pairingReception(bindingId: string): 'off' | 'connecting' | 'receiving' | 'unavailable'; reconcileBinding(bindingId: string): Promise; revoke(grantId: string): void; + startEntry(grantId: string): void; close(): void; } @@ -352,9 +354,9 @@ export function createInboundMessaging(options: { value.botSlug, 'human-dm', policy.revision, - policy.wake, + value.muted ? 'silent' : policy.wake, policy.revision, - policy.wake === 'immediate' ? 'all' : policy.wake, + value.muted ? 'silent' : policy.wake === 'immediate' ? 'all' : policy.wake, ); return sourceEventId; }; @@ -373,9 +375,9 @@ export function createInboundMessaging(options: { value.botSlug, 'group-mention', policy.revision, - policy.wake, + value.muted ? 'silent' : policy.wake, reception.revision, - policy.wake === 'immediate' ? 'all' : policy.wake, + value.muted ? 'silent' : policy.wake === 'immediate' ? 'all' : policy.wake, thread?.revision ?? null, reception.defaultRevision ?? null, ); @@ -1180,7 +1182,17 @@ export function createInboundMessaging(options: { let value: MessagingGrant | undefined = entries[0]; let created = false; if (value === undefined) { - if (readMessagingIdentity(db, id).newConversations !== 'auto') return undefined; + if (readBlock(db, identity.botSlug, identity.fingerprint, event.conversation)) + return undefined; + const reason = + readMessagingIdentity(db, id).newConversations !== 'auto' + ? ('ask' as const) + : admissionBound(db, id, new Date()); + if (reason !== undefined) { + hold(db, id, event, reason, new Date().toISOString()); + return { held: true as const }; + } + removeHeld(db, id, event.conversation); value = { id: randomUUID(), bindingId: id, @@ -1191,10 +1203,7 @@ export function createInboundMessaging(options: { fingerprint: identity.fingerprint, platform: identity.platform, targetRef: '', - targetName: - event.conversation.kind === 'dm' - ? event.actor.name || event.actor.id - : event.conversation.id, + targetName: conversationName(event), targetDigest: '', revision: 1, createdAt: new Date().toISOString(), @@ -1220,10 +1229,14 @@ export function createInboundMessaging(options: { ['grants', 'source-event', 'bot-inbox'], ); if (!admitted) return { accepted: true }; + if ('held' in admitted) { + receptionChanged(); + return { accepted: true }; + } const { value, created, sourceEventId } = admitted; if (created || !leases.has(value.id)) void start(value); if (created) receptionChanged(); - if (sourceEventId !== undefined) + if (sourceEventId !== undefined && !value.muted) setImmediate(() => { if (closed) return; try { @@ -2331,6 +2344,11 @@ export function createInboundMessaging(options: { await Promise.all(values.filter((v) => !v.revokedAt).map((value) => start(value))); }, revoke: stop, + startEntry(grantId) { + const value = grant(grantId); + if (value.revokedAt === undefined && !closed) void start(value); + receptionChanged(); + }, close() { closed = true; for (const id of new Set([...controls.keys(), ...controlRetries.keys()])) diff --git a/packages/core/src/messaging/outbound.ts b/packages/core/src/messaging/outbound.ts index dbf8417d72..b5872b9d43 100644 --- a/packages/core/src/messaging/outbound.ts +++ b/packages/core/src/messaging/outbound.ts @@ -19,7 +19,20 @@ import { type MessagingDefaults, type MessagingDefaultsInput, } from './defaults.js'; -import type { GroupReceptionPolicy } from './group-policy.js'; +import { initializeGroupReceptionPolicy, type GroupReceptionPolicy } from './group-policy.js'; +import { + admissionBound, + listBlocks, + listHeld, + readBlock, + readHeld, + removeBlock, + removeHeld, + writeBlock, + type BlockedConversation, + type HeldConversation, + type MessagingConversationInput, +} from './conversations.js'; import { bridgeChannel, humanBridgeChannel } from './channel-target.js'; import { channelBridgeRoutes, @@ -112,6 +125,8 @@ export interface MessagingGrant { channelBridge?: ChannelBridgeConfiguration; bridgeRoutes?: ChannelBridgeRoute[]; origin?: 'explicit' | 'implicit'; + muted?: boolean; + preferenceRevision?: number; revokedAt?: string; suspendedReason?: 'rebind-required'; } @@ -188,6 +203,8 @@ export interface MessagingSnapshot { threadPolicies?: ThreadReceptionView[]; ordinaryDelivery?: 'verified' | 'unverified'; })[]; + heldConversations?: HeldConversation[]; + blockedConversations?: BlockedConversation[]; intents: OutboxIntent[]; } @@ -235,6 +252,7 @@ export interface OutboundMessaging { targetDigest: string; }): Promise; revoke(botSlug: string, grantId: string): void; + conversation(botSlug: string, input: MessagingConversationInput): Promise; send( botSlug: string, grantId: string, @@ -311,6 +329,24 @@ export function createOutboundMessaging(options: { if (provider(id).token !== token) throw new MessagingError('provider-unavailable'); }; const binding = (id: string) => database.read((db) => readMessagingIdentity(db, id)); + const revokePendingIntents = (db: DatabaseSync, grantId: string, at: string) => { + const pending = db + .prepare("SELECT id FROM messaging_outbox WHERE grant_id = ? AND state = 'pending'") + .all(grantId) as unknown as { id: string }[]; + for (const row of pending) { + const intent = readIntent(row.id); + db.prepare('UPDATE messaging_outbox SET state = ?, body = ? WHERE id = ?').run( + 'grant-revoked', + JSON.stringify({ + ...intent, + state: 'grant-revoked', + reason: 'grant-revoked', + settledAt: at, + }), + row.id, + ); + } + }; const enabledBinding = (id: string, revision?: number) => database.read((db) => assertMessagingIdentity(db, id, revision)); const bounded = async (work: Promise): Promise => { @@ -1344,6 +1380,15 @@ export function createOutboundMessaging(options: { .filter((i) => i.platform === 'feishu' && !i.revokedAt) .map((i) => ({ name: i.name, status: i.reception ?? 'unavailable' })), grants, + heldConversations: database.read((db) => + identities.flatMap((identity) => listHeld(db, identity.id)), + ), + blockedConversations: database + .read((db) => listBlocks(db, botSlug)) + .map((block) => { + const owner = identities.find((identity) => identity.fingerprint === block.fingerprint); + return owner ? { ...block, bindingId: owner.id } : block; + }), channelTargets, intents, setup: { @@ -1458,22 +1503,7 @@ export function createOutboundMessaging(options: { grantId, ); - const pending = db - .prepare("SELECT id FROM messaging_outbox WHERE grant_id = ? AND state = 'pending'") - .all(grantId) as unknown as { id: string }[]; - for (const row of pending) { - const intent = readIntent(row.id); - db.prepare('UPDATE messaging_outbox SET state = ?, body = ? WHERE id = ?').run( - 'grant-revoked', - JSON.stringify({ - ...intent, - state: 'grant-revoked', - reason: 'grant-revoked', - settledAt: revokedAt, - }), - row.id, - ); - } + revokePendingIntents(db, grantId, revokedAt); }, ['grants', 'bindings', 'outbox'], ); @@ -1481,6 +1511,132 @@ export function createOutboundMessaging(options: { for (const attempt of inFlight.values()) if (attempt.fileGrantId === grantId) attempt.controller.abort(); }, + async conversation(botSlug, input) { + active(botSlug); + if (input.kind === 'mute') { + transaction( + (db) => { + const value = grant(botSlug, input.grantId); + if (value.revokedAt !== undefined || !value.receiveScope) + throw new MessagingError('grant-revoked'); + if ((value.preferenceRevision ?? 0) !== input.expectedRevision) + throw new MessagingError('conversation-stale'); + const next: MessagingGrant = { + ...value, + muted: input.muted, + preferenceRevision: input.expectedRevision + 1, + }; + db.prepare('UPDATE messaging_grants SET body = ? WHERE id = ?').run( + JSON.stringify(next), + value.id, + ); + }, + ['grants'], + ); + inbound.startEntry(input.grantId); + return; + } + if (input.kind === 'block') { + transaction( + (db) => { + const value = grant(botSlug, input.grantId); + if (value.revokedAt !== undefined || !value.receiveScope) + throw new MessagingError('grant-revoked'); + if (value.revision !== input.expectedRevision) + throw new MessagingError('conversation-stale'); + const at = now(); + const revision = value.revision + 1; + db.prepare( + 'UPDATE messaging_grants SET body = ?, revoked_at = ?, revision = ? WHERE id = ?', + ).run(JSON.stringify({ ...value, revokedAt: at, revision }), at, revision, value.id); + revokePendingIntents(db, value.id, at); + const conversation = { + kind: value.receiveScope.kind, + id: value.receiveScope.conversationId, + }; + writeBlock(db, { + botSlug, + fingerprint: value.fingerprint, + conversation, + name: value.targetName, + blockedAt: at, + }); + removeHeld(db, value.bindingId, conversation); + }, + ['grants', 'outbox'], + ); + inbound.revoke(input.grantId); + for (const attempt of inFlight.values()) + if (attempt.fileGrantId === input.grantId) attempt.controller.abort(); + inbound.startEntry(input.grantId); + return; + } + const created = transaction( + (db) => { + const identity = readMessagingIdentity(db, input.bindingId); + if (identity.botSlug !== botSlug || identity.revokedAt) + throw new MessagingError('identity-unbound'); + const held = readHeld(db, input.bindingId, input.conversation); + const blocked = readBlock(db, botSlug, identity.fingerprint, input.conversation); + if (input.kind === 'block-held') { + if (!held || held.revision !== input.expectedRevision) + throw new MessagingError('conversation-stale'); + writeBlock(db, { + botSlug, + fingerprint: identity.fingerprint, + conversation: input.conversation, + name: held.name, + blockedAt: now(), + }); + removeHeld(db, input.bindingId, input.conversation); + return undefined; + } + const source = input.from === 'held' ? held : blocked; + if (!source || source.revision !== input.expectedRevision) + throw new MessagingError('conversation-stale'); + if (!identity.enabled) throw new MessagingError('identity-paused'); + const existing = db + .prepare( + `SELECT 1 FROM messaging_grants WHERE binding_id = ? AND revoked_at IS NULL + AND json_extract(body, '$.receiveScope.kind') = ? + AND json_extract(body, '$.receiveScope.conversationId') = ?`, + ) + .get(input.bindingId, input.conversation.kind, input.conversation.id); + if (existing) throw new MessagingError('conversation-stale'); + if (admissionBound(db, input.bindingId, new Date(now())) === 'active-limit') + throw new MessagingError('conversation-limit'); + const at = now(); + const value: MessagingGrant = { + id: randomUUID(), + bindingId: identity.id, + botSlug, + providerId: identity.providerId, + accountRef: identity.accountRef, + accountName: identity.name, + fingerprint: identity.fingerprint, + platform: identity.platform, + targetRef: '', + targetName: source.name, + targetDigest: '', + revision: 1, + createdAt: at, + receiveAfter: at, + receiveScope: { kind: input.conversation.kind, conversationId: input.conversation.id }, + origin: 'implicit', + }; + db.prepare( + 'INSERT INTO messaging_grants (id, binding_id, bot_slug, revision, created_at, body) VALUES (?, ?, ?, ?, ?, ?)', + ).run(value.id, value.bindingId, botSlug, 1, at, JSON.stringify(value)); + if (input.conversation.kind === 'group') initializeGroupReceptionPolicy(db, value.id); + removeHeld(db, input.bindingId, input.conversation); + removeBlock(db, botSlug, identity.fingerprint, input.conversation); + return value.id; + }, + ['grants', 'bindings'], + ); + if (created !== undefined) inbound.startEntry(created); + else options.onReceptionChanged?.(); + }, async send(botSlug, grantId, requestId, text, sourceEventId, file, report = false) { active(botSlug); if ( diff --git a/packages/core/src/runtime/bot-runtime.ts b/packages/core/src/runtime/bot-runtime.ts index 75e299d128..d1f33e96e1 100644 --- a/packages/core/src/runtime/bot-runtime.ts +++ b/packages/core/src/runtime/bot-runtime.ts @@ -1025,13 +1025,14 @@ class BotRuntimeImplementation implements BotRuntime { if (this.#closed || !this.#externalMessaging?.inbound.available(botSlug, sourceEventId)) return; const row = this.#database.read((db) => db - .prepare(`SELECT a.attempt_state, a.reason, e.channel_id, e.message_id FROM inbox_admissions a + .prepare(`SELECT a.attempt_state, a.reason, a.wake_mode, e.channel_id, e.message_id FROM inbox_admissions a JOIN source_events e USING(source_event_id) WHERE a.bot_slug = ? AND a.source_event_id = ?`) .get(botSlug, sourceEventId), ) as | { attempt_state: string; reason: string; + wake_mode: string | null; channel_id: string | null; message_id: string | null; } @@ -1047,7 +1048,8 @@ class BotRuntimeImplementation implements BotRuntime { this.#admitChannelMessage(row.channel_id, row.message_id, 'group-ordinary'); return; } - if (!row || !['pending', 'retryable'].includes(row.attempt_state)) return; + if (!row || !['pending', 'retryable'].includes(row.attempt_state) || row.wake_mode === 'silent') + return; const active = this.#activeTurns.get(botSlug); if ( (row.reason === 'group-mention' || row.reason === 'human-dm') && @@ -5319,7 +5321,7 @@ class BotRuntimeImplementation implements BotRuntime { AND a.attempt_state IN ('pending', 'retryable') AND a.observed_at IS NULL WINDOW policy AS (PARTITION BY g.id, a.wake_policy_revision, a.source_policy_revision, a.external_default_revision, a.reason, CASE WHEN json_extract(tp.body, '$.mode') = 'follow' THEN tp.thread_id ELSE '' END, CASE WHEN json_extract(tp.body, '$.mode') = 'follow' THEN tp.revision ELSE 0 END) ) SELECT source_event_id, body, created_at, attempt_state FROM pending - WHERE reason = 'group-mention' OR (reason = 'human-dm' AND wake_mode = 'all') OR (reason = 'group-ordinary' AND ( + WHERE (reason = 'group-mention' AND wake_mode IS NOT 'silent') OR (reason = 'human-dm' AND wake_mode = 'all') OR (reason = 'group-ordinary' AND ( wake_mode = 'all' OR (wake_mode = 'digest' AND (pending_count >= wake_count OR (julianday(?) - julianday(first_at)) * 86400000 >= wake_interval_ms)) OR (? = 1 AND has_mention = 1 AND wake_mode IN ('digest', 'mentions')))) diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index f0a94a5335..daa7ea4446 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -93,6 +93,7 @@ describe('bridge typert service', () => { 'messagingTargets', 'messagingAuthorize', 'messagingRevoke', + 'messagingConversation', 'messagingSend', 'modelCatalog', 'modelPresets', diff --git a/packages/core/test/messaging-conversation-list-migration.test.ts b/packages/core/test/messaging-conversation-list-migration.test.ts new file mode 100644 index 0000000000..fa1a8c2c46 --- /dev/null +++ b/packages/core/test/messaging-conversation-list-migration.test.ts @@ -0,0 +1,68 @@ +import { expect, it } from 'vitest'; +import { attachOperationalModule, mountOperationalDatabase } from '../src/database/owner.js'; +import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; +import { defineSchemaPlan } from '../src/database/schema.js'; +import { createTempRoot } from './helpers.js'; + +it('turns revoked explicit conversations without a live replacement into blocks at generation 62', () => { + const home = createTempRoot('bh1109-upgrade-'); + const prior = mountOperationalDatabase({ + dshHome: home, + schemaPlan: defineSchemaPlan( + BOT_HARNESS_SCHEMA_PLAN.migrations.filter((m) => m.generation < 62), + ), + }); + const grant = (id: string, conversation: string, origin: string, revokedAt?: string) => ({ + id, + bindingId: 'binding', + botSlug: 'ada', + fingerprint: 'fp', + targetName: `Name ${conversation}`, + revision: 2, + origin, + receiveScope: { kind: 'group', conversationId: conversation }, + ...(revokedAt ? { revokedAt } : {}), + }); + attachOperationalModule(prior, 'test').transaction((db) => { + db.prepare( + "INSERT INTO messaging_bindings(id,bot_slug,provider_id,platform,account_ref,fingerprint,created_at,enabled) VALUES ('binding','ada','dsh-im/feishu','feishu','lark-app','fp','2026-10-01',1)", + ).run(); + for (const [id, conversation, origin, revokedAt] of [ + ['revoked', 'oc_gone', 'explicit', '2026-10-05'], + ['replaced-old', 'oc_back', 'explicit', '2026-10-04'], + ['replaced-new', 'oc_back', 'explicit', undefined], + ['implicit-gone', 'oc_unbound', 'implicit', '2026-10-06'], + ] as const) + db.prepare( + 'INSERT INTO messaging_grants(id,binding_id,bot_slug,revision,created_at,revoked_at,body) VALUES (?,?,?,?,?,?,?)', + ).run( + id, + 'binding', + 'ada', + 2, + '2026-10-02', + revokedAt ?? null, + JSON.stringify(grant(id, conversation, origin, revokedAt)), + ); + }); + prior.close(); + const current = mountOperationalDatabase({ dshHome: home, schemaPlan: BOT_HARNESS_SCHEMA_PLAN }); + expect(current.mode).toBe('ready'); + const port = attachOperationalModule(current, 'test'); + const blocks = port.read((db) => + db.prepare('SELECT conversation_id, revision, body FROM messaging_conversation_blocks').all(), + ) as { conversation_id: string; revision: number; body: string }[]; + expect(blocks.map((row) => [row.conversation_id, row.revision])).toEqual([['oc_gone', 1]]); + expect(JSON.parse(blocks[0]!.body)).toEqual({ + botSlug: 'ada', + fingerprint: 'fp', + conversation: { kind: 'group', id: 'oc_gone' }, + name: 'Name oc_gone', + blockedAt: '2026-10-05', + revision: 1, + }); + expect( + port.read((db) => db.prepare('SELECT count(*) AS n FROM messaging_held_conversations').get()), + ).toEqual({ n: 0 }); + current.close(); +}); diff --git a/packages/core/test/messaging-default-traffic.test.ts b/packages/core/test/messaging-default-traffic.test.ts index 8aaad2d11a..f60c277f9a 100644 --- a/packages/core/test/messaging-default-traffic.test.ts +++ b/packages/core/test/messaging-default-traffic.test.ts @@ -398,3 +398,191 @@ it('a recorded group follows the platform default: collecting all text admits un { reason: 'group-ordinary', messageId: 'om-chatter' }, ]); }); + +async function grantFor(fx: Awaited>, conversation: string) { + const snapshot = await fx.core.externalMessaging.snapshot('ada'); + return snapshot.grants.find( + (grant) => !grant.revokedAt && grant.receiveScope?.conversationId === conversation, + )!; +} + +it('blocking an entry stops admission and survives restart and rebind; allowing again admits only new messages', async () => { + const fx = await fixture(); + await fx.receive(mention('ask')); + const grant = await grantFor(fx, 'oc_team'); + await fx.core.externalMessaging.conversation('ada', { + kind: 'block', + grantId: grant.id, + expectedRevision: grant.revision, + }); + await fx.settle(); + await fx.receive(mention('after-block')); + expect(fx.admissions()).toEqual([{ reason: 'group-mention', messageId: 'om-ask' }]); + await fx.restart(); + await fx.receive(mention('after-restart')); + expect(fx.admissions()).toHaveLength(1); + const snapshot = await fx.core.externalMessaging.snapshot('ada'); + expect(snapshot.blockedConversations).toEqual([ + expect.objectContaining({ + conversation: { kind: 'group', id: 'oc_team' }, + bindingId: snapshot.identities![0]!.id, + revision: 1, + }), + ]); + const identity = snapshot.identities![0]!; + await fx.core.externalMessaging.identity('ada', { + kind: 'unbind', + id: identity.id, + expectedRevision: identity.revision, + }); + await fx.settle(); + const rebound = await fx.core.externalMessaging.identity('ada', { + kind: 'bind', + providerId: 'dsh-im/feishu', + accountRef: 'lark-app', + fingerprint, + }); + await fx.settle(); + await fx.receive(mention('after-rebind')); + expect(fx.admissions()).toHaveLength(1); + const blocked = (await fx.core.externalMessaging.snapshot('ada')).blockedConversations![0]!; + await fx.core.externalMessaging.conversation('ada', { + kind: 'allow', + bindingId: rebound.id, + conversation: blocked.conversation, + from: 'blocked', + expectedRevision: blocked.revision, + }); + await fx.settle(); + expect((await fx.core.externalMessaging.snapshot('ada')).blockedConversations).toEqual([]); + await fx.receive(mention('allowed')); + expect( + fx + .admissions() + .map((row) => (row as { messageId: string }).messageId) + .sort(), + ).toEqual(['om-allowed', 'om-ask']); +}); + +it('a stale revision is refused and blocking revokes the old reply route', async () => { + const fx = await fixture(); + await fx.receive(dm('1')); + const grant = await grantFor(fx, 'oc_owner'); + await expect( + fx.core.externalMessaging.conversation('ada', { + kind: 'block', + grantId: grant.id, + expectedRevision: grant.revision + 5, + }), + ).rejects.toMatchObject({ code: 'conversation-stale' }); + await fx.core.externalMessaging.conversation('ada', { + kind: 'block', + grantId: grant.id, + expectedRevision: grant.revision, + }); + await fx.settle(); + await expect( + fx.core.externalMessaging.reply('ada', fx.sourceId('om-1'), 'too late'), + ).rejects.toThrow(); + expect(fx.replies).toEqual([]); +}); + +it('a muted entry is admitted silently without a run and can still be answered', async () => { + const fx = await fixture(); + await fx.receive(mention('ask')); + expect(fx.runs).toHaveLength(1); + const grant = await grantFor(fx, 'oc_team'); + await fx.core.externalMessaging.conversation('ada', { + kind: 'mute', + grantId: grant.id, + expectedRevision: grant.preferenceRevision ?? 0, + muted: true, + }); + await fx.settle(); + expect(await grantFor(fx, 'oc_team')).toMatchObject({ muted: true, revision: grant.revision }); + await fx.receive(mention('muted')); + expect(fx.runs).toHaveLength(1); + expect( + fx.query( + "SELECT a.wake_mode FROM inbox_admissions a JOIN source_events e USING(source_event_id) WHERE json_extract(e.payload_json, '$.external.event.messageId') = 'om-muted'", + ), + ).toEqual([{ wake_mode: 'silent' }]); + await fx.core.externalMessaging.reply('ada', fx.sourceId('om-muted'), 'Seen'); + await fx.settle(); + expect(fx.replies.map((item) => item.text)).toEqual(['Seen']); + const muted = await grantFor(fx, 'oc_team'); + await fx.core.externalMessaging.conversation('ada', { + kind: 'mute', + grantId: muted.id, + expectedRevision: muted.preferenceRevision ?? 0, + muted: false, + }); + await fx.settle(); + await fx.receive(mention('loud')); + expect(fx.runs).toHaveLength(2); +}); + +it('ask mode holds a new conversation without a Source Event until it is allowed', async () => { + const fx = await fixture(); + await fx.update({ newConversations: 'ask' }); + await fx.receive(mention('first')); + await fx.receive(mention('second')); + expect(fx.query('SELECT count(*) AS n FROM source_events')).toEqual([{ n: 0 }]); + const snapshot = await fx.core.externalMessaging.snapshot('ada'); + expect(snapshot.heldConversations).toEqual([ + expect.objectContaining({ + conversation: { kind: 'group', id: 'oc_team' }, + reason: 'ask', + count: 2, + }), + ]); + const held = snapshot.heldConversations![0]!; + await fx.core.externalMessaging.conversation('ada', { + kind: 'allow', + bindingId: held.bindingId, + conversation: held.conversation, + from: 'held', + expectedRevision: held.revision, + }); + await fx.settle(); + expect((await fx.core.externalMessaging.snapshot('ada')).heldConversations).toEqual([]); + expect(fx.admissions()).toEqual([]); + await fx.receive(mention('third')); + expect(fx.admissions()).toEqual([{ reason: 'group-mention', messageId: 'om-third' }]); +}); + +it('blocking a held conversation keeps it out of the Inbox', async () => { + const fx = await fixture(); + await fx.update({ newConversations: 'ask' }); + await fx.receive(dm('1')); + const held = (await fx.core.externalMessaging.snapshot('ada')).heldConversations![0]!; + await fx.core.externalMessaging.conversation('ada', { + kind: 'block-held', + bindingId: held.bindingId, + conversation: held.conversation, + expectedRevision: held.revision, + }); + await fx.update({ newConversations: 'auto' }); + await fx.receive(dm('2')); + const snapshot = await fx.core.externalMessaging.snapshot('ada'); + expect(snapshot.heldConversations).toEqual([]); + expect(snapshot.blockedConversations).toEqual([ + expect.objectContaining({ conversation: { kind: 'dm', id: 'oc_owner' }, name: 'Owner' }), + ]); + expect(fx.admissions()).toEqual([]); +}); + +it('holds new conversations past the hourly limit instead of creating entries', async () => { + const fx = await fixture(); + for (let i = 0; i < 21; i++) + await fx.receive( + dm(`n${i}`, { + conversation: { kind: 'dm', id: `oc_${i}` }, + reply: { messageId: `om-n${i}`, conversationId: `oc_${i}`, actorId: 'ou_owner' }, + }), + ); + expect(fx.entries()).toHaveLength(20); + expect((await fx.core.externalMessaging.snapshot('ada')).heldConversations).toEqual([ + expect.objectContaining({ conversation: { kind: 'dm', id: 'oc_20' }, reason: 'hourly-limit' }), + ]); +}); diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 08d082845a..8c625b5f1f 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -353,6 +353,7 @@ describe('plugin entry', () => { 'messagingTargets', 'messagingAuthorize', 'messagingRevoke', + 'messagingConversation', 'messagingSend', 'modelCatalog', 'modelPresets',