Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 将本机 Slack 通讯与 Bot 接收设备分离 (#4506)
Chris Zhangd047bc3fbcaf
diff --git a/apps/desktop/help-knowledge/connections.md b/apps/desktop/help-knowledge/connections.mdindex 074017d121..8d375be4de 100644--- a/apps/desktop/help-knowledge/connections.md+++ b/apps/desktop/help-knowledge/connections.md@@ -7,7 +7,7 @@ External account connections have moved out of the old "Third-Party Platforms" s**Where to connect what:**-- **Slack** — bound with a single toggle under **Settings > IM bots** (the "Cindy" tab). One browser sign-in covers both directions: the Slack channel bot that receives tasks, and the agent Slack tools (search / read / post). If Slack tools don't work on an older binding, toggle it off and on once to re-authorize.+- **Slack** — connect under **Settings > IM bots** (the "Cindy" tab). Each workspace has **Slack Communications on This Device** (本机 Slack 通讯) when the server supports it. Multiple authorized devices can search, read, and post as the Slack user, while only one device receives Bot chats and tasks. Turning off local communications does not revoke the account or affect other devices. Enabling communications on a previously displaced device may open Slack authorization, but never takes over the Bot. Old servers retain the original binding-based behavior.- **Telegram** — under **Settings > IM bots** (the "Cindy" tab), turn on Telegram and choose **Link Telegram**. Open the one-time link, start the official Cindy bot, and complete confirmation if prompted. The same card lets you cancel, retry, open the bot, add it to a group, or unlink; no personal bot token is required.- **Google** (Gmail / Calendar / Drive / Sheets) — handled by the Filo Google plugin (Plugins > Filo Google).- **GitHub** — handled by the Cindy GitHub plugin (Plugins > Cindy GitHub; existing PAT connections are migrated automatically). This connection is optional for `/issue`: feedback uses Cindy's official bot by default, and a working GitHub connection only adds the option to submit as yourself.diff --git a/apps/desktop/help-knowledge/integrations.md b/apps/desktop/help-knowledge/integrations.mdindex 6a7267972f..68c8d33407 100644--- a/apps/desktop/help-knowledge/integrations.md+++ b/apps/desktop/help-knowledge/integrations.md@@ -6,7 +6,7 @@ summary: Supported external services — FeiShu, Slack, Telegram, Discord, GooglAt a glance, Cindy integrates with:- **FeiShu (Lark)** — DM-style bot notifications and interaction (Settings > IM bots). See the FeiShu bot topic. (FeiShu is no longer a sign-in method for Cindy itself.)-- **Slack** — one binding (Settings > IM bots, the "Cindy" tab) powers both directions: the Slack channel bot for receiving tasks, and agent Slack tools (search / read history / post as the bound user) available in every session.+- **Slack** — Settings > IM bots (the "Cindy" tab) manages workspace connections. With a compatible server, **Slack Communications on This Device** enables agent tools (search / read history / post as the authorized user) independently on multiple devices; Bot chats and tasks still go to a single receiving device. Enabling communications does not change that receiver.- **Telegram** — link your Telegram account to the official Cindy bot under Settings > IM bots (the "Cindy" tab). No bot token is required. Telegram tasks use the same local projects and Cindy sessions as Slack, while keeping channel-specific project and model preferences separate.- **Discord** — a Discord bot you bring yourself (your own Discord App + bot token) under Settings > IM bots.- **Google** — Gmail / Calendar / Drive / Sheets, via the Filo Google plugin (Plugins > Filo Google).diff --git a/apps/desktop/src/main/hook-control/__tests__/slackCommunicationsIpc.test.ts b/apps/desktop/src/main/hook-control/__tests__/slackCommunicationsIpc.test.tsnew file mode 100644index 0000000000..4bc7cd4efd--- /dev/null+++ b/apps/desktop/src/main/hook-control/__tests__/slackCommunicationsIpc.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it, vi } from 'vitest';+import type { SlackHookView } from '../../../shared/hookControlIpc.js';+import { setSlackCommunicationsFromIpc } from '../slackCommunicationsIpc.js';++describe('Slack communications IPC', () => {+ function harness(supported = true) {+ const snapshot = () => ({+ serverSlackCommunications: supported,+ bindings: [{ teamId: 'T1' }],+ }) as SlackHookView;+ return { snapshot, setSlackCommunications: vi.fn(async () => ({ ok: true as const, result: {} })) };+ }+ it('只修改本机已知 workspace', async () => {+ const manager = harness();+ expect(await setSlackCommunicationsFromIpc(manager, { teamId: 'T1', enabled: false })).toEqual({ hook: manager.snapshot() });+ expect(manager.setSlackCommunications).toHaveBeenCalledWith('T1', false);+ });+ it.each([null, {}, { teamId: 'T1', enabled: 'true' }, { teamId: 'T2', enabled: true }, { teamId: 'x'.repeat(129), enabled: true }])('拒绝非法或越权参数 %j', async (payload) => {+ const manager = harness();+ await expect(setSlackCommunicationsFromIpc(manager, payload)).rejects.toThrow('[INVALID_PARAMS]');+ expect(manager.setSlackCommunications).not.toHaveBeenCalled();+ });+ it('旧 server fail closed,不发送新版操作', async () => {+ const manager = harness(false);+ await expect(setSlackCommunicationsFromIpc(manager, { teamId: 'T1', enabled: true })).rejects.toThrow('[HOOK_MULTI_TEAM_UNSUPPORTED]');+ expect(manager.setSlackCommunications).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.tsindex 60aa4a67b4..601da27eb9 100644--- a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts@@ -3355,6 +3355,142 @@ describe('内置 chat 伪目录的清单注入', () => {});});+describe('Slack 本机通讯与 Bot 设备分离', () => {+ function communicationsHarness(features = ['slack-tools', 'multi-team', 'slack-communications']) {+ const frames: HookMessage[] = [];+ const transports: HookTransportOpts[] = [];+ const manager = makeManager(memoryStore({ url: 'wss://hook.example.test' }), {+ createTransport: (opts) => {+ transports.push(opts);+ return { send: (msg) => { frames.push(msg); return true; }, dispose: () => {} };+ },+ });+ cleanups.push(() => manager.dispose());+ manager.sync();+ const opts = transports[0];+ opts.onWelcome?.({ serverName: 'mock', features });+ opts.onStatus('connected', null);+ const receive = (msg: HookMessage) => opts.onMessage(msg, () => true);+ return { manager, frames, receive };+ }+ const row = { teamId: 'T1', teamName: 'Workspace', slackUserId: 'U1', slackUserName: 'tester' };++ it.each(['snapshot', 'connected'] as const)('旧 multi-team 的缓存行不阻断自动绑定:%s', async (entry) => {+ const { manager, frames, receive } = communicationsHarness(['slack-tools', 'multi-team']);+ receive(makeBindState({ bindings: [row] }));+ if (entry === 'snapshot') manager.armAutoBind();+ receive(makeBindState({ bindings: [] }));+ expect(manager.snapshot().bindings).toEqual([expect.objectContaining({ displaced: true })]);+ if (entry === 'connected') {+ manager.armAutoBind();+ manager.setProviderEnabled('slack', true);+ }+ await vi.waitFor(() => expect(frames.filter((frame) => frame.type === 'bind.start')).toHaveLength(1));+ });++ it('旧 multi-team 只剩缓存行时,首次授权失败仍关闭总连接', () => {+ const { manager, receive } = communicationsHarness(['slack-tools', 'multi-team']);+ receive(makeBindState({ bindings: [row] }));+ receive(makeBindState({ bindings: [] }));+ receive(makeBindUpdate({ state: 'denied', slackUserId: null, slackUserName: null, message: null }));+ expect(manager.snapshot().enabled).toBe(false);+ });++ it.each([true, false])('权威通讯授权 enabled=%s 时,自动恢复与重复开启均不抢 Bot', async (enabled) => {+ const { manager, frames, receive } = communicationsHarness();+ manager.armAutoBind();+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled }] }));+ manager.armAutoBind();+ manager.setProviderEnabled('slack', true);+ receive(makeBindUpdate({ state: 'denied', slackUserId: null, slackUserName: null, message: null }));+ expect(manager.snapshot().enabled).toBe(true);+ expect(frames.some((frame) => frame.type === 'bind.start')).toBe(false);+ });++ it('同 workspace 的异常跨身份快照不得把 U2 通讯权限授予 U1 Bot 卡片', () => {+ const { manager, receive } = communicationsHarness();+ receive(makeBindState({ bindings: [row], communications: [{ ...row, slackUserId: 'U2', enabled: true }] }));+ expect(manager.snapshot().bindings).toEqual([expect.objectContaining({ slackUserId: 'U1', displaced: false, communicationsEnabled: undefined })]);+ expect(manager.getSlackToolAvailability().bound).toBe(false);+ });++ it('权威快照恢复被顶设备通讯;关闭再开启只发通讯请求,不发换绑', async () => {+ const { manager, frames, receive } = communicationsHarness();+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: true }] }));+ expect(manager.snapshot().bindings).toEqual([expect.objectContaining({ displaced: true, communicationsEnabled: true })]);+ expect(manager.getSlackToolAvailability().bound).toBe(true);+ manager.setProviderEnabled('slack', true); // 重复开启总连接也不能发起 Bot 授权。+ const off = manager.setSlackCommunications('T1', false);+ const request = frames.at(-1)!;+ expect(request).toMatchObject({ type: 'tool.request', payload: { tool: 'communications.set', teamId: 'T1', args: { enabled: false } } });+ if (request.type !== 'tool.request') throw new Error('unreachable');+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: false }] }));+ receive(makeToolResponse({ replyTo: request.payload.requestId, ok: true, result: { enabled: false } }));+ expect((await off).ok).toBe(true);+ expect(manager.getSlackToolAvailability().bound).toBe(false);+ const on = manager.setSlackCommunications('T1', true);+ const enable = frames.at(-1)!;+ if (enable.type !== 'tool.request') throw new Error('unreachable');+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: true }] }));+ receive(makeToolResponse({ replyTo: enable.payload.requestId, ok: true, result: { enabled: true } }));+ expect((await on).ok).toBe(true);+ expect(manager.getSlackToolAvailability().bound).toBe(true);+ expect(frames.some((f) => f.type === 'bind.start' || f.type === 'bind.revoke')).toBe(false);+ receive(makeBindState({ bindings: [], communications: [] }));+ expect(manager.getSlackToolAvailability().bound).toBe(false);+ });++ it('存量被顶设备需重新 OAuth 时显式只授权通讯,confirmed 不恢复 Bot 绑定', async () => {+ const { manager, frames, receive } = communicationsHarness();+ receive(makeBindState({ bindings: [row], communications: [] }));+ receive(makeBindState({ bindings: [], communications: [] }));+ const enable = manager.setSlackCommunications('T1', true);+ const request = frames.at(-1)!;+ if (request.type !== 'tool.request') throw new Error('unreachable');+ receive(makeToolResponse({ replyTo: request.payload.requestId, ok: false, error: { code: 'NOT_BOUND', message: 'no grant' } }));+ expect((await enable).ok).toBe(true);+ expect(frames.at(-1)).toMatchObject({ type: 'bind.start', payload: { teamId: 'T1', purpose: 'communications' } });+ receive(makeBindUpdate({ state: 'pending', purpose: 'communications', authorizeUrl: 'https://example.test/oauth', slackUserId: null, slackUserName: null, message: null }));+ expect(manager.snapshot().pendingBind?.purpose).toBe('communications');+ receive(makeBindUpdate({ ...row, state: 'confirmed', purpose: 'communications', message: null }));+ expect(manager.snapshot().bindings[0].displaced).toBe(true);+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: true }] }));+ expect(manager.getSlackToolAvailability().bound).toBe(true);+ });++ it('迟到的删除回包不能移除已经恢复的 Bot 接收行', async () => {+ const { manager, frames, receive } = communicationsHarness();+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: true }] }));+ const removal = manager.revokeTeam('T1');+ const request = frames.at(-1)!;+ if (request.type !== 'tool.request') throw new Error('unreachable');+ receive(makeBindState({ bindings: [row], communications: [{ ...row, enabled: true }] }));+ receive(makeToolResponse({ replyTo: request.payload.requestId, ok: true, result: { removed: true } }));+ expect(await removal).toBe(true);+ expect(manager.snapshot().bindings[0]).toMatchObject({ ...row, displaced: false });+ });++ it('旧身份的迟到失败不能给新身份打开 OAuth', async () => {+ const { manager, frames, receive } = communicationsHarness();+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: false }] }));+ const enabling = manager.setSlackCommunications('T1', true);+ const request = frames.at(-1)!;+ if (request.type !== 'tool.request') throw new Error('unreachable');+ receive(makeBindState({ bindings: [], communications: [{ ...row, slackUserId: 'U2', enabled: true }] }));+ receive(makeToolResponse({ replyTo: request.payload.requestId, ok: false, error: { code: 'NOT_BOUND', message: 'changed' } }));+ expect((await enabling).ok).toBe(false);+ expect(frames.some((f) => f.type === 'bind.start')).toBe(false);+ });++ it('旧 server 不可开启通讯模式,也不相信多余的通讯快照字段', async () => {+ const { manager, frames, receive } = communicationsHarness(['slack-tools', 'multi-team']);+ receive(makeBindState({ bindings: [], communications: [{ ...row, enabled: true }] }));+ expect(manager.getSlackToolAvailability().bound).toBe(false);+ expect(await manager.setSlackCommunications('T1', true)).toMatchObject({ ok: false, error: { code: 'SERVER_TOO_OLD' } });+ expect(frames.some((f) => f.type === 'bind.start')).toBe(false);+ });+});+describe('Slack 网关工具代理(tool.request/tool.response)', () => {/** 建连 -> welcome(带/不带 slack-tools)-> 绑定 confirmed 的通用起手。 */async function connectWithTools(opts: {diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex 9c3f9612c5..1e6dbacdc4 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -108,6 +108,7 @@ import { resetTelegramSpeakerRegistrationCache } from '../im/telegram/contactsAuimport { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { getAgentIslandService } from '../agent-island/service.js';import { setLifecycleAnnouncementFromIpc } from './lifecycleAnnouncementIpc.js';+import { setSlackCommunicationsFromIpc } from './slackCommunicationsIpc.js';const log = createLogger('hook-control');@@ -913,14 +914,18 @@ export function registerHookControlIpc(): void {return runMultiTeamAction((mgr) => mgr.rebindTeam(teamId));});- registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.REVOKE_TEAM, (_e, payload) => {+ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.SET_SLACK_COMMUNICATIONS, (_e, payload) => {+ requireHookControl();+ return setSlackCommunicationsFromIpc(ensureInstances().manager, payload);+ });++ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.REVOKE_TEAM, async (_e, payload) => {requireHookControl();const p = requireObject(payload);const teamId = requireString(p.teamId, 'teamId');- // displaced 行的删除是纯本地操作, 离线也要能删 —— 不做 multi-team 能力- // 前置检查(manager 内部区分 displaced/活跃行)+ // manager 区分旧 server 本地缓存清理、新 server 通讯 grant 撤销和 Bot 解绑。const mgr = ensureInstances().manager;- if (!mgr.revokeTeam(teamId)) {+ if (!await mgr.revokeTeam(teamId)) {throwIpcError('HOOK_NOT_CONNECTED', 'slack hook is not connected');}return { hook: mgr.snapshot() };diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.tsindex 640fd1c6bb..956c6e5bd0 100644--- a/apps/desktop/src/main/hook-control/manager.ts+++ b/apps/desktop/src/main/hook-control/manager.ts@@ -296,10 +296,11 @@ export interface HookControlManager {/** (multi-team)给指定 team 重新授权(bind.start 带 teamId, pin 授权页)。 */rebindTeam(teamId: string): boolean;/**- * (multi-team)解绑指定 team。displaced 行 = 仅清本地缓存(服务端本就没有该- * 绑定, 离线也能删); 活跃行 = 发 bind.revoke{teamId} 并乐观移除(需在线)。+ * (multi-team)解绑指定 team。新 server 的通讯专用行需在线撤销本机 grant;+ * 旧 server 的 displaced 行仅清本地缓存;Bot 活跃行走 bind.revoke。*/- revokeTeam(teamId: string): boolean;+ revokeTeam(teamId: string): boolean | Promise<boolean>;+ setSlackCommunications(teamId: string, enabled: boolean): Promise<HookSlackToolResult>;/*** (multi-team)取消在途授权: 本地清 pendingBind, 在线时发 bind.revoke* {pendingOnly:true} 作废 server 侧登记(pending 授权 / 等安装)。幂等。@@ -389,14 +390,14 @@ export type HookSlackToolResult =/** Slack 工具可用性快照。 */export interface HookSlackToolAvailability {connected: boolean;- /** 绑定已 confirmed(multi-team 下 = 至少一条未 displaced 的绑定)。 */+ /** 至少一个 workspace 可通讯;新 server 不要求本机是 Bot 接收设备。 */bound: boolean;/** server 已宣告 slack-tools 能力(welcome.features)。 */serverSupportsTools: boolean;binding: HookBindingView | null;/** server 已宣告 multi-team 能力(true 时非 status 工具必须带 teamId)。 */multiTeam: boolean;- /** (multi-team)可用绑定清单(不含 displaced 行), 供 slack_status / 工具描述消费。 */+ /** (multi-team)可通讯的 workspace 清单,供 slack_status / 工具描述消费。 */bindings: Array<{ teamId: string; teamName: string | null }>;}@@ -969,6 +970,21 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContreturn multiBindings.filter((b) => !b.displaced);}+ /** 自动绑定/授权终态只认实际连接:Bot 绑定或权威通讯授权(含显式关闭)。+ * displaced 展示缓存不算连接;旧 multi-team 服务端保持只认 Bot 绑定的语义。 */+ function hasRetainedSlackConnection(): boolean {+ const communicationsSupported = serverFeatures.includes('slack-communications');+ return multiBindings.some((row) =>+ !row.displaced || (communicationsSupported && row.communicationsEnabled !== undefined),+ );+ }++ function communicationBindings(): HookTeamBindingView[] {+ return serverFeatures.includes('slack-communications')+ ? multiBindings.filter((b) => b.communicationsEnabled === true)+ : activeBindings();+ }+/** Slack 偏好镜像只认 live confirmed, 不含离线乐观绑定。 */function slackBoundForPrefsMirror(): boolean {return multiTeamKnown() ? activeBindings().length > 0 : binding?.state === 'confirmed';@@ -984,7 +1000,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 在本地/服务端, 必须用 enabled 把工具面关掉); 老 server: 关开关会把// binding 置 none, confirmed 判据自足, enabled 条件恒真不改变行为。const bound = multiTeamKnown()- ? activeBindings().length > 0 && store.get().enabled+ ? communicationBindings().length > 0 && store.get().enabled: binding?.state === 'confirmed';const next = bound && serverFeatures.includes(HOOK_FEATURE_SLACK_TOOLS);if (next === slackToolProviderEnabled) return;@@ -1288,6 +1304,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContbindings: multiBindings.map((b) => ({ ...b })),pendingBind: pendingBind !== null ? { ...pendingBind } : null,serverMultiTeam: serverMultiTeam(),+ serverSlackCommunications: serverFeatures.includes('slack-communications'),telegram: laneView(telegramLane),x: laneView(xLane),};@@ -1719,7 +1736,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont}autoBindIntent = false;openAuthorizeOnNextPending = false;- if (activeBindings().length > 0) {+ if (hasRetainedSlackConnection()) {if (transport !== null && status === 'connected') {transport.send(makeBindRevoke({ pendingOnly: true }));}@@ -1758,7 +1775,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContif (pendingBind?.state !== 'pending') return;autoBindIntent = false;openAuthorizeOnNextPending = false;- if (activeBindings().length > 0) {+ if (hasRetainedSlackConnection()) {// 已有可用绑定: 只作废这次"添加/重绑"授权(server 侧登记顺手作废),// 总开关与既有绑定不受影响if (transport !== null && status === 'connected') {@@ -1830,9 +1847,13 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont* (multi-team)发起添加/重绑授权: bind.start 带可选 teamId(重绑时 pin* 授权页), 乐观置 pendingBind 并臂授权看门狗。false = 发不出(未连接)。*/- function initiateMultiBind(teamId: string | null): boolean {+ function initiateMultiBind(teamId: string | null, purpose?: 'communications'): boolean {if (transport === null || status !== 'connected') return false;- if (!transport.send(makeBindStart(teamId !== null ? { teamId } : {}))) return false;+ const request = makeBindStart({+ ...(teamId !== null ? { teamId } : {}),+ ...(purpose ? { purpose } : {}),+ });+ if (!transport.send(request)) return false;openAuthorizeOnNextPending = true;pendingBind = {state: 'pending',@@ -1842,6 +1863,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContinstallUrl: null,teamId,intent: teamId !== null ? 'rebind' : 'add',+ ...(purpose ? { purpose } : {}),};armBindWatchdog();notifyStatus(toView());@@ -1908,7 +1930,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContopenAuthorizeOnNextPending = false;pendingBind = null;const teamId = payload.teamId ?? null;- if (teamId !== null && payload.slackUserId !== null) {+ if (teamId !== null && payload.slackUserId !== null && payload.purpose !== 'communications') {const row: HookTeamBindingView = {teamId,teamName: payload.teamName ?? null,@@ -1988,7 +2010,9 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont}// pending / denied / expired / failed → 在途授权状态const authorizeUrl = payload.authorizeUrl ?? null;+ if (payload.purpose === 'communications') autoBindIntent = false;pendingBind = {+ purpose: payload.purpose ?? pendingBind?.purpose,state,message: payload.message,authorizeUrl,@@ -2043,7 +2067,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContif (terminal) {autoBindIntent = false;clearAutoBindDefer();- if (activeBindings().length === 0 && store.get().enabled) {+ if (!hasRetainedSlackConnection() && store.get().enabled) {store.setEnabled(false);stopSlack();log.info(`slack hook auto-disabled on first-bind ${state} (multi-team)`);@@ -2144,16 +2168,25 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 上一轮)但快照缺失的 team 保留为 displaced 行 —— 覆盖「绑定在本机// 离线期间被另一台设备顶掉」的冷启动场景(实时被顶走 revoked 事件)。const snap = msg.payload.bindings;- const snapIds = new Set(snap.map((e) => e.teamId));+ const communications = serverFeatures.includes('slack-communications') ? msg.payload.communications ?? [] : [];+ const grants = new Map(communications.map((e) => [e.teamId, e]));+ const snapIds = new Set([...snap, ...communications].map((e) => e.teamId));const next: HookTeamBindingView[] = snap.map((e) => ({teamId: e.teamId,teamName: e.teamName,slackUserId: e.slackUserId,slackUserName: e.slackUserName,displaced: false,+ // 单 workspace 卡代表单一身份;异常跨身份快照 fail closed,不把 U2 权限授予 U1。+ communicationsEnabled: grants.get(e.teamId)?.slackUserId === e.slackUserId ? grants.get(e.teamId)?.enabled : undefined,}));+ for (const grant of communications) {+ if (!next.some((row) => row.teamId === grant.teamId)) {+ next.push({ ...grant, displaced: true, communicationsEnabled: grant.enabled });+ }+ }for (const row of multiBindings) {- if (!snapIds.has(row.teamId)) next.push({ ...row, displaced: true });+ if (!snapIds.has(row.teamId)) next.push({ ...row, displaced: true, communicationsEnabled: undefined });}multiBindings = next;persistBindingsCache();@@ -2163,8 +2196,8 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 先让它走「pending + 意图 → 重新发起」路径签新链接; 短窗内没有任何// bind.update 才由计时器发空 bind.start(见 autoBindDefer 声明注释)。if (autoBindIntent) {- if (activeBindings().length > 0) {- autoBindIntent = false; // 已有绑定, 秒恢复, 无需发起授权+ if (hasRetainedSlackConnection()) {+ autoBindIntent = false; // 已有绑定或通讯授权, 秒恢复, 无需发起授权} else if (autoBindDefer === null) {autoBindDefer = setTimeout(() => {autoBindDefer = null;@@ -2908,6 +2941,17 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContrevokeTeam(teamId) {const idx = multiBindings.findIndex((b) => b.teamId === teamId);if (idx < 0) return true; // 行已不在(重复点击/竞态), 幂等成功+ if (multiBindings[idx].displaced && serverFeatures.includes('slack-communications')) {+ const target = multiBindings[idx];+ return this.callSlackTool('communications.remove', {}, teamId).then((result) => {+ if (!result.ok && result.error.code !== 'NOT_BOUND') return false;+ multiBindings = multiBindings.filter((b) => b.teamId !== teamId || !b.displaced || b.slackUserId !== target.slackUserId);+ persistBindingsCache();+ notifySlackToolProviderEnabledIfChanged();+ notifyStatus(toView());+ return true;+ });+ }if (multiBindings[idx].displaced) {// displaced 行: 服务端本就没有该绑定, 删除 = 仅清本地缓存(离线可用)multiBindings.splice(idx, 1);@@ -2939,6 +2983,30 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContnotifyStatus(toView());return true;},+ async setSlackCommunications(teamId, enabled) {+ if (!serverFeatures.includes('slack-communications')) {+ return { ok: false, error: { code: 'SERVER_TOO_OLD', message: 'Slack server does not support device communications' } };+ }+ const target = multiBindings.find((b) => b.teamId === teamId);+ if (!target) return { ok: false, error: { code: 'NOT_BOUND', message: 'Unknown Slack workspace' } };+ const pendingBefore = pendingBind;+ if (pendingBefore?.state === 'pending') {+ return { ok: false, error: { code: 'BUSY', message: 'Slack authorization is in progress' } };+ }+ const result = await this.callSlackTool('communications.set', { enabled }, teamId);+ if (+ !result.ok && enabled &&+ ['NOT_BOUND', 'NO_USER_TOKEN', 'TOKEN_EXPIRED'].includes(result.error.code) &&+ pendingBind === pendingBefore &&+ multiBindings.some((b) => b.teamId === teamId && b.slackUserId === target.slackUserId)+ ) {+ // 存量被顶设备或撤权后恢复:重新 OAuth 只授予通讯,绝不重新接管 Bot。+ if (initiateMultiBind(teamId, 'communications')) {+ return { ok: true, result: { authorizing: true } };+ }+ }+ return result;+ },callSlackTool(tool, args, teamId) {const fail = (code: string, message: string): Promise<HookSlackToolResult> =>Promise.resolve({ ok: false, error: { code, message } });@@ -2946,8 +3014,9 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContif (t === null || status !== 'connected') {return fail('HOOK_NOT_CONNECTED', 'Slack 连接不在线, 请检查 设置 → Slack 开关与网络');}- const bound = multiTeamKnown() ? activeBindings().length > 0 : binding?.state === 'confirmed';- if (!bound) {+ const isCommunicationControl = serverFeatures.includes('slack-communications') && (tool === 'communications.set' || tool === 'communications.remove');+ const bound = multiTeamKnown() ? communicationBindings().length > 0 : binding?.state === 'confirmed';+ if (!bound && !isCommunicationControl && !(tool === 'status' && serverFeatures.includes('slack-communications'))) {return fail('NOT_BOUND', '本设备未绑定 Slack, 请先到 设置 → Slack 完成绑定');}// 老 server 不认识 tool.request(丢帧不应答): 按能力宣告短路, 不打空炮@@ -2993,12 +3062,12 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 已关的设备上 cindy_slack 工具面仍会挂进新会话(老路径关开关会把// binding 归零, confirmed 判据自足)bound: multi- ? store.get().enabled && activeBindings().length > 0+ ? store.get().enabled && communicationBindings().length > 0: binding?.state === 'confirmed',serverSupportsTools: serverFeatures.includes(HOOK_FEATURE_SLACK_TOOLS),binding: multi ? legacyBindingView() : binding,multiTeam: serverMultiTeam(),- bindings: activeBindings().map((b) => ({ teamId: b.teamId, teamName: b.teamName })),+ bindings: communicationBindings().map((b) => ({ teamId: b.teamId, teamName: b.teamName })),};},getWorkspacePrefs() {@@ -3034,7 +3103,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 幂等重复开启已连接的 Slack 时不会收到新的状态回放,直接消费// armAutoBind 意图;首次开启走上面的 startSlack + 服务端回放路径。if (serverMultiTeam()) {- if (activeBindings().length > 0) autoBindIntent = false;+ if (hasRetainedSlackConnection()) autoBindIntent = false;else if (initiateMultiBind(null)) autoBindIntent = false;} else if (binding?.state === 'confirmed') {autoBindIntent = false;diff --git a/apps/desktop/src/main/hook-control/slackCommunicationsIpc.ts b/apps/desktop/src/main/hook-control/slackCommunicationsIpc.tsnew file mode 100644index 0000000000..4dcb085719--- /dev/null+++ b/apps/desktop/src/main/hook-control/slackCommunicationsIpc.ts@@ -0,0 +1,19 @@+import type { HookControlManager } from './manager.js';+import { requireObject, throwIpcError } from '../utils/ipcValidate.js';++/** Main validates both the input and workspace ownership before requesting a change. */+export async function setSlackCommunicationsFromIpc(+ manager: Pick<HookControlManager, 'snapshot' | 'setSlackCommunications'>,+ payload: unknown,+) {+ const p = requireObject(payload);+ if (typeof p.teamId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(p.teamId) || typeof p.enabled !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'Expected Slack teamId and boolean enabled');+ }+ const view = manager.snapshot();+ if (!view.serverSlackCommunications) throwIpcError('HOOK_MULTI_TEAM_UNSUPPORTED', 'Slack server does not support device communications');+ if (!view.bindings.some((b) => b.teamId === p.teamId)) throwIpcError('INVALID_PARAMS', 'Unknown Slack workspace');+ const result = await manager.setSlackCommunications(p.teamId, p.enabled);+ if (!result.ok) throwIpcError('HOOK_NOT_CONNECTED', 'Could not update local Slack communications');+ return { hook: manager.snapshot() };+}diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex 03325602d8..242ac70e00 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -40,7 +40,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [id: "connections",title: "Connecting external accounts",summary: "External accounts (Google, Jira / Confluence, GitHub, GitLab) are connected on their plugin detail pages under Plugins; Slack and Telegram are bound under Settings > IM bots; Codex sign-in lives in Settings > Model Providers.",- content: "External account connections have moved out of the old \"Third-Party Platforms\" section — each integration now lives on its own plugin detail page under **Plugins**, and the plugin's tools use the account you connect there.\n\n**Where to connect what:**\n\n- **Slack** — bound with a single toggle under **Settings > IM bots** (the \"Cindy\" tab). One browser sign-in covers both directions: the Slack channel bot that receives tasks, and the agent Slack tools (search / read / post). If Slack tools don't work on an older binding, toggle it off and on once to re-authorize.\n- **Telegram** — under **Settings > IM bots** (the \"Cindy\" tab), turn on Telegram and choose **Link Telegram**. Open the one-time link, start the official Cindy bot, and complete confirmation if prompted. The same card lets you cancel, retry, open the bot, add it to a group, or unlink; no personal bot token is required.\n- **Google** (Gmail / Calendar / Drive / Sheets) — handled by the Filo Google plugin (Plugins > Filo Google).\n- **GitHub** — handled by the Cindy GitHub plugin (Plugins > Cindy GitHub; existing PAT connections are migrated automatically). This connection is optional for `/issue`: feedback uses Cindy's official bot by default, and a working GitHub connection only adds the option to submit as yourself.\n- **GitLab** — handled by the Cindy GitLab plugin (Plugins > Cindy GitLab; existing PAT connections are migrated automatically).\n- **Codex** — sign in under Settings > Model Providers (separate from the Codex CLI binary the app ships with).\n- **FeiShu** — bot only (App ID / Secret under Settings > IM bots; see the FeiShu bot topic). FeiShu is no longer a sign-in method for Cindy itself.\n- **Cindy AI** — Settings > Model Providers. Web-search keys are configured on the matching plugin detail page (Cindy Web Search).\n\n**Managing connections:**\n\n- Each plugin detail page shows the connected accounts (with status) and lets you reconnect, disconnect, or switch the default account.\n- Disconnect removes the local token only; you may also want to revoke access on the provider's side.\n- A connection error usually means the token expired or was revoked on the provider's side; reconnect to refresh.",+ content: "External account connections have moved out of the old \"Third-Party Platforms\" section — each integration now lives on its own plugin detail page under **Plugins**, and the plugin's tools use the account you connect there.\n\n**Where to connect what:**\n\n- **Slack** — connect under **Settings > IM bots** (the \"Cindy\" tab). Each workspace has **Slack Communications on This Device** (本机 Slack 通讯) when the server supports it. Multiple authorized devices can search, read, and post as the Slack user, while only one device receives Bot chats and tasks. Turning off local communications does not revoke the account or affect other devices. Enabling communications on a previously displaced device may open Slack authorization, but never takes over the Bot. Old servers retain the original binding-based behavior.\n- **Telegram** — under **Settings > IM bots** (the \"Cindy\" tab), turn on Telegram and choose **Link Telegram**. Open the one-time link, start the official Cindy bot, and complete confirmation if prompted. The same card lets you cancel, retry, open the bot, add it to a group, or unlink; no personal bot token is required.\n- **Google** (Gmail / Calendar / Drive / Sheets) — handled by the Filo Google plugin (Plugins > Filo Google).\n- **GitHub** — handled by the Cindy GitHub plugin (Plugins > Cindy GitHub; existing PAT connections are migrated automatically). This connection is optional for `/issue`: feedback uses Cindy's official bot by default, and a working GitHub connection only adds the option to submit as yourself.\n- **GitLab** — handled by the Cindy GitLab plugin (Plugins > Cindy GitLab; existing PAT connections are migrated automatically).\n- **Codex** — sign in under Settings > Model Providers (separate from the Codex CLI binary the app ships with).\n- **FeiShu** — bot only (App ID / Secret under Settings > IM bots; see the FeiShu bot topic). FeiShu is no longer a sign-in method for Cindy itself.\n- **Cindy AI** — Settings > Model Providers. Web-search keys are configured on the matching plugin detail page (Cindy Web Search).\n\n**Managing connections:**\n\n- Each plugin detail page shows the connected accounts (with status) and lets you reconnect, disconnect, or switch the default account.\n- Disconnect removes the local token only; you may also want to revoke access on the provider's side.\n- A connection error usually means the token expired or was revoked on the provider's side; reconnect to refresh.",},{id: "feishu-bot",@@ -66,7 +66,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [id: "integrations",title: "What Cindy integrates with",summary: "Supported external services — FeiShu, Slack, Telegram, Discord, Google, Jira / Confluence, GitHub, GitLab — and what's not supported.",- content: "At a glance, Cindy integrates with:\n\n- **FeiShu (Lark)** — DM-style bot notifications and interaction (Settings > IM bots). See the FeiShu bot topic. (FeiShu is no longer a sign-in method for Cindy itself.)\n- **Slack** — one binding (Settings > IM bots, the \"Cindy\" tab) powers both directions: the Slack channel bot for receiving tasks, and agent Slack tools (search / read history / post as the bound user) available in every session.\n- **Telegram** — link your Telegram account to the official Cindy bot under Settings > IM bots (the \"Cindy\" tab). No bot token is required. Telegram tasks use the same local projects and Cindy sessions as Slack, while keeping channel-specific project and model preferences separate.\n- **Discord** — a Discord bot you bring yourself (your own Discord App + bot token) under Settings > IM bots.\n- **Google** — Gmail / Calendar / Drive / Sheets, via the Filo Google plugin (Plugins > Filo Google).\n- **GitHub / GitLab** — via the Cindy GitHub and Cindy GitLab plugins (Plugins).\n- **The coding agents** — Claude Code and Codex can reach pay-per-token models through **Cindy AI** in Settings > Model Providers.\n\n**Not supported:**\n\n- There is no built-in Microsoft Teams integration. For chat notifications, use the FeiShu, Slack, Telegram, or Discord bot.\n- There's no native Linear integration as a first-party feature — those would have to come via an MCP a user installs themselves.\n\n**Notes:**\n\n- Most of these connections are accessed by the agents through their tools (plugins / MCPs), not directly by the desktop app. Connecting on the plugin detail page is what gives its tools access to your account.",+ content: "At a glance, Cindy integrates with:\n\n- **FeiShu (Lark)** — DM-style bot notifications and interaction (Settings > IM bots). See the FeiShu bot topic. (FeiShu is no longer a sign-in method for Cindy itself.)\n- **Slack** — Settings > IM bots (the \"Cindy\" tab) manages workspace connections. With a compatible server, **Slack Communications on This Device** enables agent tools (search / read history / post as the authorized user) independently on multiple devices; Bot chats and tasks still go to a single receiving device. Enabling communications does not change that receiver.\n- **Telegram** — link your Telegram account to the official Cindy bot under Settings > IM bots (the \"Cindy\" tab). No bot token is required. Telegram tasks use the same local projects and Cindy sessions as Slack, while keeping channel-specific project and model preferences separate.\n- **Discord** — a Discord bot you bring yourself (your own Discord App + bot token) under Settings > IM bots.\n- **Google** — Gmail / Calendar / Drive / Sheets, via the Filo Google plugin (Plugins > Filo Google).\n- **GitHub / GitLab** — via the Cindy GitHub and Cindy GitLab plugins (Plugins).\n- **The coding agents** — Claude Code and Codex can reach pay-per-token models through **Cindy AI** in Settings > Model Providers.\n\n**Not supported:**\n\n- There is no built-in Microsoft Teams integration. For chat notifications, use the FeiShu, Slack, Telegram, or Discord bot.\n- There's no native Linear integration as a first-party feature — those would have to come via an MCP a user installs themselves.\n\n**Notes:**\n\n- Most of these connections are accessed by the agents through their tools (plugins / MCPs), not directly by the desktop app. Connecting on the plugin detail page is what gives its tools access to your account.",},{id: "memory",diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex d63044957e..f81fd4c977 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4788,6 +4788,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:hook-control:add-binding'),rebindTeam: (teamId: string): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:rebind-team', { teamId }),+ setSlackCommunications: (teamId: string, enabled: boolean): Promise<{ hook: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:set-slack-communications', { teamId, enabled }),revokeTeam: (teamId: string): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:revoke-team', { teamId }),cancelPendingBind: (): Promise<{ hook: unknown }> =>diff --git a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsxindex 7a7f973d57..55b14790cf 100644--- a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx@@ -582,7 +582,8 @@ export function HookConnectionsSection() {// 缓存行, multiUi 自然回落。const multiUi = hook !== null && (hook.serverMultiTeam || hook.bindings.length > 0);const activeTeams = hook?.bindings.filter((b) => !b.displaced) ?? [];- const displacedCount = (hook?.bindings.length ?? 0) - activeTeams.length;+ const communicationTeams = hook?.serverSlackCommunications ? hook.bindings.filter((b) => b.communicationsEnabled !== undefined) : [];+ const displacedCount = hook?.bindings.filter((b) => b.displaced && b.communicationsEnabled === undefined).length ?? 0;/** 状态行「(M 个待处理)」= 在途/终止态授权 + displaced 行。 */const pendingIssueCount = (hook !== null && hook.pendingBind !== null ? 1 : 0) + displacedCount;@@ -611,9 +612,11 @@ export function HookConnectionsSection() {/** Terminal Slack authorization states restart through the matching main-process flow. */const handleReauthorize = useCallback(- (mode: 'enable' | 'add' | 'rebind', teamId?: string) => {+ (mode: 'enable' | 'add' | 'rebind' | 'communications', teamId?: string) => {const action =- mode === 'enable'+ mode === 'communications' && teamId+ ? () => window.electronAPI.hookControl.setSlackCommunications(teamId, true)+ : mode === 'enable'? () => window.electronAPI.hookControl.setEnabled(true): mode === 'rebind' && teamId? () => window.electronAPI.hookControl.rebindTeam(teamId)@@ -923,30 +926,39 @@ export function HookConnectionsSection() {/*** (multi-team)解绑某 workspace: 走确认弹窗(危险操作文案)。displaced 行的- * "删除"同一入口 —— main 侧按行状态区分(活跃行发 bind.revoke, displaced 行- * 仅清本地缓存), 文案按行状态取。+ * "删除"同一入口 —— main 区分 Bot 解绑、通讯专用授权撤销与旧 server 缓存。+ * 确认文案按行状态和服务端能力取。*/const handleRemoveBinding = async (b: HookTeamBindingView) => {const target = {teamId: b.teamId,slackUserId: b.slackUserId,displaced: b.displaced,+ communicationsEnabled: b.communicationsEnabled,+ serverSlackCommunications: hook?.serverSlackCommunications,};const teamLabel = b.teamName ?? b.teamId;const ok = await confirm({title: t('settings.remoteControl.hook.multi.removeConfirmTitle', { team: teamLabel }),description: b.displaced- ? t('settings.remoteControl.hook.multi.removeDisplacedConfirmDescription')+ ? t(hook?.serverSlackCommunications+ ? 'settings.remoteControl.hook.multi.removeCommunicationsConfirmDescription'+ : 'settings.remoteControl.hook.multi.removeDisplacedConfirmDescription'): t('settings.remoteControl.hook.multi.removeConfirmDescription', { team: teamLabel }),confirmText: t('settings.remoteControl.hook.multi.removeConfirm'),cancelText: t('settings.remoteControl.hook.notInstalled.confirmCancel'),});- const stillSameBinding = hookRef.current?.bindings.some(- (current) =>- current.teamId === target.teamId &&- current.slackUserId === target.slackUserId &&- current.displaced === target.displaced,- );+ // 确认授权撤销后不能因重连旧节点而降级为仅删除本地缓存。+ const currentHook = hookRef.current;+ const stillSameBinding =+ currentHook?.serverSlackCommunications === target.serverSlackCommunications &&+ currentHook?.bindings.some(+ (current) =>+ current.teamId === target.teamId &&+ current.slackUserId === target.slackUserId &&+ current.displaced === target.displaced &&+ current.communicationsEnabled === target.communicationsEnabled,+ );if (!ok || !mountedRef.current || !stillSameBinding) return;runHookAction(() => window.electronAPI.hookControl.revokeTeam(target.teamId));};@@ -959,13 +971,13 @@ export function HookConnectionsSection() {* toggle 视觉开态:* - 单绑定(老 server): 绑定已确认(连接 + 绑定齐备才算"开") —— enabled 只是* 持久化的意图, 连接中 / 授权中 / 待安装期间开关显示为关;- * - multi-team: 有可用绑定即算"开"(不再要求单一 confirmed); 首次 0 绑定- * 授权中仍显示关+「授权中…」, 与现状一致。+ * - multi-team: 有 Bot 绑定或通讯授权(含显式关闭)即算"开";仅有展示缓存+ * 不算稳定连接,首次授权中仍显示关+「授权中…」。* 两种模式都用绑定快照而非连接态承载开态 —— 断线重连的瞬时抖动不弹开关* (连接状态由左侧状态点与状态行表达, 规则 7 不跳变)。*/const toggleChecked = multiUi- ? hook.enabled && activeTeams.length > 0+ ? hook.enabled && (activeTeams.length > 0 || communicationTeams.length > 0): hook.enabled && hook.binding?.state === 'confirmed';/** 在途态(意图已开但尚无可用绑定): 此时再点 toggle = 取消本轮流程(关回)。 */const toggleInProgress = hook.enabled && !toggleChecked;@@ -1000,7 +1012,11 @@ export function HookConnectionsSection() {? t('settings.remoteControl.hook.authorizing'): isNotInstalled? t('settings.remoteControl.hook.notInstalled.status')- : t('settings.remoteControl.hook.statusUnbound')+ : communicationTeams.length > 0+ ? t(communicationTeams.some((b) => b.communicationsEnabled)+ ? 'settings.remoteControl.hook.multi.communicationsActive'+ : 'settings.remoteControl.hook.multi.communicationsInactive')+ : t('settings.remoteControl.hook.statusUnbound'): bindingState === 'confirmed'? hook.binding?.teamName? t('settings.remoteControl.hook.statusBoundTeam', {@@ -1730,7 +1746,7 @@ export function HookConnectionsSection() {{hook.bindings.map((b) => (<divkey={b.teamId}- className="flex items-center gap-2 rounded-xl border border-[var(--border-default)] px-2.5 py-2"+ className="flex flex-wrap items-center gap-2 rounded-xl border border-[var(--border-default)] px-2.5 py-2"><div className="flex min-w-0 flex-1 flex-col gap-0.5"><span className="truncate text-13 font-medium text-[var(--text-primary)]">@@ -1743,8 +1759,8 @@ export function HookConnectionsSection() {{b.displaced ? (<>{/* 被另一台设备顶掉: 标注 + 重新绑定(pin 到该 team 的授权页) */}- <span className="shrink-0 text-11 text-[var(--error-fg)]">- {t('settings.remoteControl.hook.multi.displaced')}+ <span className={`shrink-0 text-11 ${b.communicationsEnabled !== undefined ? 'text-[var(--text-tertiary)]' : 'text-[var(--error-fg)]'}`}>+ {t(b.communicationsEnabled !== undefined ? 'settings.remoteControl.hook.multi.botNotReceiving' : 'settings.remoteControl.hook.multi.displaced')}</span><buttontype="button"@@ -1758,7 +1774,7 @@ export function HookConnectionsSection() {disabled={slackAuthActionPending}className={pillBtn}>- {t('settings.remoteControl.hook.multi.rebind')}+ {t(b.communicationsEnabled !== undefined ? 'settings.remoteControl.hook.multi.receiveBot' : 'settings.remoteControl.hook.multi.rebind')}</button></>) : null}@@ -1770,6 +1786,21 @@ export function HookConnectionsSection() {><Trash2 size={13} /></button>+ {hook.serverSlackCommunications ? (+ <label className="flex basis-full items-center justify-between gap-2 text-12 text-[var(--text-secondary)]">+ {t('settings.remoteControl.hook.multi.localCommunications')}+ <Switch+ checked={b.communicationsEnabled === true}+ disabled={hook.status !== 'connected' || slackAuthActionPending || hook.pendingBind?.state === 'pending'}+ onCheckedChange={(enabled) => runSlackAuthAction(+ () => window.electronAPI.hookControl.setSlackCommunications(b.teamId, enabled),+ 'settings.remoteControl.hook.toast.actionFailed',+ true,+ )}+ aria-label={t('settings.remoteControl.hook.multi.localCommunications')}+ />+ </label>+ ) : null}</div>))}{hook.pendingBind?.state === 'pending' ? (@@ -1866,6 +1897,10 @@ export function HookConnectionsSection() {// (denied/expired/failed/already-bound)即使 server 回显 teamId// 也是「新增」失败, 重试必须回 add 流程让授权页可切换 workspace;// 只有发起时就 pin 到 team 的定向重绑才走 rebindTeam。+ if (pending?.purpose === 'communications' && pending.teamId) {+ handleReauthorize('communications', pending.teamId);+ return;+ }const rebindIntent = pending?.intent === 'rebind';handleReauthorize(rebindIntent ? 'rebind' : 'add',diff --git a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsxindex 93af3f8b36..bd0e2b36d5 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx@@ -10,6 +10,7 @@ const ipc = vi.hoisted(() => ({onStatusChanged: vi.fn<(listener: (view: SlackHookView) => void) => () => void>(() => () => {}),setEnabled: vi.fn(),setLifecycleAnnouncement: vi.fn(),+ setSlackCommunications: vi.fn(),providerBindStart: vi.fn(),providerBindCancel: vi.fn(),providerBindRevoke: vi.fn(),@@ -182,6 +183,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {onStatusChanged: ipc.onStatusChanged,setEnabled: ipc.setEnabled,setLifecycleAnnouncement: ipc.setLifecycleAnnouncement,+ setSlackCommunications: ipc.setSlackCommunications,providerBindStart: ipc.providerBindStart,providerBindCancel: ipc.providerBindCancel,providerBindRevoke: ipc.providerBindRevoke,@@ -252,6 +254,39 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {);});+ it.each([true, false])('displaced workspace communications toggle (%s) never invokes Bot rebind or revoke', async (enabled) => {+ const row = { teamId: 'T1', teamName: 'Workspace', slackUserId: 'U1', slackUserName: 'tester', displaced: true, communicationsEnabled: enabled };+ const view: SlackHookView = { ...BASE_HOOK, enabled: true, status: 'connected', serverMultiTeam: true, serverSlackCommunications: true, bindings: [row] };+ ipc.get.mockResolvedValue({ hook: view });+ ipc.setSlackCommunications.mockResolvedValue({ hook: { ...view, bindings: [{ ...row, communicationsEnabled: !enabled }] } });+ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ const toggle = await screen.findByRole('switch', { name: 'settings.remoteControl.hook.multi.localCommunications' });+ const masterToggle = screen.getByRole('switch', { name: 'settings.remoteControl.hook.toggleAria' });+ expect(masterToggle.getAttribute('aria-checked')).toBe('true');+ expect(toggle.getAttribute('aria-checked')).toBe(String(enabled));+ fireEvent.click(toggle);+ await waitFor(() => expect(ipc.setSlackCommunications).toHaveBeenCalledWith('T1', !enabled));+ expect(masterToggle.getAttribute('aria-checked')).toBe('true');+ fireEvent.click(masterToggle);+ await waitFor(() => expect(ipc.setEnabled).toHaveBeenCalledWith(false));+ expect(ipc.rebindTeam).not.toHaveBeenCalled();+ expect(ipc.revokeTeam).not.toHaveBeenCalled();+ });++ it.each([true, false])('workspace removal confirmation reflects device communications support (%s)', async (supported) => {+ const row = { teamId: 'T1', teamName: 'Workspace', slackUserId: 'U1', slackUserName: 'tester', displaced: true, communicationsEnabled: true };+ ipc.get.mockResolvedValue({ hook: { ...BASE_HOOK, enabled: true, status: 'connected', serverMultiTeam: true, serverSlackCommunications: supported, bindings: [row] } });+ dialog.confirm.mockResolvedValue(false);+ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(await screen.findByRole('button', { name: 'settings.remoteControl.hook.multi.removeAria' }));+ expect(dialog.confirm).toHaveBeenCalledWith(expect.objectContaining({+ description: supported ? 'settings.remoteControl.hook.multi.removeCommunicationsConfirmDescription' : 'settings.remoteControl.hook.multi.removeDisplacedConfirmDescription',+ }));+ expect(ipc.revokeTeam).not.toHaveBeenCalled();+ });+it('shows the lifecycle notification switch only after Slack is bound and persists changes', async () => {const boundHook: SlackHookView = {...BASE_HOOK,@@ -1539,6 +1574,55 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {expect(ipc.revokeTeam).not.toHaveBeenCalled();});+ it.each([+ { name: 'server capability lost', supported: false, enabled: true, removes: false },+ { name: 'communication disabled', supported: true, enabled: false, removes: false },+ { name: 'communication grant removed', supported: true, enabled: undefined, removes: false },+ { name: 'unchanged grant', supported: true, enabled: true, removes: true },+ ])('rechecks Slack removal confirmation: $name', async ({ supported, enabled, removes }) => {+ let pushStatus: ((view: SlackHookView) => void) | undefined;+ let resolveConfirm: ((value: boolean) => void) | undefined;+ dialog.confirm.mockReturnValue(new Promise<boolean>((resolve) => { resolveConfirm = resolve; }));+ ipc.onStatusChanged.mockImplementation((listener: (view: SlackHookView) => void) => {+ pushStatus = listener;+ return () => {};+ });+ const initial: SlackHookView = {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ serverSlackCommunications: true,+ bindings: [{+ teamId: 'team-1', teamName: 'Cindy Team', slackUserId: 'user-1',+ slackUserName: 'Cindy User', displaced: true, communicationsEnabled: true,+ }],+ };+ ipc.get.mockResolvedValue({ hook: initial });+ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.multi.removeAria',+ }));+ await waitFor(() => expect(dialog.confirm).toHaveBeenCalledOnce());+ expect(dialog.confirm).toHaveBeenCalledWith(expect.objectContaining({+ description: 'settings.remoteControl.hook.multi.removeCommunicationsConfirmDescription',+ }));+ act(() => {+ pushStatus?.({+ ...initial,+ serverSlackCommunications: supported,+ bindings: [{ ...initial.bindings[0], communicationsEnabled: enabled }],+ });+ });+ await act(async () => { resolveConfirm?.(true); });+ if (removes) {+ expect(ipc.revokeTeam).toHaveBeenCalledExactlyOnceWith('team-1');+ } else {+ expect(ipc.revokeTeam).not.toHaveBeenCalled();+ }+ });+it('X 卡是 chip 形态, Telegram 卡是目录行内的选中态单选', async () => {// X 一次交互只有一条公开推文, 没有目录选择面板的位置; Telegram 虽能在会话里// /workspace, 但那是每会话各自设的 —— 设置页绑好目录后进新群仍会落「对话」。diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e8fd309bbc..897c6db94c 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3760,6 +3760,12 @@"statusPendingSuffix_other": " ({{count}} pending)","statusOffKept_one": "Off · {{count}} workspace binding kept","statusOffKept_other": "Off · {{count}} workspace bindings kept",+ "removeCommunicationsConfirmDescription": "Remove this device's communications access to this workspace. Other devices and Bot reception settings are not affected.",+ "localCommunications": "Slack Communications on This Device",+ "communicationsActive": "Slack Communications On",+ "communicationsInactive": "Slack Communications Off",+ "botNotReceiving": "Not Receiving Bot Chats",+ "receiveBot": "Receive Bot Chats","displaced": "Bound on another device","rebind": "Rebind","removeAria": "Unlink this workspace",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex abfe6861ac..0c8641e4b8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3759,6 +3759,12 @@"statusPendingSuffix_other": "({{count}} 件対応待ち)","statusOffKept_one": "オフ · {{count}} 個のワークスペース連携を保持中","statusOffKept_other": "オフ · {{count}} 個のワークスペース連携を保持中",+ "removeCommunicationsConfirmDescription": "このデバイスのワークスペースへの通信権限を削除します。他のデバイスや Bot の受信設定には影響しません。",+ "localCommunications": "このデバイスでの Slack 通信",+ "communicationsActive": "Slack 通信オン",+ "communicationsInactive": "Slack 通信オフ",+ "botNotReceiving": "Bot チャットを受信しない",+ "receiveBot": "Bot チャットを受信","displaced": "別のデバイスで連携済み","rebind": "再連携","removeAria": "このワークスペースの連携を解除",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex f7d855a41b..3dbd6faa7c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3759,6 +3759,12 @@"statusPendingSuffix_other": "({{count}}개 처리 대기)","statusOffKept_one": "꺼짐 · 워크스페이스 바인딩 {{count}}개 유지됨","statusOffKept_other": "꺼짐 · 워크스페이스 바인딩 {{count}}개 유지됨",+ "removeCommunicationsConfirmDescription": "이 기기의 워크스페이스 통신 권한을 제거합니다. 다른 기기나 Bot 수신 설정에는 영향을 주지 않습니다.",+ "localCommunications": "이 기기의 Slack 통신",+ "communicationsActive": "Slack 통신 켜짐",+ "communicationsInactive": "Slack 통신 꺼짐",+ "botNotReceiving": "Bot 대화 수신 안 함",+ "receiveBot": "Bot 대화 수신","displaced": "다른 기기에서 바인딩됨","rebind": "다시 바인딩","removeAria": "이 워크스페이스 바인딩 해제",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 567d713b27..82bb5eb439 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3755,6 +3755,12 @@"statusPendingSuffix_other": "({{count}} 个待处理)","statusOffKept_one": "已关闭 · {{count}} 个 workspace 绑定已保留","statusOffKept_other": "已关闭 · {{count}} 个 workspace 绑定已保留",+ "removeCommunicationsConfirmDescription": "将移除此设备对该 workspace 的通讯授权,不影响其他设备或 Bot 接收设置。",+ "localCommunications": "本机 Slack 通讯",+ "communicationsActive": "Slack 通讯已开启",+ "communicationsInactive": "Slack 通讯已关闭",+ "botNotReceiving": "不接收 Bot 对话",+ "receiveBot": "接收 Bot 对话","displaced": "已在另一台设备绑定","rebind": "重新绑定","removeAria": "解绑此 workspace",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex efaec4a638..c2df51a0bd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3755,6 +3755,12 @@"statusPendingSuffix_other": "({{count}} 個待處理)","statusOffKept_one": "已關閉 · {{count}} 個 workspace 繫結已保留","statusOffKept_other": "已關閉 · {{count}} 個 workspace 繫結已保留",+ "removeCommunicationsConfirmDescription": "將移除此裝置對該 workspace 的通訊授權,不影響其他裝置或 Bot 接收設定。",+ "localCommunications": "本機 Slack 通訊",+ "communicationsActive": "Slack 通訊已開啟",+ "communicationsInactive": "Slack 通訊已關閉",+ "botNotReceiving": "不接收 Bot 對話",+ "receiveBot": "接收 Bot 對話","displaced": "已在另一臺裝置繫結","rebind": "重新繫結","removeAria": "解綁此 workspace",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex f0aae9eb43..eaa4e74bb4 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4148,6 +4148,10 @@ interface ElectronAPI {rebindTeam: (teamId: string,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;+ setSlackCommunications: (+ teamId: string,+ enabled: boolean,+ ) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;revokeTeam: (teamId: string,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;diff --git a/apps/desktop/src/shared/hookControlIpc.ts b/apps/desktop/src/shared/hookControlIpc.tsindex f18a967e2d..4e979312e3 100644--- a/apps/desktop/src/shared/hookControlIpc.ts+++ b/apps/desktop/src/shared/hookControlIpc.ts@@ -50,8 +50,9 @@ export const HOOK_CONTROL_INVOKE = {ADD_BINDING: 'maker:hook-control:add-binding',/** (multi-team)给指定 team 重新授权(bind.start 带 teamId, pin 授权页)。 */REBIND_TEAM: 'maker:hook-control:rebind-team',- /** (multi-team)解绑指定 team(bind.revoke{teamId}; displaced 行 = 仅清本地缓存)。 */+ /** (multi-team)解绑指定 team;通讯专用行只撤本机 grant,不撤账号授权。 */REVOKE_TEAM: 'maker:hook-control:revoke-team',+ SET_SLACK_COMMUNICATIONS: 'maker:hook-control:set-slack-communications',/** (multi-team)取消在途的添加/重绑授权(bind.revoke{pendingOnly} + 本地清 pending)。 */CANCEL_PENDING_BIND: 'maker:hook-control:cancel-pending-bind',/** 独立开关一个 Cindy IM provider;不会改动其它 provider。 */@@ -237,11 +238,13 @@ export interface HookTeamBindingView {slackUserId: string;slackUserName: string | null;/**- * true = 该 team 的绑定已被同用户在另一台设备顶替(reason=superseded 实时- * 推送, 或冷启动快照 diff 出「本地有、服务端没有」): 行保留并标注- * 「已在另一台设备绑定」, 用户可重新绑定(rebind)或删除(仅清本地缓存)。+ * true = 本机不是该 team 的 Bot 接收设备(换绑、通讯专用 OAuth 或缓存缺失)。+ * 是否仍可通讯由独立 communicationsEnabled 决定;删除新 server 的通讯行+ * 只撤本机 grant,旧 server 行仅清本地缓存。*/displaced: boolean;+ /** undefined = 未收到独立通讯授权,不能从 displaced 或本地缓存推断。 */+ communicationsEnabled?: boolean;}/**@@ -250,6 +253,7 @@ export interface HookTeamBindingView {* failed)。confirmed/revoked 只落到 bindings 列表, 不出现在这里。*/export interface HookPendingBindView {+ purpose?: 'communications';state: 'pending' | 'denied' | 'expired' | 'failed';message: string | null;/** 仅 pending 时非空(SIWS OIDC 授权链接, 复制链接兜底用)。 */@@ -304,6 +308,8 @@ export interface SlackHookView {pendingBind: HookPendingBindView | null;/** server 是否宣告 multi-team 能力(welcome.features; renderer 据此显示「添加」入口)。 */serverMultiTeam: boolean;+ /** 新 server 将通讯授权与唯一 Bot 接收设备分离。 */+ serverSlackCommunications?: boolean;/** 平级 Telegram hook 服务状态;Slack 旧字段保持原形。 */telegram: ProviderHookView;/** 平级 X (Twitter) hook 服务状态。 */diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-communications.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-communications.test.tsnew file mode 100644index 0000000000..8d46d11e07--- /dev/null+++ b/packages/slack-hook-protocol/src/__tests__/protocol-communications.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';+import { makeBindStart, makeBindState, makeBindUpdate, parseHookMessage, serializeHookMessage } from '../index';++describe('device Slack communications (append-only)', () => {+ it('round-trips legacy binding and communications-only authorization', () => {+ const row = { teamId: 'T1', teamName: null, slackUserId: 'U1', slackUserName: null, enabled: false };+ for (const frame of [+ makeBindStart({}),+ makeBindStart({ teamId: 'T1', purpose: 'communications' }),+ makeBindUpdate({ state: 'pending', purpose: 'communications', authorizeUrl: 'https://example.test/oauth', slackUserId: null, slackUserName: null, message: null }),+ makeBindState({ bindings: [] }),+ makeBindState({ bindings: [], communications: [row] }),+ ]) expect(parseHookMessage(serializeHookMessage(frame))).toMatchObject({ ok: true, message: frame });+ });+ it.each([null, {}, [{ enabled: true }], [{ teamId: 'T1', teamName: null, slackUserId: 'U1', slackUserName: null, enabled: 'true' }]])('rejects malformed communications %j', (communications) => {+ const frame = makeBindState({ bindings: [] });+ expect(parseHookMessage({ ...frame, payload: { ...frame.payload, communications } }).ok).toBe(false);+ });+ it('rejects an unknown authorization purpose instead of treating it as Bot takeover', () => {+ const frame = makeBindStart({});+ expect(parseHookMessage({ ...frame, payload: { purpose: 'unknown' } }).ok).toBe(false);+ });+});diff --git a/packages/slack-hook-protocol/src/parse.ts b/packages/slack-hook-protocol/src/parse.tsindex 9375bfc83a..59f66fa20c 100644--- a/packages/slack-hook-protocol/src/parse.ts+++ b/packages/slack-hook-protocol/src/parse.ts@@ -553,6 +553,7 @@ function validateMessageOpResult(p: Record<string, unknown>): string | null {* 拒收会丢帧, server 就无从判断)。*/function validateBindStart(p: Record<string, unknown>): string | null {+ if (p.purpose !== undefined && p.purpose !== 'communications') return 'bind.start.purpose must be communications';if (p.email !== undefined && (!isNonEmptyString(p.email) || !p.email.includes('@'))) {return 'bind.start.email, when present, must be an email-like string';}@@ -563,6 +564,7 @@ function validateBindStart(p: Record<string, unknown>): string | null {}function validateBindUpdate(p: Record<string, unknown>): string | null {+ if (p.purpose !== undefined && p.purpose !== 'communications') return 'bind.update.purpose must be communications';if (!BIND_UPDATE_STATES.includes(p.state as never)) {return `bind.update.state must be one of: ${BIND_UPDATE_STATES.join(', ')}`;}@@ -622,6 +624,12 @@ function validateBindRevoke(p: Record<string, unknown>): string | null {/** bind.state(multi-team): 绑定全量快照。 */function validateBindState(p: Record<string, unknown>): string | null {+ if (p.communications !== undefined) {+ if (!Array.isArray(p.communications)) return 'bind.state.communications must be an array';+ const error = validateBindState({ bindings: p.communications });+ if (error) return error.replace('bindings', 'communications');+ if (p.communications.some((row) => typeof row.enabled !== 'boolean')) return 'bind.state.communications.enabled must be boolean';+ }if (!Array.isArray(p.bindings)) return 'bind.state.bindings must be an array';for (let i = 0; i < p.bindings.length; i++) {const b: unknown = p.bindings[i];diff --git a/packages/slack-hook-protocol/src/types.ts b/packages/slack-hook-protocol/src/types.tsindex dde66d5215..efb036915b 100644--- a/packages/slack-hook-protocol/src/types.ts+++ b/packages/slack-hook-protocol/src/types.ts@@ -651,6 +651,8 @@ export interface TurnReopenPayload {* 提示升级, 不再执行邮箱定位。*/export interface BindStartPayload {+ /** 仅授权本机通讯,绝不修改 Bot 接收设备。只能在 slack-communications 协商后发送。 */+ purpose?: 'communications';/** @deprecated 旧版邮箱绑定流字段; 新端不再发送, 仅用于 server 识别老客户端。 */email?: string;/**@@ -689,6 +691,8 @@ export type BindUpdateState = (typeof BIND_UPDATE_STATES)[number];* authorizeUrl 非空(OIDC 授权链接); failed 时 message 非空。*/export interface BindUpdatePayload {+ /** 回放授权意图,防重连/重试将通讯授权误升级为 Bot 换绑。 */+ purpose?: 'communications';state: BindUpdateState;slackUserId: string | null;/** Slack 显示名(设置页展示「已绑定 @xxx」用), 拿不到可为 null。 */@@ -765,6 +769,8 @@ export interface BindStateEntry {export interface BindStatePayload {bindings: BindStateEntry[];+ /** 设备通讯授权快照;缺省表示旧 server,不可由本地缓存推断授权。 */+ communications?: (BindStateEntry & { enabled: boolean })[];}// ── Provider-neutral binding (append-only v1) ───────────────────────────────@@ -1269,6 +1275,8 @@ export interface ProviderBehaviorStatePayload* 为 SERVER_TOO_OLD, 不打空炮。*/export const HOOK_FEATURE_SLACK_TOOLS = 'slack-tools';+/** 工具权限独立于 Bot 接收设备,支持 communications.set。 */+export const HOOK_FEATURE_SLACK_COMMUNICATIONS = 'slack-communications';/*** 双向能力标识: 多 workspace 绑定(见文件头第 13 条)。desktop 在