Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 接线 X (Twitter) hook provider (#1230)
Dash7e9b93e091d6
diff --git a/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts b/apps/desktop/src/main/__tests__/endpointManifestCache.test.tsindex 9e89989106..741adb836b 100644--- a/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts+++ b/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts@@ -147,7 +147,7 @@ describe('缓存端点的受信任域约束(安全边界)', () => {const GLOBAL_BASE = 'https://hotfix.cindy.app/cindy';const CN_BASE = 'https://hotfix.cindy.com.cn/cindy';const TRUSTED = Object.values(REGION_ENDPOINT_DOMAIN);- /** CN 构建的策略:非跨区端点锁 cindy.com.cn,slack/telegram hook 才允许 cindy.app。 */+ /** CN 构建的策略:非跨区端点锁 cindy.com.cn,slack/telegram/x hook 才允许 cindy.app。 */const CN_POLICY = {regionDomain: REGION_ENDPOINT_DOMAIN.cn,crossRegionDomain: REGION_ENDPOINT_DOMAIN.global,@@ -165,9 +165,13 @@ describe('缓存端点的受信任域约束(安全边界)', () => {expect(REGION_ENDPOINT_DOMAIN.global).toBe('cindy.app');});- it('跨区例外只有 slack / telegram hook 两个 key', () => {+ it('跨区例外只有 slack / telegram / x hook 三个 key', () => {// 每加一个 key 就等于允许该端点跨区,而跨区 token 误发正是要防的事。- expect([...CROSS_REGION_ENDPOINT_KEYS].sort()).toEqual(['slackHookWsUrl', 'telegramHookWsUrl']);+ expect([...CROSS_REGION_ENDPOINT_KEYS].sort()).toEqual([+ 'slackHookWsUrl',+ 'telegramHookWsUrl',+ 'xHookWsUrl',+ ]);});it('CN 构建拒绝换成 Global 真实服务的伪造缓存(跨区 token 误发)', () => {@@ -223,6 +227,9 @@ describe('缓存端点的受信任域约束(安全边界)', () => {authApiBaseUrl: 'https://auth.cindy.com.cn',slackHookWsUrl: 'wss://slack-hook.cindy.app',telegramHookWsUrl: 'wss://telegram-hook.cindy.app',+ // CN 清单按 Telegram 同款单部署模式放量 X 时,离线缓存回退必须仍受信+ // (PR #1230 review:漏登记会让 CN 用户断网时失去缓存启动出口)。+ xHookWsUrl: 'wss://x-hook.cindy.app',websiteUrl: 'https://cindy.com.cn',cdnBaseUrl: 'https://hotfix.cindy.com.cn/cindy',authDesktopCallbackUrl: 'https://auth.cindy.com.cn/api/auth/desktop/callback',diff --git a/apps/desktop/src/main/endpointManifestCache.ts b/apps/desktop/src/main/endpointManifestCache.tsindex 24325e278a..0f68589fd3 100644--- a/apps/desktop/src/main/endpointManifestCache.ts+++ b/apps/desktop/src/main/endpointManifestCache.ts@@ -234,14 +234,15 @@ export const REGION_ENDPOINT_DOMAIN: Readonly<Record<'cn' | 'global', string>> =};/**- * 跨区共享的 hook 服务:两份清单(含 CN)都指向 cindy.app,所以只有这两个 key 允许- * 落在 Global 域。**别往这里加 key** —— 每加一个就等于允许该端点跨区,而这个集合之外+ * 跨区共享的 hook 服务:两份清单(含 CN)都指向 cindy.app,所以只有这几个 hook key+ * 允许落在 Global 域。**别往这里加 key** —— 每加一个就等于允许该端点跨区,而这个集合之外* 的所有端点(尤其 auth / device-link / oauth-broker / model-access / voice)必须锁在* 本构建区域,否则就回到上面说的跨区 token 误发。*/export const CROSS_REGION_ENDPOINT_KEYS: ReadonlySet<string> = new Set(['slackHookWsUrl','telegramHookWsUrl',+ 'xHookWsUrl',]);/** 缓存端点的来源策略:按 key 决定它允许落在哪个域。 */diff --git a/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts b/apps/desktop/src/main/hook-control/__tests__/outbound.test.tsindex f5436e8a40..2a2fff88c2 100644--- a/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts@@ -33,8 +33,19 @@ describe('buildHookPromptNote', () => {expect(buildHookPromptNote('slack')).not.toContain('[Telegram 回复格式]');});+ it('X 平台名正确且给出纯文本回帖格式约束, 不复用 Telegram/Slack 提示', () => {+ const x = buildHookPromptNote('x');+ expect(x).toContain('本会话来自 X。');+ expect(x).toContain('[X 回复格式]');+ expect(x).toContain('纯文本');+ expect(x).not.toContain('[Telegram 回复格式]');+ expect(x).not.toContain('本会话来自 Slack');+ // 未接线前的回归写法: x 曾被三元兜底误标成 Slack。+ expect(buildHookPromptNote('slack')).not.toContain('[X 回复格式]');+ });+it('两个平台都在开头声明「不是用户消息」,防止模型把渠道说明当成用户请求(2026-07 实踩)', () => {- for (const im of ['telegram', 'slack'] as const) {+ for (const im of ['telegram', 'slack', 'x'] as const) {const note = buildHookPromptNote(im);// guard 必须在附件正文之前出现,才能在模型读到附件指令前先定性。expect(note).toContain('不是用户发来的消息');diff --git a/apps/desktop/src/main/hook-control/__tests__/store.test.ts b/apps/desktop/src/main/hook-control/__tests__/store.test.tsindex 09442584e7..166d34d293 100644--- a/apps/desktop/src/main/hook-control/__tests__/store.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/store.test.ts@@ -49,11 +49,13 @@ describe('默认态与持久化', () => {expect(store.get()).toEqual({enabled: false,telegramEnabled: false,+ xEnabled: false,urlOverride: null,workspaces: {},bindingsCache: [],lifecycleAnnouncementOverride: null,telegramBindingCache: null,+ xBindingCache: null,});expect(store.effectiveUrl()).toBe(TEST_DEFAULT_URL);});@@ -168,11 +170,13 @@ describe('旧多连接文件迁移', () => {expect(makeStore().get()).toEqual({enabled: false,telegramEnabled: false,+ xEnabled: false,urlOverride: null,workspaces: {},bindingsCache: [],lifecycleAnnouncementOverride: null,telegramBindingCache: null,+ xBindingCache: null,});});});@@ -249,7 +253,7 @@ describe('provider 与 Cindy 账号隔离', () => {store.setEnabled(true);store.setProviderEnabled('telegram', true);- store.setTelegramBindingCache(telegramBinding);+ store.setProviderBindingCache('telegram', telegramBinding);store.setWorkspaces({ cindy: abs });expect(store.anyProviderEnabled()).toBe(true);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 3e04dfbb30..cdea2d2734 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@@ -60,11 +60,13 @@ function memoryStore(initial: Partial<SlackHookConfigState> & { url: string }):let state: SlackHookConfigState = {enabled: initial.enabled ?? true,telegramEnabled: initial.telegramEnabled ?? false,+ xEnabled: initial.xEnabled ?? false,urlOverride: initial.url,workspaces: initial.workspaces ?? {},bindingsCache: initial.bindingsCache ?? [],lifecycleAnnouncementOverride: initial.lifecycleAnnouncementOverride ?? null,telegramBindingCache: initial.telegramBindingCache ?? null,+ xBindingCache: initial.xBindingCache ?? null,};return {get: () => ({@@ -72,6 +74,7 @@ function memoryStore(initial: Partial<SlackHookConfigState> & { url: string }):workspaces: { ...state.workspaces },bindingsCache: state.bindingsCache.map((e) => ({ ...e })),telegramBindingCache: state.telegramBindingCache ? { ...state.telegramBindingCache } : null,+ xBindingCache: state.xBindingCache ? { ...state.xBindingCache } : null,}),effectiveUrl: () => state.urlOverride ?? 'wss://unused.example',setEnabled(enabled) {@@ -79,11 +82,16 @@ function memoryStore(initial: Partial<SlackHookConfigState> & { url: string }):return state;},setProviderEnabled(provider, enabled) {- state = provider === 'slack' ? { ...state, enabled } : { ...state, telegramEnabled: enabled };+ state =+ provider === 'slack'+ ? { ...state, enabled }+ : provider === 'x'+ ? { ...state, xEnabled: enabled }+ : { ...state, telegramEnabled: enabled };return state;},anyProviderEnabled() {- return state.enabled || state.telegramEnabled;+ return state.enabled || state.telegramEnabled || state.xEnabled;},setWorkspaces(workspaces) {state = { ...state, workspaces };@@ -97,8 +105,11 @@ function memoryStore(initial: Partial<SlackHookConfigState> & { url: string }):state = { ...state, lifecycleAnnouncementOverride: enabled };return state;},- setTelegramBindingCache(entry) {- state = { ...state, telegramBindingCache: entry ? { ...entry } : null };+ setProviderBindingCache(provider, entry) {+ state =+ provider === 'x'+ ? { ...state, xBindingCache: entry ? { ...entry } : null }+ : { ...state, telegramBindingCache: entry ? { ...entry } : null };return state;},};@@ -112,6 +123,8 @@ function makeManager(store,createTransport: createHookTransport,getTelegramUrl: () => store.effectiveUrl(),+ // X lane 默认不配端点(未部署形态), 相关用例用 overrides 显式注入。+ getXUrl: () => '',getAuthToken: async () => 'jwt-token-1',refreshAuthToken: async () => false,deviceInfo: () => ({ deviceId: 'dev-1', deviceName: 'TestBox' }),@@ -504,6 +517,36 @@ describe('provider dispatch boundary', () => {expect(providerForTaskDispatch({ externalKey: 'telegram:dm:bot-1:user-1:g0' })).toBeNull();});+ it('routes X dispatches only when source and lane key agree, failing closed on mismatch', () => {+ expect(+ providerForTaskDispatch({+ externalKey: 'x:conv:999:conv-1:111:g1',+ source: { im: 'x' },+ }),+ ).toBe('x');+ // source/key 任一缺失或错配一律 fail closed —— X 不得继承 Slack 语义。+ expect(providerForTaskDispatch({ externalKey: 'x:conv:999:conv-1:111:g1' })).toBeNull();+ expect(+ providerForTaskDispatch({+ externalKey: 'x:conv:999:conv-1:111:g1',+ source: { im: 'slack' },+ }),+ ).toBeNull();+ expect(+ providerForTaskDispatch({+ externalKey: 'x:conv:999:conv-1:111:g1',+ source: { im: 'telegram' },+ }),+ ).toBeNull();+ expect(providerForTaskDispatch({ externalKey: 'T1:C1:1.1', source: { im: 'x' } })).toBeNull();+ expect(+ providerForTaskDispatch({+ externalKey: 'telegram:dm:bot-1:user-1:g0',+ source: { im: 'x' },+ }),+ ).toBeNull();+ });+it('routes only known provider lane keys for session archive', () => {expect(providerForExternalKey('slack:dm:T1:U1:g2')).toBe('slack');expect(providerForExternalKey('dm:U1:g2')).toBe('slack');@@ -511,6 +554,7 @@ describe('provider dispatch boundary', () => {expect(providerForExternalKey('team-slack:C1:1.1')).toBe('slack');expect(providerForExternalKey('T1:C1:1.1')).toBe('slack');expect(providerForExternalKey('telegram:dm:bot:user:g2')).toBe('telegram');+ expect(providerForExternalKey('x:conv:999:conv-1:111:g1')).toBe('x');expect(providerForExternalKey('discord:channel-1')).toBeNull();expect(providerForExternalKey('arbitrary')).toBeNull();});@@ -2152,7 +2196,7 @@ describe('Telegram provider capability, binding and prefs', () => {it('本地绑定缓存写失败时仍保留并广播服务端确认态', async () => {const { wss, url } = await startServer();const store = memoryStore({ url, enabled: false, telegramEnabled: true });- store.setTelegramBindingCache = () => {+ store.setProviderBindingCache = () => {throw new Error('disk full');};const warnings: string[] = [];@@ -2433,15 +2477,15 @@ describe('Telegram provider capability, binding and prefs', () => {principalId: 'telegram-user-1',scopeId: 'bot-1',});- await expect(manager.openTelegramAction('connect')).resolves.toBe(false);- await expect(manager.openTelegramAction('provider')).resolves.toBe(true);- await expect(manager.openTelegramAction('add-to-group')).resolves.toBe(true);+ await expect(manager.openProviderAction('telegram', 'connect')).resolves.toBe(false);+ await expect(manager.openProviderAction('telegram', 'provider')).resolves.toBe(true);+ await expect(manager.openProviderAction('telegram', 'add-to-group')).resolves.toBe(true);expect(opened).toEqual(['https://t.me/cindy_example_bot','https://t.me/cindy_example_bot?startgroup=true',]);rejectOpen = true;- await expect(manager.openTelegramAction('provider')).rejects.toThrow('no system URL handler');+ await expect(manager.openProviderAction('telegram', 'provider')).rejects.toThrow('no system URL handler');const prefs = {provider: 'telegram' as const,diff --git a/apps/desktop/src/main/hook-control/__tests__/workspaceProviderSourceStore.test.ts b/apps/desktop/src/main/hook-control/__tests__/workspaceProviderSourceStore.test.tsindex 8841730208..31c738bc4e 100644--- a/apps/desktop/src/main/hook-control/__tests__/workspaceProviderSourceStore.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/workspaceProviderSourceStore.test.ts@@ -33,9 +33,12 @@ describe('workspaceProviderSourceStore', () => {it('写读一条来源偏好;不同渠道/目录互不串', () => {setWorkspaceProviderSource('telegram', null, 'chat', 'anthropic');setWorkspaceProviderSource('slack', null, 'chat', 'openai');+ setWorkspaceProviderSource('x', null, 'chat', 'google');expect(getWorkspaceProviderSource('telegram', null, 'chat')).toBe('anthropic');expect(getWorkspaceProviderSource('slack', null, 'chat')).toBe('openai');+ expect(getWorkspaceProviderSource('x', null, 'chat')).toBe('google');expect(getWorkspaceProviderSource('telegram', null, 'repo')).toBeNull();+ expect(getWorkspaceProviderSource('x', null, 'repo')).toBeNull();});it('teamId 精确匹配优先, null 行兜底(multi-team 宽松语义)', () => {diff --git a/apps/desktop/src/main/hook-control/__tests__/xDeepLink.test.ts b/apps/desktop/src/main/hook-control/__tests__/xDeepLink.test.tsnew file mode 100644index 0000000000..2868b55d68--- /dev/null+++ b/apps/desktop/src/main/hook-control/__tests__/xDeepLink.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import {+ parseXConnectUrl,+ validateXExternalUrl,+ xProfileUrl,+ xProfileUrlOrNull,+} from '../xDeepLink';++const AUTHORIZE_QS =+ 'response_type=code&client_id=client-1&redirect_uri=https%3A%2F%2Fx-hook.example%2Fx%2Foauth%2Fcallback&scope=tweet.read%20tweet.write&state=state-abc_123&code_challenge=challenge-abc_123&code_challenge_method=S256';+const VALID_AUTHORIZE = `https://x.com/i/oauth2/authorize?${AUTHORIZE_QS}`;++describe('parseXConnectUrl', () => {+ it('accepts the canonical X OAuth2 (PKCE) authorize URL', () => {+ expect(parseXConnectUrl(VALID_AUTHORIZE).url).toContain('https://x.com/i/oauth2/authorize?');+ });++ it.each([+ ['whitespace padding', ` ${VALID_AUTHORIZE}`],+ ['http downgrade', VALID_AUTHORIZE.replace('https:', 'http:')],+ ['wrong host', VALID_AUTHORIZE.replace('x.com', 'twitter.com')],+ ['host lookalike', VALID_AUTHORIZE.replace('x.com', 'x.com.evil.example')],+ ['embedded credentials', VALID_AUTHORIZE.replace('https://x.com', 'https://user:[email protected]')],+ ['explicit default port', VALID_AUTHORIZE.replace('https://x.com', 'https://x.com:443')],+ ['fragment', `${VALID_AUTHORIZE}#frag`],+ ['empty fragment delimiter', `${VALID_AUTHORIZE}#`],+ ['wrong path', VALID_AUTHORIZE.replace('/i/oauth2/authorize', '/i/oauth2/authorize/extra')],+ ['unexpected parameter', `${VALID_AUTHORIZE}&prompt=none`],+ ['repeated parameter', `${VALID_AUTHORIZE}&state=state-2`],+ ['missing parameter', VALID_AUTHORIZE.replace('&state=state-abc_123', '')],+ ['empty parameter', VALID_AUTHORIZE.replace('state=state-abc_123', 'state=')],+ ['implicit flow', VALID_AUTHORIZE.replace('response_type=code', 'response_type=token')],+ ['plain PKCE challenge', VALID_AUTHORIZE.replace('code_challenge_method=S256', 'code_challenge_method=plain')],+ ['not a URL', 'not a url'],+ ])('rejects %s', (_label, input) => {+ expect(() => parseXConnectUrl(input)).toThrow(/X (binding URL|link)/);+ });+});++describe('xProfileUrl', () => {+ it('builds the bot profile URL and strips a leading @', () => {+ expect(xProfileUrl('@CindyBot')).toBe('https://x.com/CindyBot');+ expect(xProfileUrl('CindyBot')).toBe('https://x.com/CindyBot');+ });++ it('rejects malformed handles; the null-safe variant swallows them', () => {+ expect(() => xProfileUrl('has space')).toThrow(/Invalid X handle/);+ expect(() => xProfileUrl('way-too-long-handle-x')).toThrow(/Invalid X handle/);+ expect(xProfileUrlOrNull('has space')).toBeNull();+ expect(xProfileUrlOrNull(null)).toBeNull();+ expect(xProfileUrlOrNull('@CindyBot')).toBe('https://x.com/CindyBot');+ });+});++describe('validateXExternalUrl', () => {+ it('accepts the authorize URL and bare profile URLs, nothing else', () => {+ expect(validateXExternalUrl(VALID_AUTHORIZE)).toContain('/i/oauth2/authorize?');+ expect(validateXExternalUrl('https://x.com/CindyBot')).toBe('https://x.com/CindyBot');+ // profile URL 不允许携带 query / 编码路径 / 多段路径+ expect(() => validateXExternalUrl('https://x.com/CindyBot?ref=1')).toThrow();+ expect(() => validateXExternalUrl('https://x.com/%43indyBot')).toThrow();+ expect(() => validateXExternalUrl('https://x.com/CindyBot/status/1')).toThrow();+ expect(() => validateXExternalUrl('https://t.me/CindyBot')).toThrow();+ });+});diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex 7e123f1c68..34199746cd 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -1531,7 +1531,9 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {payload.prompt,bareKey,payload.source?.teamName ??- (payload.source?.im === 'telegram' ? payload.source.channelName : null),+ (payload.source?.im === 'telegram' || payload.source?.im === 'x'+ ? payload.source.channelName+ : null),),prompt: payload.prompt,attachments: payload.attachments,diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex 960c804591..df8dd5328a 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -80,6 +80,7 @@ import { createMakerHookSessionRunner } from './session-runner.js';import { resolveHookInteraction } from './interactions.js';import { listRecentHookSessions } from './recentSessions.js';import { validateTelegramExternalUrl } from './telegramDeepLink.js';+import { validateXExternalUrl } from './xDeepLink.js';import { isAppContentWindow } from '../windowFocusClassifier.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { getAgentIslandService } from '../agent-island/service.js';@@ -130,6 +131,15 @@ function disabledHookView(): SlackHookView {capabilityPending: false,binding: null,},+ x: {+ enabled: false,+ url: getClientEndpoint('xHookWsUrl'),+ status: 'disabled',+ lastError: null,+ available: false,+ capabilityPending: false,+ binding: null,+ },};}@@ -260,15 +270,39 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager// 两个 provider 复用 dispatcher,但连接身份和服务地址彼此隔离。getConnection: (connectionId) => {const config = store!.get();- const provider = connectionId.endsWith(':telegram') ? 'telegram' : 'slack';+ // connectionId 形如 `slack:<账号指纹>:<provider>`(manager 的 dispatchId+ // 拼装, 指纹是 base64url 不含冒号)或裸 id(Slack legacy 线, 末段即+ // 'slack')—— 按末段解析 provider。未登记的 provider 返回 null,+ // dispatcher 按连接不存在拒绝(fail closed): 回落到 Slack 会让它读到+ // 错误的开关与端点。+ const provider = connectionId.split(':').pop() ?? '';+ const metaByProvider: Record<+ string,+ { name: string; url: string; enabled: boolean } | undefined+ > = {+ telegram: {+ name: `${BRAND_NAME} Telegram`,+ url: getClientEndpoint('telegramHookWsUrl'),+ enabled: config.telegramEnabled,+ },+ x: {+ name: `${BRAND_NAME} X`,+ url: getClientEndpoint('xHookWsUrl'),+ enabled: config.xEnabled,+ },+ slack: {+ name: `${BRAND_NAME} Slack`,+ url: store!.effectiveUrl(),+ enabled: config.enabled,+ },+ };+ const meta = metaByProvider[provider];+ if (!meta) return null;return {id: connectionId,- name: `${BRAND_NAME} ${provider === 'telegram' ? 'Telegram' : 'Slack'}`,- url:- provider === 'telegram'- ? getClientEndpoint('telegramHookWsUrl')- : store!.effectiveUrl(),- enabled: provider === 'telegram' ? config.telegramEnabled : config.enabled,+ name: meta.name,+ url: meta.url,+ enabled: meta.enabled,workspaces: config.workspaces,createdAt: 0,};@@ -351,6 +385,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManagerisAvailable: hookControlAvailable,createTransport: createHookTransport,getTelegramUrl: () => getClientEndpoint('telegramHookWsUrl'),+ getXUrl: () => getClientEndpoint('xHookWsUrl'),// 与 device-link 同款 token 源: 现值优先, 缺失 refresh 一次getAuthToken: async () => {if (!hookControlAvailable()) return null;@@ -416,6 +451,10 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManagerconst safeUrl = validateTelegramExternalUrl(url);return shell.openExternal(safeUrl);},+ openXUrl: (url) => {+ const safeUrl = validateXExternalUrl(url);+ return shell.openExternal(safeUrl);+ },log,});// Slack 网关工具桥: lizi_slack provider 经叶子注册表取用(不直接 import@@ -517,57 +556,75 @@ export function registerHookControlIpc(): void {requireHookControl();const { manager: m } = ensureInstances();const p = requireObject(payload);- if (p.provider !== 'telegram') {- throwIpcError('INVALID_PARAMS', 'provider must be telegram');+ if (p.provider !== 'telegram' && p.provider !== 'x') {+ throwIpcError('INVALID_PARAMS', 'provider must be telegram or x');}if (typeof p.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'enabled must be boolean');- m.setProviderEnabled('telegram', p.enabled);+ m.setProviderEnabled(p.provider, p.enabled);return { hook: m.snapshot() };});- registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_START, () => {+ /** provider-neutral 绑定动作的 provider 形参校验(telegram / x)。 */+ const requireNeutralProvider = (payload: unknown): 'telegram' | 'x' => {+ const p = requireObject(payload);+ if (p.provider !== 'telegram' && p.provider !== 'x') {+ throwIpcError('INVALID_PARAMS', 'provider must be telegram or x');+ }+ return p.provider;+ };+ const providerDisplayName = (provider: 'telegram' | 'x'): string =>+ provider === 'telegram' ? 'Telegram' : 'X';++ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_START, (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();- if (!m.providerBindStart('telegram')) {- throwIpcError('HOOK_NOT_CONNECTED', 'Telegram provider is not connected');+ const provider = requireNeutralProvider(payload);+ if (!m.providerBindStart(provider)) {+ throwIpcError('HOOK_NOT_CONNECTED', `${providerDisplayName(provider)} provider is not connected`);}return { hook: m.snapshot() };});- registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_CANCEL, () => {+ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_CANCEL, (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();- if (!m.providerBindCancel('telegram')) {- throwIpcError('HOOK_NOT_CONNECTED', 'Telegram binding attempt is not active');+ const provider = requireNeutralProvider(payload);+ if (!m.providerBindCancel(provider)) {+ throwIpcError('HOOK_NOT_CONNECTED', `${providerDisplayName(provider)} binding attempt is not active`);}return { hook: m.snapshot() };});- registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_REVOKE, () => {+ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_BIND_REVOKE, (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();- if (!m.providerBindRevoke('telegram')) {- throwIpcError('HOOK_NOT_CONNECTED', 'Telegram binding is not connected');+ const provider = requireNeutralProvider(payload);+ if (!m.providerBindRevoke(provider)) {+ throwIpcError('HOOK_NOT_CONNECTED', `${providerDisplayName(provider)} binding is not connected`);}return { hook: m.snapshot() };});registerTrustedHookControlHandler(- HOOK_CONTROL_INVOKE.TELEGRAM_OPEN_ACTION,+ HOOK_CONTROL_INVOKE.PROVIDER_OPEN_ACTION,async (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();+ const provider = requireNeutralProvider(payload);const p = requireObject(payload);const action = requireString(p.action, 'action');if (action !== 'connect' && action !== 'provider' && action !== 'add-to-group') {- throwIpcError('INVALID_PARAMS', 'invalid Telegram open action');+ throwIpcError('INVALID_PARAMS', `invalid ${providerDisplayName(provider)} open action`);}try {- if (!(await m.openTelegramAction(action))) {- throwIpcError('INVALID_PARAMS', 'Telegram action is not available');+ if (!(await m.openProviderAction(provider, action))) {+ throwIpcError('INVALID_PARAMS', `${providerDisplayName(provider)} action is not available`);}} catch (err) {- if (err instanceof Error && err.name === 'TelegramDeepLinkValidationError') {+ if (+ err instanceof Error &&+ (err.name === 'TelegramDeepLinkValidationError' || err.name === 'XLinkValidationError')+ ) {throwIpcError('INVALID_PARAMS', err.message);}throw err;@@ -699,11 +756,12 @@ export function registerHookControlIpc(): void {}});- registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_PREFS_GET, async () => {+ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_PREFS_GET, async (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();+ const provider = requireNeutralProvider(payload);try {- return { prefs: await m.getProviderWorkspacePrefs('telegram') };+ return { prefs: await m.getProviderWorkspacePrefs(provider) };} catch (err) {throwHookPrefsError(err);}@@ -712,6 +770,7 @@ export function registerHookControlIpc(): void {registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.PROVIDER_PREFS_SET, async (_e, payload) => {requireHookControl();const { manager: m } = ensureInstances();+ const provider = requireNeutralProvider(payload);const p = requireObject(payload);const workspace = requireString(p.workspace, 'workspace');const rawPatch = requireObject(p.patch);@@ -725,7 +784,7 @@ export function registerHookControlIpc(): void {patch[field] = value as string | null;}try {- return { prefs: await m.setProviderWorkspacePrefs('telegram', workspace, patch) };+ return { prefs: await m.setProviderWorkspacePrefs(provider, workspace, patch) };} catch (err) {throwHookPrefsError(err);}@@ -742,8 +801,8 @@ export function registerHookControlIpc(): void {async (_e, payload) => {const p = requireObject(payload);const channel = requireString(p.channel, 'channel');- if (channel !== 'slack' && channel !== 'telegram') {- throwIpcError('INVALID_PARAMS', 'channel must be slack or telegram');+ if (channel !== 'slack' && channel !== 'telegram' && channel !== 'x') {+ throwIpcError('INVALID_PARAMS', 'channel must be slack, telegram or x');}// 输入设界(codex review): 即使 renderer 被攻破, 也不允许任意长度/格式的键// 无限追加条目撑爆本地文件 —— workspace 按别名正则(与 prefs 同规), 其余限长。diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.tsindex f08a304b9b..31c6f740a8 100644--- a/apps/desktop/src/main/hook-control/manager.ts+++ b/apps/desktop/src/main/hook-control/manager.ts@@ -23,6 +23,7 @@ import {HOOK_FEATURE_PROVIDER_BIND,HOOK_FEATURE_PROVIDER_PREFS,HOOK_FEATURE_PROVIDER_TELEGRAM,+ HOOK_FEATURE_PROVIDER_X,HOOK_FEATURE_SESSION_PICKER,HOOK_FEATURE_SLACK_TOOLS,makeBindRevoke,@@ -61,6 +62,7 @@ import type {HookPrefsView,HookProvider as ClientHookProvider,ProviderBindingView,+ ProviderHookView,ProviderPrefsView,HookTeamBindingView,SlackHookView,@@ -74,6 +76,7 @@ import type { HookDispatcher } from './dispatcher.js';import { buildQueryResponse, type AgentModelSource } from './queryResponder.js';import { recordGroupMessage, sweepGroupWindowExpired } from './groupWindow.js';import { parseTelegramConnectUrl } from './telegramDeepLink.js';+import { parseXConnectUrl, xProfileUrlOrNull } from './xDeepLink.js';import type { HookTransport, HookTransportOpts, HookTransportStatus } from './transport.js';/** dispatcher / bindings 的 connectionId 基础键;运行时追加账号与 provider。 */@@ -90,9 +93,9 @@ function isLegacySlackDmExternalKey(externalKey: string): boolean {}/**- * Route only the two providers implemented by this client. Missing source is- * retained solely for legacy Slack servers; Telegram always has both an- * explicit source and the provider-prefixed lane key from its wire contract.+ * Route only the providers implemented by this client. Missing source is+ * retained solely for legacy Slack servers; Telegram and X always have both an+ * explicit source and the provider-prefixed lane key from their wire contracts.* A source/key disagreement fails closed instead of letting a future or* compromised provider inherit Slack permissions and prompt semantics.*/@@ -100,6 +103,7 @@ export function providerForTaskDispatch(payload: Pick<import('@cindy/slack-hook-protocol').TaskDispatchPayload, 'externalKey' | 'source'>,): HookProvider | null {const telegramKey = payload.externalKey.startsWith('telegram:');+ const xKey = payload.externalKey.startsWith('x:');const slackKey =payload.externalKey.startsWith('slack:') ||payload.externalKey.startsWith('team-slack:') ||@@ -109,6 +113,7 @@ export function providerForTaskDispatch(const source = payload.source?.im;if (source === undefined) return slackKey ? 'slack' : null;if (source === 'telegram') return telegramKey ? 'telegram' : null;+ if (source === 'x') return xKey ? 'x' : null;if (source === 'slack') return slackKey ? 'slack' : null;return null;}@@ -116,6 +121,7 @@ export function providerForTaskDispatch(/** Route archive frames only for lane-key formats owned by implemented providers. */export function providerForExternalKey(externalKey: string): HookProvider | null {if (externalKey.startsWith('telegram:')) return 'telegram';+ if (externalKey.startsWith('x:')) return 'x';if (externalKey.startsWith('slack:') ||externalKey.startsWith('team-slack:') ||@@ -135,6 +141,8 @@ export interface HookControlManagerDeps {createTransport: (opts: HookTransportOpts) => HookTransport;/** Telegram 平级服务端点;空字符串表示当前环境尚未部署该服务。 */getTelegramUrl: () => string;+ /** X (Twitter) 平级服务端点;空字符串表示当前环境尚未部署该服务。 */+ getXUrl: () => string;/** 登录 accessToken 源(transport 每次建连实时取; null = 未登录)。 */getAuthToken: () => Promise<string | null>;/** upgrade 401 后强制刷新一次登录凭证;成功后 transport 立即重连。 */@@ -192,6 +200,8 @@ export interface HookControlManagerDeps {* renderer 主动触发的打开动作能等待系统 shell 的真实结果。*/openTelegramUrl?: (url: string) => void | Promise<void>;+ /** X URL 的 main 安全边界(语义同 openTelegramUrl, 校验走 validateXExternalUrl)。 */+ openXUrl?: (url: string) => void | Promise<void>;log: { info(msg: string): void; warn(msg: string): void };}@@ -274,13 +284,17 @@ export interface HookControlManager {teamId?: string | null,): Promise<HookPrefsView>;setProviderEnabled(provider: HookProvider, enabled: boolean): void;- providerBindStart(provider: 'telegram'): boolean;- providerBindCancel(provider: 'telegram'): boolean;- providerBindRevoke(provider: 'telegram'): boolean;- openTelegramAction(action: 'connect' | 'provider' | 'add-to-group'): Promise<boolean>;- getProviderWorkspacePrefs(provider: 'telegram'): Promise<ProviderPrefsView>;+ providerBindStart(provider: NeutralHookProvider): boolean;+ providerBindCancel(provider: NeutralHookProvider): boolean;+ providerBindRevoke(provider: NeutralHookProvider): boolean;+ /** 在本机安全打开 provider 的绑定链接 / bot 主页 / 加群链接(main 边界校验)。 */+ openProviderAction(+ provider: NeutralHookProvider,+ action: 'connect' | 'provider' | 'add-to-group',+ ): Promise<boolean>;+ getProviderWorkspacePrefs(provider: NeutralHookProvider): Promise<ProviderPrefsView>;setProviderWorkspacePrefs(- provider: 'telegram',+ provider: NeutralHookProvider,workspace: string,patch: HookPrefsPatch,): Promise<ProviderPrefsView>;@@ -333,9 +347,11 @@ export class HookNotConnectedError extends Error {super(provider === 'telegram'? 'telegram provider connection is not connected'- : provider === 'slack'- ? 'slack hook connection is not connected'- : 'hook connection is not connected',+ : provider === 'x'+ ? 'x provider connection is not connected'+ : provider === 'slack'+ ? 'slack hook connection is not connected'+ : 'hook connection is not connected',);this.name = 'HookNotConnectedError';this.provider = provider;@@ -352,9 +368,11 @@ export class HookNotConnectedError extends Error {export function hookNotConnectedIpcMessage(provider: HookProvider | null): string {return provider === 'telegram'? 'Telegram provider is not connected'- : provider === 'slack'- ? 'slack hook is not connected'- : 'hook is not connected';+ : provider === 'x'+ ? 'X provider is not connected'+ : provider === 'slack'+ ? 'slack hook is not connected'+ : 'hook is not connected';}/** prefs 往返超时 —— server 大概率是不认识 prefs.* 帧的旧版本(丢帧不应答)。 */@@ -423,14 +441,13 @@ type ProviderBindRequest =* Provider-neutral 连接线的 provider 值域(Slack 走 legacy 专属帧, 不进本表)。** 从**客户端支持集**(IPC 契约的 ClientHookProvider)派生, 而不是协议全集:- * 协议按 append-only 先行加了 'x'(配套能力 provider:x), 但客户端的 X 渠道- * 还没实现(见 makecindy/cindy#691), 运行期也没有对应 lane。若沿用协议全集,- * 一个客户端从不支持的 provider 会漏进 renderer 可见类型。等 X 的 lane config- * 与设置页一并落地时, 放宽 ClientHookProvider 即可自动带上本表。+ * 协议按 append-only 演进, 客户端尚未实现的 provider 不得漏进 renderer 可见+ * 类型。X 渠道已随 xConfig lane 与设置页落地(makecindy/cindy#691),+ * ClientHookProvider 已同步放宽为含 'x'。*/-type NeutralHookProvider = Exclude<ClientHookProvider, 'slack'>;+export type NeutralHookProvider = Exclude<ClientHookProvider, 'slack'>;-/** renderer 请求打开 provider 相关链接的动作(openTelegramAction 的值域)。 */+/** renderer 请求打开 provider 相关链接的动作(openProviderAction 的值域)。 */type ProviderOpenAction = 'connect' | 'provider' | 'add-to-group';/**@@ -512,6 +529,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContisAvailable = () => true,createTransport,getTelegramUrl,+ getXUrl,getAuthToken,refreshAuthToken,deviceInfo,@@ -531,6 +549,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContaccountInitiallyActive,openExternalUrl,openTelegramUrl,+ openXUrl,log,} = deps;const id = SLACK_HOOK_CONNECTION_ID;@@ -599,7 +618,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont};},writeBindingCache: (entry) => {- store.setTelegramBindingCache(entry);+ store.setProviderBindingCache('telegram', entry);},normalizePendingPayload: (payload) => {const connectLink = parseTelegramConnectUrl(payload.connectUrl ?? '');@@ -632,6 +651,69 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContopenUrl: openTelegramUrl,};+ const xConfig: NeutralProviderConfig = {+ provider: 'x',+ label: 'X',+ getUrl: getXUrl,+ notConfiguredError: 'X service endpoint is not configured',+ requiredFeatures: [+ HOOK_FEATURE_PROVIDER_BIND,+ HOOK_FEATURE_PROVIDER_PREFS,+ HOOK_FEATURE_SESSION_PICKER,+ HOOK_FEATURE_PROVIDER_X,+ ],+ // X v1 没有群消息中继(group relay 是 Telegram 专属能力), 不声明。+ helloFeatures: [+ HOOK_FEATURE_PROVIDER_BIND,+ HOOK_FEATURE_PROVIDER_PREFS,+ HOOK_FEATURE_SESSION_PICKER,+ ],+ isEnabled: () => store.get().xEnabled,+ setEnabled: (enabled) => {+ store.setProviderEnabled('x', enabled);+ },+ restoreCachedBinding: () => {+ const cached = store.get().xBindingCache;+ if (cached === null) return null;+ return {+ provider: 'x',+ state: 'confirmed',+ attemptId: null,+ bindingId: cached.bindingId,+ principalId: cached.principalId,+ principalName: cached.principalName,+ scopeId: cached.scopeId,+ scopeName: cached.scopeName,+ connectUrl: null,+ expiresAt: null,+ reason: null,+ // scopeName 是 bot handle(如 '@CindyBot'); 形状不合法时容错为 null,+ // 缓存恢复路径不抛错。+ remediationUrl: xProfileUrlOrNull(cached.scopeName),+ actions: ['revoke', 'open_provider'],+ };+ },+ writeBindingCache: (entry) => {+ store.setProviderBindingCache('x', entry);+ },+ normalizePendingPayload: (payload) => {+ // connectUrl 是 X OAuth2 (PKCE) 授权页 —— host/path/参数集精确校验,+ // 授权 URL 不含 bot 身份, scopeName 原样保留(由 server 侧协商下发)。+ const connectLink = parseXConnectUrl(payload.connectUrl ?? '');+ return { ...payload, connectUrl: connectLink.url };+ },+ actionUrl: (action, bindingView) => {+ if (action === 'connect' && bindingView.actions.includes('open_connect_url')) {+ return bindingView.connectUrl;+ }+ if (action === 'provider' && bindingView.actions.includes('open_provider')) {+ return xProfileUrlOrNull(bindingView.scopeName);+ }+ return null; // X 没有加群概念, add-to-group 恒不可用+ },+ ...(openXUrl !== undefined ? { openUrl: openXUrl } : {}),+ };+function createNeutralLane(config: NeutralProviderConfig): NeutralProviderLane {return {config,@@ -651,8 +733,9 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont}const telegramLane = createNeutralLane(telegramConfig);+ const xLane = createNeutralLane(xConfig);/** 全部 provider-neutral 线; 遍历顺序即启动 / hello 重发顺序。 */- const lanes: readonly NeutralProviderLane[] = [telegramLane];+ const lanes: readonly NeutralProviderLane[] = [telegramLane, xLane];// key 收窄到 NeutralHookProvider: 'slack' 走 legacy 线, 在编译期就挡在本表外const laneByProvider = new Map<NeutralHookProvider, NeutralProviderLane>(lanes.map((lane) => [lane.config.provider, lane]),@@ -923,7 +1006,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont}/** 本线的 IPC 视图切片(形状与历史 SlackHookView.telegram 字段完全一致)。 */- function laneView(lane: NeutralProviderLane): SlackHookView['telegram'] {+ function laneView(lane: NeutralProviderLane): ProviderHookView {const enabled = lane.config.isEnabled();const url = lane.config.getUrl().trim();return {@@ -958,6 +1041,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContpendingBind: pendingBind !== null ? { ...pendingBind } : null,serverMultiTeam: serverMultiTeam(),telegram: laneView(telegramLane),+ x: laneView(xLane),};}@@ -2648,9 +2732,9 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContif (sent) lane.bindRequest = { kind: 'revoke', requestId, bindingId };return sent;},- async openTelegramAction(action) {- const lane = telegramLane;- if (!lane.config.openUrl || lane.binding === null) return false;+ async openProviderAction(provider, action) {+ const lane = laneByProvider.get(provider);+ if (lane === undefined || !lane.config.openUrl || lane.binding === null) return false;const url = lane.config.actionUrl(action, lane.binding);if (!url) return false;await lane.config.openUrl(url);diff --git a/apps/desktop/src/main/hook-control/outbound.ts b/apps/desktop/src/main/hook-control/outbound.tsindex 4cbe30e8e3..cd51449cd6 100644--- a/apps/desktop/src/main/hook-control/outbound.ts+++ b/apps/desktop/src/main/hook-control/outbound.ts@@ -49,7 +49,7 @@ const MAX_OUT_TOTAL_BYTES = 30 * 1024 * 1024;* 请求或加以引用/臆测。删改这句 guard 会让该误读复发。*/export function buildHookPromptNote(im: string | undefined): string {- const platform = im === 'telegram' ? 'Telegram' : 'Slack';+ const platform = im === 'telegram' ? 'Telegram' : im === 'x' ? 'X' : 'Slack';const attachmentNote ='[渠道说明] 以下为系统每轮自动追加的投递与格式规范,不是用户发来的消息;' +'回复时不要把它当作用户的请求,也不要引用、复述或据此臆测用户意图。' +@@ -60,6 +60,14 @@ export function buildHookPromptNote(im: string | undefined): string {'xdt-file 文件必须位于当前工作目录内;无法读取、超限或目录外的附件不会发送,' +'最终回复会明确显示附件发送不完整。' +'不要用 cindy_feishu_bot 发送,除非用户明确要求发到飞书。';+ if (im === 'x') {+ return (+ `${attachmentNote}\n` ++ '[X 回复格式] 最终回复会被转换为纯文本、以单条公开回帖发布在 X 上。' ++ '保持简短聚焦(过长会被折叠), 用短段落和简单列表; 不要依赖表格、' ++ '多级标题等富结构 —— 转换后会失去排版; 代码用 fenced code block。'+ );+ }if (im !== 'telegram') return attachmentNote;return (`${attachmentNote}\n` +diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 5cd003e77f..498c1a71ec 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -152,9 +152,11 @@ async function resolveNewSessionConfig(const channel =sourceIm === 'telegram'? ('telegram' as const)- : sourceIm === 'slack'- ? ('slack' as const)- : null;+ : sourceIm === 'x'+ ? ('x' as const)+ : sourceIm === 'slack'+ ? ('slack' as const)+ : null;const workdirProviderId =channel !== null && workspaceCtx?.alias? getWorkspaceProviderSource(channel, workspaceCtx.teamId, workspaceCtx.alias)@@ -471,7 +473,12 @@ export function createMakerHookSessionRunner(deps: {...(req.isNew? {vendorOptions: {- source: req.source?.im === 'telegram' ? 'telegram' : 'slack-hook',+ source:+ req.source?.im === 'telegram'+ ? 'telegram'+ : req.source?.im === 'x'+ ? 'x'+ : 'slack-hook',},}: {}),@@ -630,8 +637,8 @@ export function createMakerHookSessionRunner(deps: {if (providerId) {await setSessionProviderIdInDb(session.id, providerId);}- if (req.source?.im === 'telegram') {- await setSessionSourceInDb(session.id, 'telegram');+ if (req.source?.im === 'telegram' || req.source?.im === 'x') {+ await setSessionSourceInDb(session.id, req.source.im);}broadcastSessionCreated(session.id);}diff --git a/apps/desktop/src/main/hook-control/store.ts b/apps/desktop/src/main/hook-control/store.tsindex 580b4123e9..023d2e1b57 100644--- a/apps/desktop/src/main/hook-control/store.ts+++ b/apps/desktop/src/main/hook-control/store.ts@@ -36,7 +36,7 @@ export interface HookBindingCacheEntry {/*** Provider-neutral confirmed binding 的无凭证本地影子,用于关闭 provider 后- * 稳定展示(字段与 provider.bind.* 协议词汇对齐; 当前仅 Telegram 存储槽使用)。+ * 稳定展示(字段与 provider.bind.* 协议词汇对齐; Telegram / X 存储槽使用)。*/export interface ProviderBindingCacheEntry {bindingId: string;@@ -52,6 +52,8 @@ export interface SlackHookConfigState {enabled: boolean;/** Telegram provider 独立开关。 */telegramEnabled: boolean;+ /** X (Twitter) provider 独立开关。 */+ xEnabled: boolean;/** 服务器地址覆写(高级/调试用, 无 UI 入口); null = 跟随内置默认。 */urlOverride: string | null;/** 别名 -> 本地绝对路径。 */@@ -64,6 +66,7 @@ export interface SlackHookConfigState {*/lifecycleAnnouncementOverride: boolean | null;telegramBindingCache: ProviderBindingCacheEntry | null;+ xBindingCache: ProviderBindingCacheEntry | null;}export const DEFAULT_SLACK_LIFECYCLE_ANNOUNCEMENT = false;@@ -153,13 +156,17 @@ export interface SlackHookStore {/** 实际生效的服务器地址(覆写优先, 否则内置默认)。 */effectiveUrl(): string;setEnabled(enabled: boolean): SlackHookConfigState;- setProviderEnabled(provider: 'slack' | 'telegram', enabled: boolean): SlackHookConfigState;+ setProviderEnabled(provider: 'slack' | 'telegram' | 'x', enabled: boolean): SlackHookConfigState;anyProviderEnabled(): boolean;setWorkspaces(workspaces: Record<string, string>): SlackHookConfigState;/** (multi-team)覆写本地绑定缓存(bind.state / 绑定行变化后由 manager 调用)。 */setBindingsCache(entries: HookBindingCacheEntry[]): SlackHookConfigState;setLifecycleAnnouncementOverride(enabled: boolean | null): SlackHookConfigState;- setTelegramBindingCache(entry: ProviderBindingCacheEntry | null): SlackHookConfigState;+ /** provider-neutral(Telegram / X)confirmed 绑定的本地影子写入。 */+ setProviderBindingCache(+ provider: 'telegram' | 'x',+ entry: ProviderBindingCacheEntry | null,+ ): SlackHookConfigState;}export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {@@ -172,6 +179,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {lifecycleAnnouncementOverride: boolean | null;};telegram: { enabled: boolean; bindingCache: ProviderBindingCacheEntry | null };+ x: { enabled: boolean; bindingCache: ProviderBindingCacheEntry | null };}interface StoredDocument {@@ -208,11 +216,13 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {const migrated: SlackHookConfigState = {enabled: source?.enabled === true,telegramEnabled: false,+ xEnabled: false,urlOverride: null, // 旧 url 是自部署地址, 不迁移 —— 新形态用内置中心服务器workspaces,bindingsCache: [], // 旧多连接时代没有绑定缓存概念lifecycleAnnouncementOverride: null,telegramBindingCache: null,+ xBindingCache: null,};// 清理旧文件与旧 secret(best-effort, 失败只记日志)const legacyIds = rows.map((r) => (typeof r.id === 'string' ? r.id : '')).filter(Boolean);@@ -243,6 +253,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {lifecycleAnnouncementOverride: null,},telegram: { enabled: false, bindingCache: null },+ x: { enabled: false, bindingCache: null },});/** 绑定缓存条目形状校验(坏条目静默丢弃 —— 缓存是可再生数据, 不值得报错)。 */@@ -264,7 +275,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {return entries;}- function parseTelegramBindingCache(raw: unknown): ProviderBindingCacheEntry | null {+ function parseProviderBindingCache(raw: unknown): ProviderBindingCacheEntry | null {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;const row = raw as Record<string, unknown>;if (@@ -299,6 +310,10 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {row.telegram && typeof row.telegram === 'object' && !Array.isArray(row.telegram)? (row.telegram as Record<string, unknown>): {};+ const x =+ row.x && typeof row.x === 'object' && !Array.isArray(row.x)+ ? (row.x as Record<string, unknown>)+ : {};return {slack: {enabled: slack.enabled === true,@@ -310,7 +325,11 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {},telegram: {enabled: telegram.enabled === true,- bindingCache: parseTelegramBindingCache(telegram.bindingCache),+ bindingCache: parseProviderBindingCache(telegram.bindingCache),+ },+ x: {+ enabled: x.enabled === true,+ bindingCache: parseProviderBindingCache(x.bindingCache),},};}@@ -341,6 +360,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {lifecycleAnnouncementOverride: state.lifecycleAnnouncementOverride,},telegram: { enabled: false, bindingCache: null },+ x: { enabled: false, bindingCache: null },},};}@@ -390,11 +410,13 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {return fromLegacyState({enabled: row.enabled === true,telegramEnabled: false,+ xEnabled: false,urlOverride,workspaces,bindingsCache: parseBindingsCache(row.bindingsCache),lifecycleAnnouncementOverride: null,telegramBindingCache: null,+ xBindingCache: null,});} catch (err) {log.warn(@@ -428,6 +450,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {return {enabled: account.slack.enabled,telegramEnabled: account.telegram.enabled,+ xEnabled: account.x.enabled,urlOverride: document.urlOverride,workspaces: { ...document.workspaces },bindingsCache: account.slack.bindingsCache.map((entry) => ({ ...entry })),@@ -435,6 +458,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {telegramBindingCache: account.telegram.bindingCache? { ...account.telegram.bindingCache }: null,+ xBindingCache: account.x.bindingCache ? { ...account.x.bindingCache } : null,};}@@ -470,7 +494,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {},anyProviderEnabled() {const state = read();- return state.enabled || state.telegramEnabled;+ return state.enabled || state.telegramEnabled || state.xEnabled;},setWorkspaces(workspaces) {const current = currentDocument();@@ -489,9 +513,9 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {account.slack.lifecycleAnnouncementOverride = enabled;});},- setTelegramBindingCache(entry) {+ setProviderBindingCache(provider, entry) {return mutateAccount((account) => {- account.telegram.bindingCache = entry ? { ...entry } : null;+ account[provider].bindingCache = entry ? { ...entry } : null;});},};diff --git a/apps/desktop/src/main/hook-control/workspaceProviderSourceStore.ts b/apps/desktop/src/main/hook-control/workspaceProviderSourceStore.tsindex e22978d7f7..aae2392fd3 100644--- a/apps/desktop/src/main/hook-control/workspaceProviderSourceStore.ts+++ b/apps/desktop/src/main/hook-control/workspaceProviderSourceStore.ts@@ -46,7 +46,7 @@ function isEntry(raw: unknown): raw is WorkspaceProviderSourceEntry {if (!raw || typeof raw !== 'object') return false;const r = raw as Record<string, unknown>;return (- (r.channel === 'slack' || r.channel === 'telegram') &&+ (r.channel === 'slack' || r.channel === 'telegram' || r.channel === 'x') &&(r.teamId === null || (typeof r.teamId === 'string' && r.teamId.length > 0 && r.teamId.length <= 64)) &&typeof r.workspace === 'string' &&HOOK_WORKSPACE_ALIAS_RE.test(r.workspace) &&diff --git a/apps/desktop/src/main/hook-control/xDeepLink.ts b/apps/desktop/src/main/hook-control/xDeepLink.tsnew file mode 100644index 0000000000..ccc7a061ee--- /dev/null+++ b/apps/desktop/src/main/hook-control/xDeepLink.ts@@ -0,0 +1,128 @@+/**+ * X (Twitter) URL policy for Cindy provider binding.+ *+ * The x-hook server supplies a short-lived OAuth2 (PKCE) authorize link, but+ * main re-validates the complete URL immediately before shell.openExternal.+ * Renderer input is never treated as a URL authority. This keeps credentials,+ * alternate hosts, ports, fragments and query smuggling away from the shell+ * boundary. Deliberately not shared with telegramDeepLink: the accepted URL+ * shapes have nothing in common and a merged allowlist only widens both.+ */++export class XLinkValidationError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'XLinkValidationError';+ }+}++/** X handles are 1-15 word characters; a leading @ is accepted and stripped. */+export const X_HANDLE_RE = /^[A-Za-z0-9_]{1,15}$/;++const X_HOST = 'x.com';+const X_AUTHORIZE_PATH = '/i/oauth2/authorize';+/** OAuth2 PKCE 授权页要求的精确参数键集(服务端 bind.ts 构造的形状)。 */+const X_AUTHORIZE_REQUIRED_PARAMS = [+ 'response_type',+ 'client_id',+ 'redirect_uri',+ 'scope',+ 'state',+ 'code_challenge',+ 'code_challenge_method',+] as const;++function fail(reason: string): never {+ throw new XLinkValidationError(reason);+}++function validateBase(url: URL, input: string): void {+ if (input.trim() !== input) fail('X link must not include surrounding whitespace');+ if (url.protocol !== 'https:') fail('X link must use HTTPS');+ if (url.hostname !== X_HOST) fail(`X link host must be exactly ${X_HOST}`);+ const authority = /^[A-Za-z]+:\/\/([^/?#]+)/.exec(input)?.[1];+ // URL normalizes an explicit default :443 port away, so inspect the raw+ // authority as well before handing a link to Electron's shell.+ if (authority?.toLowerCase() !== X_HOST) {+ fail('X link must not include credentials or a port');+ }+ if (url.port) fail('X link must not include a port');+ if (url.username || url.password) fail('X link must not include credentials');+ // URL.hash is also '' for an explicit trailing '#'; inspect the source so+ // even an empty fragment is excluded from the canonical shell boundary.+ if (input.includes('#')) fail('X link must not include a fragment');+}++export interface ValidXConnectLink {+ url: string;+}++/** Parse the only URL shape accepted for a Cindy X bind attempt. */+export function parseXConnectUrl(input: string): ValidXConnectLink {+ let url: URL;+ try {+ url = new URL(input);+ } catch {+ return fail('Invalid X binding URL');+ }+ validateBase(url, input);+ if (url.pathname !== X_AUTHORIZE_PATH) {+ fail(`X binding URL path must be exactly ${X_AUTHORIZE_PATH}`);+ }+ // 精确参数集合:每个必需键恰好一次、无未知键 —— 重复/多余键即拒绝,+ // URLSearchParams 的解码宽容不构成放行理由。+ const entries = [...url.searchParams.entries()];+ const seen = new Set<string>();+ for (const [key, value] of entries) {+ if (!(X_AUTHORIZE_REQUIRED_PARAMS as readonly string[]).includes(key)) {+ fail(`X binding URL contains an unexpected parameter: ${key}`);+ }+ if (seen.has(key)) fail(`X binding URL repeats parameter: ${key}`);+ seen.add(key);+ if (value.length === 0) fail(`X binding URL parameter must not be empty: ${key}`);+ }+ for (const key of X_AUTHORIZE_REQUIRED_PARAMS) {+ if (!seen.has(key)) fail(`X binding URL is missing parameter: ${key}`);+ }+ if (url.searchParams.get('response_type') !== 'code') {+ fail('X binding URL must request the authorization code flow');+ }+ if (url.searchParams.get('code_challenge_method') !== 'S256') {+ fail('X binding URL must use the S256 PKCE challenge');+ }+ return { url: url.toString() };+}++/** Profile URL for the bound bot account; accepts and strips a leading @. */+export function xProfileUrl(handle: string): string {+ const bare = handle.startsWith('@') ? handle.slice(1) : handle;+ if (!X_HANDLE_RE.test(bare)) fail('Invalid X handle');+ return `https://${X_HOST}/${bare}`;+}++/** null-safe 变体:handle 形状不合法时返回 null(缓存恢复等容错路径用)。 */+export function xProfileUrlOrNull(handle: string | null): string | null {+ if (handle === null) return null;+ try {+ return xProfileUrl(handle);+ } catch {+ return null;+ }+}++/** Validate all X URLs that the Settings actions may hand to Electron shell. */+export function validateXExternalUrl(input: string): string {+ let url: URL;+ try {+ url = new URL(input);+ } catch {+ return fail('Invalid X URL');+ }+ validateBase(url, input);+ if (url.pathname === X_AUTHORIZE_PATH) return parseXConnectUrl(input).url;+ const match = /^\/([^/]+)$/.exec(url.pathname);+ const handle = match?.[1] ?? '';+ if (url.pathname.includes('%')) fail('X handle must not be encoded');+ if (url.search !== '' || input.includes('?')) fail('X profile link must not include a query');+ return xProfileUrl(handle);+}diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex e2f1f843d8..bacbc87501 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1611,7 +1611,7 @@ export async function setSessionProviderIdInDb(}/** Persist the provider-facing source for a newly-created shared IM session. */-export async function setSessionSourceInDb(sessionId: string, source: 'telegram'): Promise<void> {+export async function setSessionSourceInDb(sessionId: string, source: 'telegram' | 'x'): Promise<void> {try {const db = getDbClient().drizzle;await db.update(sessions).set({ source }).where(eq(sessions.id, sessionId));diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 5db948e2c9..9ef1420faf 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -25,6 +25,7 @@ const SESSION_SOURCES = ['feishu','slack','telegram',+ 'x','discord','wechat','dingtalk',diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 2c7eabce8c..d732f78c48 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3461,7 +3461,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:hook-control:set-enabled', { enabled }),setLifecycleAnnouncement: (enabled: boolean): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:set-lifecycle-announcement', { enabled }),- setProviderEnabled: (provider: 'telegram', enabled: boolean): Promise<{ hook: unknown }> =>+ setProviderEnabled: (+ provider: 'telegram' | 'x',+ enabled: boolean,+ ): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:set-provider-enabled', { provider, enabled }),setWorkspaces: (workspaces: Record<string, string>): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:set-workspaces', { workspaces }),@@ -3480,14 +3483,17 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:hook-control:revoke-team', { teamId }),cancelPendingBind: (): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:cancel-pending-bind'),- providerBindStart: (): Promise<{ hook: unknown }> =>- ipcRenderer.invoke('maker:hook-control:provider-bind-start'),- providerBindCancel: (): Promise<{ hook: unknown }> =>- ipcRenderer.invoke('maker:hook-control:provider-bind-cancel'),- providerBindRevoke: (): Promise<{ hook: unknown }> =>- ipcRenderer.invoke('maker:hook-control:provider-bind-revoke'),- openTelegramAction: (action: 'connect' | 'provider' | 'add-to-group'): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:hook-control:telegram-open-action', { action }),+ providerBindStart: (provider: 'telegram' | 'x'): Promise<{ hook: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:provider-bind-start', { provider }),+ providerBindCancel: (provider: 'telegram' | 'x'): Promise<{ hook: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:provider-bind-cancel', { provider }),+ providerBindRevoke: (provider: 'telegram' | 'x'): Promise<{ hook: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:provider-bind-revoke', { provider }),+ openProviderAction: (+ provider: 'telegram' | 'x',+ action: 'connect' | 'provider' | 'add-to-group',+ ): Promise<{ ok: true }> =>+ ipcRenderer.invoke('maker:hook-control:provider-open-action', { provider, action }),// 目录偏好远程读写(数据正本在 slack-hook-server, 与 Slack /model 卡同一份;// teamId 为 multi-team 下的归属 team, 单绑定缺省)getWorkspacePrefs: (): Promise<{ prefs: unknown }> =>@@ -3502,18 +3508,19 @@ contextBridge.exposeInMainWorld('electronAPI', {patch,...(teamId !== undefined ? { teamId } : {}),}),- getProviderWorkspacePrefs: (): Promise<{ prefs: unknown }> =>- ipcRenderer.invoke('maker:hook-control:provider-prefs-get'),+ getProviderWorkspacePrefs: (provider: 'telegram' | 'x'): Promise<{ prefs: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:provider-prefs-get', { provider }),setProviderWorkspacePrefs: (+ provider: 'telegram' | 'x',workspace: string,patch: Record<string, string | null>,): Promise<{ prefs: unknown }> =>- ipcRenderer.invoke('maker:hook-control:provider-prefs-set', { workspace, patch }),+ ipcRenderer.invoke('maker:hook-control:provider-prefs-set', { provider, workspace, patch }),// 工作目录模型来源偏好(纯本地, 不经 WS; providerId=null 清除条目)getWorkspaceProviderSources: (): Promise<{ entries: unknown }> =>ipcRenderer.invoke('maker:hook-control:workspace-provider-source-get'),setWorkspaceProviderSource: (payload: {- channel: 'slack' | 'telegram';+ channel: 'slack' | 'telegram' | 'x';teamId: string | null;workspace: string;providerId: string | null;diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex 9b1b83316c..5ca269b42f 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -108,6 +108,7 @@ describe('automation-generated sessions', () => {'feishu','slack','telegram',+ 'x','discord','wechat','dingtalk',diff --git a/apps/desktop/src/renderer/components/chat/HookTaskCard.tsx b/apps/desktop/src/renderer/components/chat/HookTaskCard.tsxindex 3034188d1c..5725d23ae2 100644--- a/apps/desktop/src/renderer/components/chat/HookTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/HookTaskCard.tsx@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { Collapse } from '@/components/ui/collapse';import SlackIcon from './SlackIcon';+import XIcon from './XIcon';interface ThreadContextEntry {author: string;@@ -35,6 +36,8 @@ function ImIcon({ im }: { im: string }) {return <SlackIcon className="w-[14px] h-[14px] shrink-0 text-[var(--text-primary)]" />;case 'telegram':return <Send size={14} strokeWidth={1.75} className="shrink-0 text-[var(--text-primary)]" />;+ case 'x':+ return <XIcon className="w-[14px] h-[14px] shrink-0 text-[var(--text-primary)]" />;default:return <MessageSquare size={14} strokeWidth={1.75} className="shrink-0 text-[var(--text-primary)]" />;}@@ -46,6 +49,8 @@ function imLabel(im: string): string {return 'Slack';case 'telegram':return 'Telegram';+ case 'x':+ return 'X';case 'feishu':return 'Feishu';default:diff --git a/apps/desktop/src/renderer/components/chat/XIcon.tsx b/apps/desktop/src/renderer/components/chat/XIcon.tsxnew file mode 100644index 0000000000..f7bc276057--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/XIcon.tsx@@ -0,0 +1,7 @@+export default function XIcon({ className }: { className?: string }) {+ return (+ <svg viewBox="0 0 24 24" fill="currentColor" className={className}>+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231zm-1.161 17.52h1.833L7.084 4.126H5.117l11.966 15.644z" />+ </svg>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsxindex a65172e627..a5a27ef08a 100644--- a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx@@ -22,6 +22,9 @@* 开关; 等待期显示引导行(安装/复制链接 + 等待提示);* - Telegram 卡: 同构 —— 开关 + 状态徽章 + 关联动作(打开 bot / 加群 /* 解绑);+ * - X 卡: 与 Telegram 卡同构(provider-neutral 状态机), 绑定走 X OAuth2+ * 授权页(open connect url / 复制链接), 无加群概念(动作按 binding.actions+ * 数据驱动, X 的 actions 里没有 add_to_group 自然不渲染);* - 工作目录映射内嵌在每张渠道卡的展开区: 目录清单**设备共享**(所有渠道* 同一份, 刻意设计, 任一卡里增删都作用于全部渠道), 运行偏好按渠道隔离,* 由所在卡决定读写哪个渠道的那份(Slack 多绑定时再叠 workspace 归属@@ -53,13 +56,17 @@ import {HOOK_WORKSPACE_ALIAS_RE,slackHookInstallUrl,type HookTeamBindingView,+ type ProviderHookView,type SlackHookView,} from '../../../shared/hookControlIpc';++/** provider-neutral 渠道卡覆盖的 provider(Slack 走 legacy 专属卡)。 */+type NeutralCardProvider = 'telegram' | 'x';import { useHookWorkspacePrefs, WorkspacePrefsEditor } from './HookWorkspacePrefsEditor';import { ImChannelSettingsCard } from './ImChannelSettingsCard';/** 「官方」栏的渠道手风琴卡(同刻最多展开一张, 交互对齐「个人」栏)。 */-type CindyImCard = 'slack' | 'telegram';+type CindyImCard = 'slack' | 'telegram' | 'x';/** 渠道卡状态徽章的色调档(映射到「个人」栏同款 --settings-badge-* token)。 */type ChannelBadgeTone = 'ok' | 'progress' | 'attention' | 'error';@@ -430,10 +437,11 @@ export function HookConnectionsSection() {await saveWorkspaces(next);};- // 目录清单设备共享;运行偏好按 provider 隔离。两个 hook 都始终调用,避免+ // 目录清单设备共享;运行偏好按 provider 隔离。三个 hook 都始终调用,避免// provider 开关切换时改变 React hook 顺序。const slackPrefsState = useHookWorkspacePrefs(hook, 'slack');const telegramPrefsState = useHookWorkspacePrefs(hook, 'telegram');+ const xPrefsState = useHookWorkspacePrefs(hook, 'x');/** 复制授权链接(远程控制兜底: 到本机浏览器打开, 规则 26)。 */const handleCopyLink = async () => {@@ -458,21 +466,24 @@ export function HookConnectionsSection() {}};- const handleTelegramToggle = (enabled: boolean) => {- if (enabled) setExpandedCard('telegram');- runHookAction(() => window.electronAPI.hookControl.setProviderEnabled('telegram', enabled));+ const handleProviderToggle = (provider: NeutralCardProvider, enabled: boolean) => {+ if (enabled) setExpandedCard(provider);+ runHookAction(() => window.electronAPI.hookControl.setProviderEnabled(provider, enabled));};- const handleTelegramOpen = (action: 'connect' | 'provider' | 'add-to-group') => {- void window.electronAPI.hookControl.openTelegramAction(action).catch((err: unknown) => {+ const handleProviderOpen = (+ provider: NeutralCardProvider,+ action: 'connect' | 'provider' | 'add-to-group',+ ) => {+ void window.electronAPI.hookControl.openProviderAction(provider, action).catch((err: unknown) => {toast.error(extractIpcError(err)?.message ?? t('settings.remoteControl.hook.toast.actionFailed'),);});};- const handleCopyTelegramLink = async () => {- const url = hook?.telegram.binding?.connectUrl;+ const handleCopyProviderLink = async (provider: NeutralCardProvider) => {+ const url = hook?.[provider].binding?.connectUrl;if (!url) return;try {await navigator.clipboard.writeText(url);@@ -482,17 +493,17 @@ export function HookConnectionsSection() {}};- const handleTelegramUnlink = async () => {+ const handleProviderUnlink = async (provider: NeutralCardProvider) => {const targetBindingId =- hook?.telegram.binding?.state === 'confirmed' ? hook.telegram.binding.bindingId : null;+ hook?.[provider].binding?.state === 'confirmed' ? hook[provider].binding.bindingId : null;if (targetBindingId === null) return;const ok = await confirm({- title: t('settings.remoteControl.hook.telegram.unlinkConfirmTitle'),- description: t('settings.remoteControl.hook.telegram.unlinkConfirmDescription'),- confirmText: t('settings.remoteControl.hook.telegram.unlink'),+ title: t(`settings.remoteControl.hook.${provider}.unlinkConfirmTitle`),+ description: t(`settings.remoteControl.hook.${provider}.unlinkConfirmDescription`),+ confirmText: t(`settings.remoteControl.hook.${provider}.unlink`),cancelText: t('settings.remoteControl.hook.notInstalled.confirmCancel'),});- const currentBinding = hookRef.current?.telegram.binding;+ const currentBinding = hookRef.current?.[provider].binding;if (!ok ||!mountedRef.current ||@@ -501,7 +512,7 @@ export function HookConnectionsSection() {) {return;}- runHookAction(() => window.electronAPI.hookControl.providerBindRevoke());+ runHookAction(() => window.electronAPI.hookControl.providerBindRevoke(provider));};/**@@ -615,63 +626,66 @@ export function HookConnectionsSection() {hook.lastError === 'not logged in'? t('settings.remoteControl.hook.loginRequired'): hook.lastError;- const telegram = hook.telegram;- const telegramBinding = telegram.binding;- const telegramActions = telegramBinding?.actions ?? [];- const telegramState = telegramBinding?.state ?? 'none';- // A configured endpoint is the rollout gate. Capability negotiation starts- // only after the user enables Telegram, so the disabled card cannot depend- // on an already-received welcome to become discoverable.- const telegramVisible =- telegram.url.length > 0 || telegram.capabilityPending || telegram.available || telegram.enabled;- const telegramConfirmed = telegramState === 'confirmed';- const telegramInProgress =- telegram.enabled && (telegramState === 'pending' || telegramState === 'awaiting_confirmation');- const telegramCanStartLink =- telegramState === 'none' ||- ((telegramState === 'failed' ||- telegramState === 'denied' ||- telegramState === 'expired' ||- telegramState === 'revoked' ||- telegramState === 'superseded') &&- telegramActions.includes('retry'));- // The switch represents provider ingress, not only the final bind state. Keep- // it on while Telegram is waiting for /start confirmation so clicking it is- // an unsurprising cancel/disable action.- const telegramToggleChecked = telegram.enabled;- /** Telegram 卡的状态徽章: 只承载传输/能力状态, 绑定细节走摘要与展开区。 */- const telegramBadge: { tone: ChannelBadgeTone; label: string } = !telegram.enabled- ? { tone: 'attention', label: t('settings.remoteControl.hook.telegram.status.disabled') }- : telegram.status === 'error'- ? { tone: 'error', label: t('settings.remoteControl.hook.status.error') }- : telegram.capabilityPending- ? { tone: 'progress', label: t('settings.remoteControl.hook.telegram.status.checking') }- : !telegram.available- ? {- tone: 'attention',- label: t('settings.remoteControl.hook.telegram.status.unavailable'),- }- : {- tone: transportBadgeTone(telegram.status),- label: t(`settings.remoteControl.hook.status.${telegram.status}`),- };- /** Telegram 绑定态一行(收起行摘要与展开区共用文案)。 */- const telegramBindingLine =- telegram.enabled &&- telegram.available &&- !telegram.capabilityPending &&- telegram.status === 'connected'- ? telegramConfirmed- ? t('settings.remoteControl.hook.telegram.status.confirmed', {- user: telegramBinding?.principalName ?? telegramBinding?.principalId ?? '',- bot: telegramBinding?.scopeName ?? '',- })- : t(`settings.remoteControl.hook.telegram.status.${telegramState}`)- : null;- const telegramErrorText =- telegram.lastError === 'not logged in'- ? t('settings.remoteControl.hook.loginRequired')- : telegram.lastError;+ /**+ * provider-neutral 渠道卡(Telegram / X)的派生展示状态。i18n 前缀按+ * provider 取 settings.remoteControl.hook.<provider>.*, 两块 key 结构平行。+ */+ const providerCardState = (provider: NeutralCardProvider, view: ProviderHookView) => {+ const binding = view.binding;+ const actions = binding?.actions ?? [];+ const state = binding?.state ?? 'none';+ // A configured endpoint is the rollout gate. Capability negotiation starts+ // only after the user enables the provider, so the disabled card cannot+ // depend on an already-received welcome to become discoverable.+ const visible =+ view.url.length > 0 || view.capabilityPending || view.available || view.enabled;+ const confirmed = state === 'confirmed';+ const inProgress =+ view.enabled && (state === 'pending' || state === 'awaiting_confirmation');+ const canStartLink =+ state === 'none' ||+ ((state === 'failed' ||+ state === 'denied' ||+ state === 'expired' ||+ state === 'revoked' ||+ state === 'superseded') &&+ actions.includes('retry'));+ // The switch represents provider ingress, not only the final bind state.+ // Keep it on while the provider is waiting for confirmation so clicking it+ // is an unsurprising cancel/disable action.+ const toggleChecked = view.enabled;+ /** 状态徽章: 只承载传输/能力状态, 绑定细节走摘要与展开区。 */+ const badge: { tone: ChannelBadgeTone; label: string } = !view.enabled+ ? { tone: 'attention', label: t(`settings.remoteControl.hook.${provider}.status.disabled`) }+ : view.status === 'error'+ ? { tone: 'error', label: t('settings.remoteControl.hook.status.error') }+ : view.capabilityPending+ ? { tone: 'progress', label: t(`settings.remoteControl.hook.${provider}.status.checking`) }+ : !view.available+ ? {+ tone: 'attention',+ label: t(`settings.remoteControl.hook.${provider}.status.unavailable`),+ }+ : {+ tone: transportBadgeTone(view.status),+ label: t(`settings.remoteControl.hook.status.${view.status}`),+ };+ /** 绑定态一行(收起行摘要与展开区共用文案)。 */+ const bindingLine =+ view.enabled && view.available && !view.capabilityPending && view.status === 'connected'+ ? confirmed+ ? t(`settings.remoteControl.hook.${provider}.status.confirmed`, {+ user: binding?.principalName ?? binding?.principalId ?? '',+ bot: binding?.scopeName ?? '',+ })+ : t(`settings.remoteControl.hook.${provider}.status.${state}`)+ : null;+ const errorText =+ view.lastError === 'not logged in'+ ? t('settings.remoteControl.hook.loginRequired')+ : view.lastError;+ return { binding, actions, state, visible, confirmed, inProgress, canStartLink, toggleChecked, badge, bindingLine, errorText };+ };const workdirCount = Object.keys(hook.workspaces).length;const hasActiveSlackBinding = multiUi? activeTeams.length > 0@@ -811,6 +825,162 @@ export function HookConnectionsSection() {</>);+ /**+ * provider-neutral 渠道卡(Telegram / X 同构)。用普通函数而非内联子组件+ * 渲染(同 renderWorkdirSection 的理由: 内联组件类型每次渲染重建会导致+ * 子树 remount)。动作按钮完全由 binding.actions 数据驱动 —— X 的 actions+ * 里没有 add_to_group, 加群按钮自然不渲染。+ */+ const renderProviderCard = (provider: NeutralCardProvider) => {+ const view = hook[provider] as ProviderHookView | undefined;+ if (view === undefined) return null; // 旧 main 快照尚无该 provider 字段时不渲染+ const cs = providerCardState(provider, view);+ if (!cs.visible) return null;+ const prefsState = provider === 'telegram' ? telegramPrefsState : xPrefsState;+ return (+ <ImChannelSettingsCard+ id={`cindy-im-${provider}`}+ title={t(+ provider === 'telegram'+ ? 'settings.tina.prefs.providerTelegram'+ : 'settings.tina.prefs.providerX',+ )}+ description={t(`settings.remoteControl.hook.${provider}.description`)}+ routeSummary={cs.bindingLine}+ status={<ChannelStatusBadge tone={cs.badge.tone} label={cs.badge.label} />}+ headerAction={+ <Switch+ checked={cs.toggleChecked}+ disabled={!view.enabled && view.url.length === 0}+ onCheckedChange={(enabled) => handleProviderToggle(provider, enabled)}+ aria-label={t(`settings.remoteControl.hook.${provider}.toggleAria`)}+ />+ }+ expanded={expandedCard === provider}+ onToggle={() => toggleCard(provider)}+ >+ <div className="flex flex-col gap-2">+ {!view.enabled ? (+ <span className="text-11 leading-relaxed text-[var(--text-tertiary)]">+ {t(`settings.remoteControl.hook.${provider}.disabledHint`)}+ </span>+ ) : null}++ {/* 绑定进度/结果一行(完成关联引导、失败原因等; 已关联的摘要由+ 收起行承载, 展开区不重复) */}+ {cs.bindingLine !== null && !cs.confirmed ? (+ <span+ className={`text-11 leading-relaxed ${+ cs.state === 'failed' ||+ cs.state === 'denied' ||+ cs.state === 'expired' ||+ cs.state === 'superseded'+ ? 'text-[var(--error-fg)]'+ : 'text-[var(--text-tertiary)]'+ }`}+ >+ {cs.bindingLine}+ </span>+ ) : null}++ {view.enabled &&+ view.status === 'error' &&+ cs.errorText &&+ cs.errorText !== cs.badge.label ? (+ <span className="text-11 leading-relaxed text-[var(--error-fg)]">{cs.errorText}</span>+ ) : null}++ {view.enabled && view.available ? (+ <div className="flex flex-wrap items-center gap-2">+ {cs.inProgress && cs.binding?.connectUrl ? (+ <>+ {cs.actions.includes('open_connect_url') ? (+ <button+ type="button"+ onClick={() => handleProviderOpen(provider, 'connect')}+ className={pillBtn}+ >+ {t(`settings.remoteControl.hook.${provider}.openApp`)}+ </button>+ ) : null}+ {cs.actions.includes('copy_connect_url') ? (+ <button+ type="button"+ onClick={() => void handleCopyProviderLink(provider)}+ className={pillBtn}+ >+ {t('settings.remoteControl.hook.binding.copyLink')}+ </button>+ ) : null}+ </>+ ) : null}+ {cs.inProgress && cs.actions.includes('cancel') ? (+ <button+ type="button"+ onClick={() =>+ runHookAction(() => window.electronAPI.hookControl.providerBindCancel(provider))+ }+ className={pillBtn}+ >+ {t(`settings.remoteControl.hook.${provider}.cancel`)}+ </button>+ ) : null}+ {cs.confirmed ? (+ <>+ {cs.actions.includes('open_provider') ? (+ <button+ type="button"+ onClick={() => handleProviderOpen(provider, 'provider')}+ className={pillBtn}+ >+ {t(`settings.remoteControl.hook.${provider}.openBot`)}+ </button>+ ) : null}+ {cs.actions.includes('add_to_group') ? (+ <button+ type="button"+ onClick={() => handleProviderOpen(provider, 'add-to-group')}+ className={pillBtn}+ >+ {t(`settings.remoteControl.hook.${provider}.addToGroup`)}+ </button>+ ) : null}+ {cs.actions.includes('revoke') ? (+ <button+ type="button"+ onClick={() => void handleProviderUnlink(provider)}+ className={pillBtn}+ >+ {t(`settings.remoteControl.hook.${provider}.unlink`)}+ </button>+ ) : null}+ </>+ ) : cs.canStartLink ? (+ <button+ type="button"+ onClick={() =>+ runHookAction(() => window.electronAPI.hookControl.providerBindStart(provider))+ }+ className={pillBtn}+ >+ {t(+ cs.state === 'none'+ ? `settings.remoteControl.hook.${provider}.connect`+ : `settings.remoteControl.hook.${provider}.retry`,+ )}+ </button>+ ) : null}+ </div>+ ) : null}++ {/* 工作目录映射(清单共享, 偏好取本 provider 那份) */}+ {view.enabled ? renderWorkdirSection(prefsState) : null}+ </div>+ </ImChannelSettingsCard>+ );+ };++return (<div className="flex flex-col gap-3"><p className="text-12 text-[var(--text-tertiary)]">@@ -1131,146 +1301,9 @@ export function HookConnectionsSection() {</div></ImChannelSettingsCard>- {/* ── Telegram 渠道卡 ──────────────────────────────────────────── */}- {telegramVisible ? (- <ImChannelSettingsCard- id="cindy-im-telegram"- title={t('settings.tina.prefs.providerTelegram')}- description={t('settings.remoteControl.hook.telegram.description')}- routeSummary={telegramBindingLine}- status={<ChannelStatusBadge tone={telegramBadge.tone} label={telegramBadge.label} />}- headerAction={- <Switch- checked={telegramToggleChecked}- disabled={!telegram.enabled && telegram.url.length === 0}- onCheckedChange={handleTelegramToggle}- aria-label={t('settings.remoteControl.hook.telegram.toggleAria')}- />- }- expanded={expandedCard === 'telegram'}- onToggle={() => toggleCard('telegram')}- >- <div className="flex flex-col gap-2">- {!telegram.enabled ? (- <span className="text-11 leading-relaxed text-[var(--text-tertiary)]">- {t('settings.remoteControl.hook.telegram.disabledHint')}- </span>- ) : null}-- {/* 绑定进度/结果一行(「点 Start 完成关联」引导、失败原因等;- 已关联的摘要由收起行承载, 展开区不重复) */}- {telegramBindingLine !== null && !telegramConfirmed ? (- <span- className={`text-11 leading-relaxed ${- telegramState === 'failed' ||- telegramState === 'denied' ||- telegramState === 'expired' ||- telegramState === 'superseded'- ? 'text-[var(--error-fg)]'- : 'text-[var(--text-tertiary)]'- }`}- >- {telegramBindingLine}- </span>- ) : null}-- {telegram.enabled &&- telegram.status === 'error' &&- telegramErrorText &&- telegramErrorText !== telegramBadge.label ? (- <span className="text-11 leading-relaxed text-[var(--error-fg)]">- {telegramErrorText}- </span>- ) : null}-- {telegram.enabled && telegram.available ? (- <div className="flex flex-wrap items-center gap-2">- {telegramInProgress && telegramBinding?.connectUrl ? (- <>- {telegramActions.includes('open_connect_url') ? (- <button- type="button"- onClick={() => handleTelegramOpen('connect')}- className={pillBtn}- >- {t('settings.remoteControl.hook.telegram.openTelegram')}- </button>- ) : null}- {telegramActions.includes('copy_connect_url') ? (- <button- type="button"- onClick={() => void handleCopyTelegramLink()}- className={pillBtn}- >- {t('settings.remoteControl.hook.binding.copyLink')}- </button>- ) : null}- </>- ) : null}- {telegramInProgress && telegramActions.includes('cancel') ? (- <button- type="button"- onClick={() =>- runHookAction(() => window.electronAPI.hookControl.providerBindCancel())- }- className={pillBtn}- >- {t('settings.remoteControl.hook.telegram.cancel')}- </button>- ) : null}- {telegramConfirmed ? (- <>- {telegramActions.includes('open_provider') ? (- <button- type="button"- onClick={() => handleTelegramOpen('provider')}- className={pillBtn}- >- {t('settings.remoteControl.hook.telegram.openBot')}- </button>- ) : null}- {telegramActions.includes('add_to_group') ? (- <button- type="button"- onClick={() => handleTelegramOpen('add-to-group')}- className={pillBtn}- >- {t('settings.remoteControl.hook.telegram.addToGroup')}- </button>- ) : null}- {telegramActions.includes('revoke') ? (- <button- type="button"- onClick={() => void handleTelegramUnlink()}- className={pillBtn}- >- {t('settings.remoteControl.hook.telegram.unlink')}- </button>- ) : null}- </>- ) : telegramCanStartLink ? (- <button- type="button"- onClick={() =>- runHookAction(() => window.electronAPI.hookControl.providerBindStart())- }- className={pillBtn}- >- {t(- telegramState === 'none'- ? 'settings.remoteControl.hook.telegram.connect'- : 'settings.remoteControl.hook.telegram.retry',- )}- </button>- ) : null}- </div>- ) : null}-- {/* 工作目录映射(清单共享, 偏好取 Telegram 那份) */}- {telegram.enabled ? renderWorkdirSection(telegramPrefsState) : null}- </div>- </ImChannelSettingsCard>- ) : null}+ {/* ── provider-neutral 渠道卡(Telegram / X, 同构渲染) ─────────── */}+ {renderProviderCard('telegram')}+ {renderProviderCard('x')}</div>);}diff --git a/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx b/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsxindex adce5d113b..59c35c93a6 100644--- a/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx+++ b/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx@@ -126,7 +126,13 @@ export interface HookWorkspacePrefsState {showTeamChip: boolean;}-export type HookPrefsProvider = 'slack' | 'telegram';+export type HookPrefsProvider = 'slack' | 'telegram' | 'x';++/** provider-neutral prefs 线(Telegram / X): 走 provider.bind/prefs 帧, 绑定按 bindingId 归属。 */+type NeutralPrefsProvider = Exclude<HookPrefsProvider, 'slack'>;+function isNeutralPrefsProvider(provider: HookPrefsProvider): provider is NeutralPrefsProvider {+ return provider !== 'slack';+}function isProviderPrefsView(view: HookPrefsView | ProviderPrefsView): view is ProviderPrefsView {return 'provider' in view;@@ -150,24 +156,20 @@ export function useHookWorkspacePrefs(const [providerSources, setProviderSources] = useState<HookWorkspaceProviderSourceEntry[]>([]);// latest-wins 守卫(Copilot review): 快速连选/跨窗口广播时, 较慢的旧回复不得覆盖新状态。const providerSourceRevisionRef = useRef(0);- const telegramBindingId =- provider === 'telegram' && hook?.telegram.binding?.state === 'confirmed'- ? hook.telegram.binding.bindingId- : null;- const connected =- provider === 'telegram'- ? hook?.telegram.enabled === true &&- hook.telegram.available &&- hook.telegram.status === 'connected'- : hook?.enabled === true && hook.status === 'connected';- const providerBindingConfirmed =- provider !== 'telegram' || hook?.telegram.binding?.state === 'confirmed';+ const neutral = isNeutralPrefsProvider(provider);+ const neutralView = neutral && hook !== null ? hook[provider as NeutralPrefsProvider] : null;+ const neutralBindingId =+ neutralView?.binding?.state === 'confirmed' ? neutralView.binding.bindingId : null;+ const connected = neutral+ ? neutralView?.enabled === true && neutralView.available && neutralView.status === 'connected'+ : hook?.enabled === true && hook.status === 'connected';+ const providerBindingConfirmed = !neutral || neutralView?.binding?.state === 'confirmed';const readyIdentity =connected && providerBindingConfirmed- ? provider === 'telegram'- ? telegramBindingId === null+ ? neutral+ ? neutralBindingId === null? null- : `telegram:${telegramBindingId}`+ : `${provider}:${neutralBindingId}`: 'slack': null;// Initialised to null (never a real identity) so the ready-edge effect below@@ -177,23 +179,22 @@ export function useHookWorkspacePrefs(const lastReadyIdentityRef = useRef<string | null>(null);const fetchRevisionRef = useRef(0);const mutationRevisionRef = useRef(0);- const telegramBindingIdRef = useRef<string | null>(telegramBindingId);- telegramBindingIdRef.current = telegramBindingId;+ const neutralBindingIdRef = useRef<string | null>(neutralBindingId);+ neutralBindingIdRef.current = neutralBindingId;const fetchPrefs = useCallback(async () => {const revision = ++fetchRevisionRef.current;try {- const res =- provider === 'telegram'- ? await window.electronAPI.hookControl.getProviderWorkspacePrefs()- : await window.electronAPI.hookControl.getWorkspacePrefs();+ const res = isNeutralPrefsProvider(provider)+ ? await window.electronAPI.hookControl.getProviderWorkspacePrefs(provider)+ : await window.electronAPI.hookControl.getWorkspacePrefs();if (revision !== fetchRevisionRef.current) return;const nextPrefs: HookPrefsView | ProviderPrefsView = res.prefs;if (- provider === 'telegram' &&+ isNeutralPrefsProvider(provider) &&(!isProviderPrefsView(nextPrefs) ||- nextPrefs.provider !== 'telegram' ||- nextPrefs.bindingId !== telegramBindingIdRef.current)+ nextPrefs.provider !== provider ||+ nextPrefs.bindingId !== neutralBindingIdRef.current)) {return;}@@ -213,11 +214,11 @@ export function useHookWorkspacePrefs(useEffect(() => {let active = true;const applyIncoming = (view: HookPrefsView | ProviderPrefsView) => {- if (provider === 'telegram') {+ if (isNeutralPrefsProvider(provider)) {if (!isProviderPrefsView(view) ||- view.provider !== 'telegram' ||- view.bindingId !== telegramBindingIdRef.current+ view.provider !== provider ||+ view.bindingId !== neutralBindingIdRef.current) {return;}@@ -229,12 +230,11 @@ export function useHookWorkspacePrefs(setPrefsView(view);setLoadError(null);};- const offPrefs =- provider === 'telegram'- ? window.electronAPI.hookControl.onProviderPrefsChanged((view) => {- if (view.provider === 'telegram') applyIncoming(view);- })- : window.electronAPI.hookControl.onPrefsChanged(applyIncoming);+ const offPrefs = isNeutralPrefsProvider(provider)+ ? window.electronAPI.hookControl.onProviderPrefsChanged((view) => {+ if (view.provider === provider) applyIncoming(view);+ })+ : window.electronAPI.hookControl.onPrefsChanged(applyIncoming);// The ready-edge effect below performs the initial prefs fetch (only when// reachable). The subscription set up here just needs to exist first so no// server push is missed before that fetch resolves.@@ -306,17 +306,16 @@ export function useHookWorkspacePrefs(const selectedTeamId = teams.some((tm) => tm.teamId === selectedTeamRaw)? selectedTeamRaw: (teams[0]?.teamId ?? null);- const activePrefsView: HookPrefsView | ProviderPrefsView | null =- provider === 'telegram'- ? prefsView !== null &&- isProviderPrefsView(prefsView) &&- prefsView.provider === 'telegram' &&- prefsView.bindingId === telegramBindingId- ? prefsView- : null- : prefsView !== null && !isProviderPrefsView(prefsView)- ? prefsView- : null;+ const activePrefsView: HookPrefsView | ProviderPrefsView | null = neutral+ ? prefsView !== null &&+ isProviderPrefsView(prefsView) &&+ prefsView.provider === provider &&+ prefsView.bindingId === neutralBindingId+ ? prefsView+ : null+ : prefsView !== null && !isProviderPrefsView(prefsView)+ ? prefsView+ : null;const prefsFor = useCallback((alias: string): HookWorkspacePrefs => {@@ -379,14 +378,13 @@ export function useHookWorkspacePrefs(const revision = ++fetchRevisionRef.current;const mutationRevision = ++mutationRevisionRef.current;setPendingWs(workspace);- const request =- provider === 'telegram'- ? window.electronAPI.hookControl.setProviderWorkspacePrefs(workspace, patch)- : window.electronAPI.hookControl.setWorkspacePrefs(- workspace,- patch,- multiTeam ? selectedTeamId : undefined,- );+ const request = isNeutralPrefsProvider(provider)+ ? window.electronAPI.hookControl.setProviderWorkspacePrefs(provider, workspace, patch)+ : window.electronAPI.hookControl.setWorkspacePrefs(+ workspace,+ patch,+ multiTeam ? selectedTeamId : undefined,+ );void request.then((res) => {// 来源落地在快照守卫**之前**(codex review): invoke 成功 = 远端已确认@@ -399,10 +397,10 @@ export function useHookWorkspacePrefs(if (revision !== fetchRevisionRef.current) return;const nextPrefs: HookPrefsView | ProviderPrefsView = res.prefs;if (- provider === 'telegram' &&+ isNeutralPrefsProvider(provider) &&(!isProviderPrefsView(nextPrefs) ||- nextPrefs.provider !== 'telegram' ||- nextPrefs.bindingId !== telegramBindingIdRef.current)+ nextPrefs.provider !== provider ||+ nextPrefs.bindingId !== neutralBindingIdRef.current)) {return;}@@ -429,7 +427,9 @@ export function useHookWorkspacePrefs(const providerLabel = t(provider === 'telegram'? 'settings.tina.prefs.providerTelegram'- : 'settings.tina.prefs.providerSlack',+ : provider === 'x'+ ? 'settings.tina.prefs.providerX'+ : 'settings.tina.prefs.providerSlack',);const hint = !connected? t('settings.tina.prefs.requireConnected', { provider: providerLabel })diff --git a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsxindex 5cdeb93709..71c41bba50 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx@@ -15,7 +15,7 @@ const ipc = vi.hoisted(() => ({providerBindRevoke: vi.fn(),cancelPendingBind: vi.fn(),revokeTeam: vi.fn(),- openTelegramAction: vi.fn(),+ openProviderAction: vi.fn(),openExternal: vi.fn(),}));const dialog = vi.hoisted(() => ({ confirm: vi.fn() }));@@ -87,6 +87,7 @@ async function expandChannelCard(titleKey: RegExp) {}const SLACK_CARD = /settings\.tina\.prefs\.providerSlack/;const TELEGRAM_CARD = /settings\.tina\.prefs\.providerTelegram/;+const X_CARD = /settings\.tina\.prefs\.providerX/;const BASE_HOOK: SlackHookView = {enabled: false,@@ -108,6 +109,15 @@ const BASE_HOOK: SlackHookView = {capabilityPending: false,binding: null,},+ x: {+ enabled: false,+ url: '',+ status: 'disabled',+ lastError: null,+ available: false,+ capabilityPending: false,+ binding: null,+ },};describe('HookConnectionsSection Telegram binding actions', () => {@@ -118,7 +128,7 @@ describe('HookConnectionsSection Telegram binding actions', () => {ipc.setLifecycleAnnouncement.mockResolvedValue({ hook: BASE_HOOK });ipc.providerBindRevoke.mockResolvedValue({ hook: BASE_HOOK });ipc.revokeTeam.mockResolvedValue({ hook: BASE_HOOK });- ipc.openTelegramAction.mockResolvedValue(undefined);+ ipc.openProviderAction.mockResolvedValue(undefined);dialog.confirm.mockResolvedValue(true);(window as unknown as { electronAPI: unknown }).electronAPI = {hookControl: {@@ -131,7 +141,7 @@ describe('HookConnectionsSection Telegram binding actions', () => {providerBindRevoke: ipc.providerBindRevoke,cancelPendingBind: ipc.cancelPendingBind,revokeTeam: ipc.revokeTeam,- openTelegramAction: ipc.openTelegramAction,+ openProviderAction: ipc.openProviderAction,},openExternal: ipc.openExternal,};@@ -302,7 +312,7 @@ describe('HookConnectionsSection Telegram binding actions', () => {await expandChannelCard(TELEGRAM_CARD);const openButton = await screen.findByRole('button', {- name: 'settings.remoteControl.hook.telegram.openTelegram',+ name: 'settings.remoteControl.hook.telegram.openApp',});expect(screen.getByRole('button', { name: 'settings.remoteControl.hook.binding.copyLink' }),@@ -312,7 +322,111 @@ describe('HookConnectionsSection Telegram binding actions', () => {).toBeTruthy();fireEvent.click(openButton);- await waitFor(() => expect(ipc.openTelegramAction).toHaveBeenCalledWith('connect'));+ await waitFor(() => expect(ipc.openProviderAction).toHaveBeenCalledWith('telegram', 'connect'));+ });++ it('hides the X card entirely while the endpoint manifest leaves xHookWsUrl empty', async () => {+ // BASE_HOOK 的 x.url 为空且未启用/不可用 —— 端点清单缺失即灰度关闭,+ // 设置页不得出现 X 入口(providerCardState.visible 语义)。+ ipc.get.mockResolvedValue({ hook: BASE_HOOK });++ render(<HookConnectionsSection />);+ await screen.findByRole('button', { name: TELEGRAM_CARD });++ expect(screen.queryByRole('button', { name: X_CARD })).toBeNull();+ });++ it('keeps the OAuth deep-link actions visible while X binding is pending', async () => {+ const hook: SlackHookView = {+ ...BASE_HOOK,+ x: {+ enabled: true,+ url: 'wss://x-hook.example.test',+ status: 'connected',+ lastError: null,+ available: true,+ capabilityPending: false,+ binding: {+ provider: 'x',+ state: 'pending',+ attemptId: 'attempt-x1',+ bindingId: null,+ principalId: null,+ principalName: null,+ scopeId: 'bot-x',+ scopeName: 'CindyBot',+ connectUrl:+ 'https://x.com/i/oauth2/authorize?response_type=code&client_id=c1&redirect_uri=r&scope=s&state=st&code_challenge=cc&code_challenge_method=S256',+ expiresAt: Date.now() + 60_000,+ reason: null,+ remediationUrl: null,+ actions: ['open_connect_url', 'copy_connect_url', 'cancel'],+ },+ },+ };+ ipc.get.mockResolvedValue({ hook });++ render(<HookConnectionsSection />);+ await expandChannelCard(X_CARD);++ const openButton = await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.x.openApp',+ });+ expect(+ screen.getByRole('button', { name: 'settings.remoteControl.hook.binding.copyLink' }),+ ).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'settings.remoteControl.hook.x.cancel' }),+ ).toBeTruthy();++ fireEvent.click(openButton);+ await waitFor(() => expect(ipc.openProviderAction).toHaveBeenCalledWith('x', 'connect'));+ });++ it('renders confirmed X actions from the wire action list and never a group action', async () => {+ const hook: SlackHookView = {+ ...BASE_HOOK,+ x: {+ enabled: true,+ url: 'wss://x-hook.example.test',+ status: 'connected',+ lastError: null,+ available: true,+ capabilityPending: false,+ binding: {+ provider: 'x',+ state: 'confirmed',+ attemptId: null,+ bindingId: 'x-binding-1',+ principalId: 'x-user-1',+ principalName: '@dash',+ scopeId: 'bot-x',+ scopeName: 'CindyBot',+ connectUrl: null,+ expiresAt: null,+ reason: null,+ remediationUrl: 'https://x.com/CindyBot',+ actions: ['open_provider', 'revoke'],+ },+ },+ };+ ipc.get.mockResolvedValue({ hook });++ render(<HookConnectionsSection />);+ await expandChannelCard(X_CARD);++ fireEvent.click(+ await screen.findByRole('button', { name: 'settings.remoteControl.hook.x.openBot' }),+ );+ await waitFor(() => expect(ipc.openProviderAction).toHaveBeenCalledWith('x', 'provider'));++ // X 无群概念: server 不会下发 add_to_group, 按钮为数据驱动, 不得凭空渲染。+ expect(+ screen.queryByRole('button', { name: 'settings.remoteControl.hook.x.addToGroup' }),+ ).toBeNull();+ expect(+ screen.getByRole('button', { name: 'settings.remoteControl.hook.x.unlink' }),+ ).toBeTruthy();});it('uses the latest Slack install URL after an async confirmation', async () => {diff --git a/apps/desktop/src/renderer/components/settings/__tests__/HookWorkspacePrefsEditor.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/HookWorkspacePrefsEditor.test.tsxindex 1b727510de..4cdfec073b 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/HookWorkspacePrefsEditor.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/HookWorkspacePrefsEditor.test.tsx@@ -3,7 +3,7 @@import { act, renderHook, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { SlackHookView } from '../../../../shared/hookControlIpc';+import type { ProviderPrefsView, SlackHookView } from '../../../../shared/hookControlIpc';vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -34,6 +34,15 @@ const BASE_HOOK: SlackHookView = {capabilityPending: false,binding: null,},+ x: {+ enabled: false,+ url: '',+ status: 'disabled',+ lastError: null,+ available: false,+ capabilityPending: false,+ binding: null,+ },};const TELEGRAM_CONFIRMED: SlackHookView = {@@ -63,6 +72,33 @@ const TELEGRAM_CONFIRMED: SlackHookView = {},};+const X_CONFIRMED: SlackHookView = {+ ...BASE_HOOK,+ x: {+ enabled: true,+ url: 'wss://x-hook.example.test',+ status: 'connected',+ lastError: null,+ available: true,+ capabilityPending: false,+ binding: {+ provider: 'x',+ state: 'confirmed',+ attemptId: null,+ bindingId: 'x-binding-1',+ principalId: 'x-user-1',+ principalName: '@dash',+ scopeId: 'bot-x',+ scopeName: 'CindyBot',+ connectUrl: null,+ expiresAt: null,+ reason: null,+ remediationUrl: 'https://x.com/CindyBot',+ actions: ['revoke'],+ },+ },+};+const TELEGRAM_REBOUND: SlackHookView = {...TELEGRAM_CONFIRMED,telegram: {@@ -77,7 +113,9 @@ const TELEGRAM_REBOUND: SlackHookView = {};describe('useHookWorkspacePrefs provider isolation', () => {- const getProviderWorkspacePrefs = vi.fn(async () => ({+ const getProviderWorkspacePrefs = vi.fn<+ (provider: 'telegram' | 'x') => Promise<{ prefs: ProviderPrefsView }>+ >(async () => ({prefs: {provider: 'telegram' as const,bindingId: 'binding-1',@@ -258,4 +296,59 @@ describe('useHookWorkspacePrefs provider isolation', () => {expect(result.current.prefsFor('cindy').model).toBe('pushed-model');expect(result.current.pendingWs).toBeNull();});++ it('X 绑定确认后按 provider=x 拉取偏好,跨 provider 或跨 binding 的推送不落进 X', async () => {+ getProviderWorkspacePrefs.mockResolvedValue({+ prefs: { provider: 'x', bindingId: 'x-binding-1', scopeId: null, bound: true, prefs: [] },+ });+ let pushProviderPrefs!: (view: ProviderPrefsView) => void;+ vi.mocked(window.electronAPI.hookControl.onProviderPrefsChanged).mockImplementation(+ (listener) => {+ pushProviderPrefs = listener;+ return () => {};+ },+ );++ const { result } = renderHook(() => useHookWorkspacePrefs(X_CONFIRMED, 'x'));+ await waitFor(() => expect(getProviderWorkspacePrefs).toHaveBeenCalledWith('x'));+ await waitFor(() => expect(result.current.editable).toBe(true));+ expect(getWorkspacePrefs).not.toHaveBeenCalled();++ const entry = (model: string) => [+ { workspace: 'cindy', model, effort: null, agentKind: null, permissionMode: null },+ ];+ // 同 bindingId 但 provider=telegram: 订阅层按 provider 过滤, 不得写进 X 线。+ act(() => {+ pushProviderPrefs({+ provider: 'telegram',+ bindingId: 'x-binding-1',+ scopeId: null,+ bound: true,+ prefs: entry('telegram-model'),+ });+ });+ expect(result.current.prefsFor('cindy').model).toBeNull();+ // provider=x 但 bindingId 不匹配: applyIncoming 按 binding 围栏丢弃。+ act(() => {+ pushProviderPrefs({+ provider: 'x',+ bindingId: 'x-binding-2',+ scopeId: null,+ bound: true,+ prefs: entry('other-binding-model'),+ });+ });+ expect(result.current.prefsFor('cindy').model).toBeNull();+ // 完全匹配的 X 推送正常生效。+ act(() => {+ pushProviderPrefs({+ provider: 'x',+ bindingId: 'x-binding-1',+ scopeId: null,+ bound: true,+ prefs: entry('x-model'),+ });+ });+ expect(result.current.prefsFor('cindy').model).toBe('x-model');+ });});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 1917c2bac0..bab9b44f72 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2557,7 +2557,7 @@"disabledHint": "Turn on the switch, then follow the prompts in Telegram to link your account.","toggleAria": "Toggle the Telegram connection","connect": "Link Telegram",- "openTelegram": "Open Telegram",+ "openApp": "Open Telegram","cancel": "Cancel Linking","retry": "Retry Linking","openBot": "Open Bot",@@ -2579,6 +2579,33 @@"revoked": "Link removed","superseded": "Linked to another device"}+ },+ "x": {+ "description": "Link your X (Twitter) account and dispatch tasks by mentioning the Cindy bot on X.",+ "disabledHint": "Turn on the switch, then follow the prompts to authorize your X account.",+ "toggleAria": "Toggle X connection",+ "connect": "Link X",+ "openApp": "Open X to authorize",+ "cancel": "Cancel linking",+ "retry": "Retry linking",+ "openBot": "View bot on X",+ "unlink": "Unlink X",+ "unlinkConfirmTitle": "Unlink X?",+ "unlinkConfirmDescription": "After unlinking, X can no longer dispatch tasks to this device; local projects and other channels are unaffected.",+ "status": {+ "checking": "Checking server support…",+ "unavailable": "Not yet available on this server",+ "disabled": "Disabled",+ "none": "Not linked",+ "pending": "Open X to authorize your account",+ "awaiting_confirmation": "Confirm the authorization on X",+ "confirmed": "{{user}} linked to {{bot}}",+ "denied": "Authorization denied",+ "expired": "Authorization link expired",+ "failed": "Linking failed",+ "revoked": "Unlinked",+ "superseded": "Linked on another device"+ }}},"summary": {@@ -2597,7 +2624,7 @@"tina": {"chat": {"title": "Chat",- "description": "Plain conversations without any repository; select \"chat\" from Slack or Telegram, one session per conversation lane."+ "description": "Plain conversations without any repository; select \"chat\" from Slack, Telegram, or X, one session per conversation lane."},"prefs": {"agentLabel": "Agent",@@ -2606,6 +2633,7 @@"permissionLabel": "Permission mode","providerSlack": "Slack","providerTelegram": "Telegram",+ "providerX": "X","requireConnected": "Editable once {{provider}} is connected (enable its switch above and wait for the connection).","requireBinding": "Complete {{provider}} account linking first.","serverUnsupported": "Server is too old or not responding; preferences cannot be loaded.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 8e2fbfbffc..693484bce6 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2556,7 +2556,7 @@"disabledHint": "スイッチをオンにして、Telegram 内の案内に従ってアカウント連携を完了してください。","toggleAria": "Telegram 接続を切り替える","connect": "Telegram と連携",- "openTelegram": "Telegram を開く",+ "openApp": "Telegram を開く","cancel": "連携をキャンセル","retry": "連携を再試行","openBot": "Bot を開く",@@ -2578,6 +2578,33 @@"revoked": "連携を解除しました","superseded": "別のデバイスに連携されています"}+ },+ "x": {+ "description": "X (Twitter) アカウントを連携し、X で Cindy bot にメンションしてタスクを依頼できます。",+ "disabledHint": "スイッチをオンにして、案内に従って X アカウントを認証してください。",+ "toggleAria": "X 接続を切り替え",+ "connect": "X を連携",+ "openApp": "X を開いて認証",+ "cancel": "連携をキャンセル",+ "retry": "再連携",+ "openBot": "X で bot を表示",+ "unlink": "X の連携を解除",+ "unlinkConfirmTitle": "X の連携を解除しますか?",+ "unlinkConfirmDescription": "解除すると X からこのデバイスへタスクを送れなくなります。ローカルプロジェクトと他のチャンネルには影響しません。",+ "status": {+ "checking": "サーバーの対応状況を確認中…",+ "unavailable": "このサーバーではまだ利用できません",+ "disabled": "無効",+ "none": "未連携",+ "pending": "X を開いてアカウントを認証してください",+ "awaiting_confirmation": "X で認証を確認してください",+ "confirmed": "{{user}} が {{bot}} と連携済み",+ "denied": "認証が拒否されました",+ "expired": "認証リンクの有効期限切れ",+ "failed": "連携に失敗しました",+ "revoked": "連携が解除されました",+ "superseded": "別のデバイスで連携済み"+ }}},"summary": {@@ -2596,7 +2623,7 @@"tina": {"chat": {"title": "会話",- "description": "リポジトリに紐づかない会話です。Slack または Telegram で「chat」を選ぶと、会話 lane ごとにセッションを利用できます。"+ "description": "リポジトリに紐づかない会話です。Slack・Telegram・X で「chat」を選ぶと、会話 lane ごとにセッションを利用できます。"},"prefs": {"agentLabel": "Agent",@@ -2605,6 +2632,7 @@"permissionLabel": "権限モード","providerSlack": "Slack","providerTelegram": "Telegram",+ "providerX": "X","requireConnected": "{{provider}} 接続後に編集できます(上のスイッチをオンにして接続をお待ちください)。","requireBinding": "先に {{provider}} アカウントの連携を完了してください。","serverUnsupported": "サーバーのバージョンが古いか応答がないため、設定を読み込めません。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex abbb280ba8..d82662a23c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2556,7 +2556,7 @@"disabledHint": "스위치를 켠 뒤 Telegram의 안내에 따라 계정 연결을 완료하세요.","toggleAria": "Telegram 연결 전환","connect": "Telegram 연결",- "openTelegram": "Telegram 열기",+ "openApp": "Telegram 열기","cancel": "연결 취소","retry": "연결 다시 시도","openBot": "봇 열기",@@ -2578,6 +2578,33 @@"revoked": "연결 해제됨","superseded": "다른 기기에 연결됨"}+ },+ "x": {+ "description": "X (Twitter) 계정을 연결하고 X에서 Cindy bot을 멘션해 작업을 요청하세요.",+ "disabledHint": "스위치를 켠 뒤 안내에 따라 X 계정 인증을 완료하세요.",+ "toggleAria": "X 연결 전환",+ "connect": "X 연결",+ "openApp": "X 열어 인증하기",+ "cancel": "연결 취소",+ "retry": "다시 연결",+ "openBot": "X에서 bot 보기",+ "unlink": "X 연결 해제",+ "unlinkConfirmTitle": "X 연결을 해제할까요?",+ "unlinkConfirmDescription": "해제하면 X에서 이 기기로 작업을 보낼 수 없습니다. 로컬 프로젝트와 다른 채널 연결에는 영향이 없습니다.",+ "status": {+ "checking": "서버 지원 확인 중…",+ "unavailable": "이 서버에서는 아직 사용할 수 없습니다",+ "disabled": "비활성화됨",+ "none": "연결되지 않음",+ "pending": "X를 열어 계정 인증을 완료하세요",+ "awaiting_confirmation": "X에서 인증을 확인하세요",+ "confirmed": "{{user}} 님이 {{bot}} 과 연결됨",+ "denied": "인증이 거부되었습니다",+ "expired": "인증 링크가 만료되었습니다",+ "failed": "연결에 실패했습니다",+ "revoked": "연결이 해제되었습니다",+ "superseded": "다른 기기에서 연결됨"+ }}},"summary": {@@ -2596,7 +2623,7 @@"tina": {"chat": {"title": "대화",- "description": "저장소에 연결되지 않은 대화입니다. Slack 또는 Telegram에서 \"chat\"을 선택하면 대화 lane마다 세션을 사용할 수 있습니다."+ "description": "저장소에 연결되지 않은 대화입니다. Slack, Telegram 또는 X에서 \"chat\"을 선택하면 대화 lane마다 세션을 사용할 수 있습니다."},"prefs": {"agentLabel": "Agent",@@ -2605,6 +2632,7 @@"permissionLabel": "권한 모드","providerSlack": "Slack","providerTelegram": "Telegram",+ "providerX": "X","requireConnected": "{{provider}} 연결 후 편집할 수 있습니다(위의 스위치를 켜고 연결을 기다려 주세요).","requireBinding": "먼저 {{provider}} 계정 연결을 완료해 주세요.","serverUnsupported": "서버 버전이 오래되었거나 응답이 없어 설정을 불러올 수 없습니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b46858b7c1..4ec2cd31ce 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2556,7 +2556,7 @@"disabledHint": "打开开关后,按提示在 Telegram 里完成账号关联。","toggleAria": "切换 Telegram 连接","connect": "关联 Telegram",- "openTelegram": "打开 Telegram",+ "openApp": "打开 Telegram","cancel": "取消关联","retry": "重新关联","openBot": "打开 Cindy bot",@@ -2578,6 +2578,33 @@"revoked": "已解除关联","superseded": "已关联到另一台设备"}+ },+ "x": {+ "description": "关联 X (Twitter) 账号,在 X 上 @提及 Cindy bot 即可派发任务。",+ "disabledHint": "打开开关后,按提示完成 X 账号授权。",+ "toggleAria": "切换 X 连接",+ "connect": "关联 X",+ "openApp": "打开 X 完成授权",+ "cancel": "取消关联",+ "retry": "重新关联",+ "openBot": "在 X 上查看 bot",+ "unlink": "解绑 X",+ "unlinkConfirmTitle": "解绑 X?",+ "unlinkConfirmDescription": "解绑后 X 将不能再向这台设备派发任务;本地项目和其它渠道连接不受影响。",+ "status": {+ "checking": "正在检查服务器支持…",+ "unavailable": "当前服务器尚未开放",+ "disabled": "已停用",+ "none": "未绑定",+ "pending": "打开 X 完成账号授权",+ "awaiting_confirmation": "请完成 X 授权确认",+ "confirmed": "{{user}} 已关联 {{bot}}",+ "denied": "已拒绝授权",+ "expired": "授权链接已过期",+ "failed": "关联失败",+ "revoked": "已解除关联",+ "superseded": "已关联到另一台设备"+ }}},"summary": {@@ -2596,7 +2623,7 @@"tina": {"chat": {"title": "对话",- "description": "不落任何仓库的纯对话;在 Slack 或 Telegram 里选择 chat 即可使用,每条对话 lane 独立复用 session。"+ "description": "不落任何仓库的纯对话;在 Slack、Telegram 或 X 里选择 chat 即可使用,每条对话 lane 独立复用 session。"},"prefs": {"agentLabel": "Agent",@@ -2605,6 +2632,7 @@"permissionLabel": "权限模式","providerSlack": "Slack","providerTelegram": "Telegram",+ "providerX": "X","requireConnected": "连接 {{provider}} 后可编辑(先在上方开启对应开关并等待连接成功)。","requireBinding": "先完成 {{provider}} 账号关联后可编辑。","serverUnsupported": "服务器版本过旧或暂时无应答,无法读取偏好。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex ae163a3fee..72a241d5c0 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3167,7 +3167,7 @@ interface ElectronAPI {enabled: boolean,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;setProviderEnabled: (- provider: 'telegram',+ provider: 'telegram' | 'x',enabled: boolean,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;setWorkspaces: (@@ -3184,11 +3184,18 @@ interface ElectronAPI {teamId: string,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;cancelPendingBind: () => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;- providerBindStart: () => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;- providerBindCancel: () => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;- providerBindRevoke: () => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;- openTelegramAction: (- action: import('../shared/hookControlIpc').TelegramOpenAction,+ providerBindStart: (+ provider: 'telegram' | 'x',+ ) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;+ providerBindCancel: (+ provider: 'telegram' | 'x',+ ) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;+ providerBindRevoke: (+ provider: 'telegram' | 'x',+ ) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;+ openProviderAction: (+ provider: 'telegram' | 'x',+ action: import('../shared/hookControlIpc').ProviderOpenAction,) => Promise<{ ok: true }>;getWorkspacePrefs: () => Promise<{prefs: import('../shared/hookControlIpc').HookPrefsView;@@ -3198,10 +3205,11 @@ interface ElectronAPI {patch: import('../shared/hookControlIpc').HookPrefsPatch,teamId?: string | null,) => Promise<{ prefs: import('../shared/hookControlIpc').HookPrefsView }>;- getProviderWorkspacePrefs: () => Promise<{+ getProviderWorkspacePrefs: (provider: 'telegram' | 'x') => Promise<{prefs: import('../shared/hookControlIpc').ProviderPrefsView;}>;setProviderWorkspacePrefs: (+ provider: 'telegram' | 'x',workspace: string,patch: import('../shared/hookControlIpc').HookPrefsPatch,) => Promise<{ prefs: import('../shared/hookControlIpc').ProviderPrefsView }>;@@ -3209,7 +3217,7 @@ interface ElectronAPI {entries: import('../shared/hookControlIpc').HookWorkspaceProviderSourceEntry[];}>;setWorkspaceProviderSource: (payload: {- channel: 'slack' | 'telegram';+ channel: 'slack' | 'telegram' | 'x';teamId: string | null;workspace: string;providerId: string | null;diff --git a/apps/desktop/src/shared/hookControlIpc.ts b/apps/desktop/src/shared/hookControlIpc.tsindex 382b1c83e4..35573ad4af 100644--- a/apps/desktop/src/shared/hookControlIpc.ts+++ b/apps/desktop/src/shared/hookControlIpc.ts@@ -51,17 +51,17 @@ export const HOOK_CONTROL_INVOKE = {CANCEL_PENDING_BIND: 'maker:hook-control:cancel-pending-bind',/** 独立开关一个 Cindy IM provider;不会改动其它 provider。 */SET_PROVIDER_ENABLED: 'maker:hook-control:set-provider-enabled',- /** 发起 Telegram 一次性 deep-link 绑定。 */+ /** 发起 provider-neutral(Telegram / X)一次性绑定。 */PROVIDER_BIND_START: 'maker:hook-control:provider-bind-start',- /** 取消当前 Telegram 绑定尝试。 */+ /** 取消当前 provider-neutral 绑定尝试。 */PROVIDER_BIND_CANCEL: 'maker:hook-control:provider-bind-cancel',- /** 解除当前 Telegram principal 与本设备的绑定。 */+ /** 解除当前 provider-neutral principal 与本设备的绑定。 */PROVIDER_BIND_REVOKE: 'maker:hook-control:provider-bind-revoke',- /** 在本机安全打开当前 Telegram 绑定链接 / bot / 加群链接。 */- TELEGRAM_OPEN_ACTION: 'maker:hook-control:telegram-open-action',- /** 读取 Telegram provider 独立的 workspace 偏好。 */+ /** 在本机安全打开 provider 的绑定链接 / bot 主页 / 加群链接。 */+ PROVIDER_OPEN_ACTION: 'maker:hook-control:provider-open-action',+ /** 读取 provider-neutral(Telegram / X)独立的 workspace 偏好。 */PROVIDER_PREFS_GET: 'maker:hook-control:provider-prefs-get',- /** 更新 Telegram provider 独立的 workspace 偏好。 */+ /** 更新 provider-neutral(Telegram / X)独立的 workspace 偏好。 */PROVIDER_PREFS_SET: 'maker:hook-control:provider-prefs-set',/** 读取工作目录模型来源偏好(纯本地, 不经 WS; 见 workspaceProviderSourceStore)。 */WORKSPACE_PROVIDER_SOURCE_GET: 'maker:hook-control:workspace-provider-source-get',@@ -74,7 +74,7 @@ export const HOOK_CONTROL_EVENT = {STATUS_CHANGED: 'maker:hook-control:status-changed',/** 目录偏好快照推送(prefs.state; 含 Slack /model 卡改动的实时同步)。 */PREFS_CHANGED: 'maker:hook-control:prefs-changed',- /** provider-neutral 偏好快照推送(本版由 Telegram 消费)。 */+ /** provider-neutral 偏好快照推送(Telegram / X 消费)。 */PROVIDER_PREFS_CHANGED: 'maker:hook-control:provider-prefs-changed',/** 目录模型来源偏好全量推送(本地写入后广播全窗口, 多窗口设置页同步)。 */WORKSPACE_PROVIDER_SOURCE_CHANGED: 'maker:hook-control:workspace-provider-source-changed',@@ -84,8 +84,14 @@ export const HOOK_CONTROL_EVENT = {* renderer 用海量唯一 teamId 无限追加撑爆本地文件)。 */export const HOOK_WORKSPACE_PROVIDER_SOURCE_MAX_ENTRIES = 256;-/** Cindy relay 当前支持的客户端 provider。 */-export type HookProvider = 'slack' | 'telegram';+/**+ * Cindy relay 当前支持的客户端 provider。协议包 HOOK_PROVIDERS 的手抄副本+ * (shared 层刻意不引协议包)——协议 bump 新增 provider 时必须手动同步。+ */+export type HookProvider = 'slack' | 'telegram' | 'x';++/** provider-neutral 状态机(非 slack legacy 线)覆盖的 provider。 */+export type NeutralHookProvider = Exclude<HookProvider, 'slack'>;/** provider-neutral 绑定状态(与 cindy-protocol v1 严格同形)。 */export type ProviderBindingState =@@ -116,10 +122,10 @@ export interface ProviderBindingView {actions: string[];}-/** Telegram provider 的独立设置与绑定视图。 */-export interface TelegramHookView {+/** provider-neutral(Telegram / X)的独立设置与绑定视图。 */+export interface ProviderHookView {enabled: boolean;- /** Telegram 平级 hook 服务的运行期端点;空值表示当前环境尚未部署。 */+ /** 该 provider 平级 hook 服务的运行期端点;空值表示当前环境尚未部署。 */url: string;status: HookConnectionStatus;lastError: string | null;@@ -130,7 +136,14 @@ export interface TelegramHookView {binding: ProviderBindingView | null;}-export type TelegramOpenAction = 'connect' | 'provider' | 'add-to-group';+/** @deprecated 兼容别名;新代码用 ProviderHookView。 */+export type TelegramHookView = ProviderHookView;++/** 绑定卡可打开的链接类别;'add-to-group' 仅 Telegram 使用。 */+export type ProviderOpenAction = 'connect' | 'provider' | 'add-to-group';++/** @deprecated 兼容别名;新代码用 ProviderOpenAction。 */+export type TelegramOpenAction = ProviderOpenAction;/*** Slack 账号绑定状态(与 hook-protocol 的 BindUpdateState 一致, 本文件为@@ -267,7 +280,9 @@ export interface SlackHookView {/** server 是否宣告 multi-team 能力(welcome.features; renderer 据此显示「添加」入口)。 */serverMultiTeam: boolean;/** 平级 Telegram hook 服务状态;Slack 旧字段保持原形。 */- telegram: TelegramHookView;+ telegram: ProviderHookView;+ /** 平级 X (Twitter) hook 服务状态。 */+ x: ProviderHookView;}/** 工作区别名的合法格式(与 hook server 侧约定一致)。 */@@ -295,8 +310,8 @@ export const HOOK_CHAT_WORKSPACE_ALIAS = 'chat';* model 组合后经 effectiveSourceIdForModel 收窄派发。*/export interface HookWorkspaceProviderSourceEntry {- channel: 'slack' | 'telegram';- /** Slack multi-team 归属; Telegram / 单绑定为 null。 */+ channel: 'slack' | 'telegram' | 'x';+ /** Slack multi-team 归属; Telegram / X / 单绑定为 null。 */teamId: string | null;workspace: string;providerId: string;diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.tsindex d33ef54613..f9eee855c7 100644--- a/apps/desktop/src/shared/sessionSource.ts+++ b/apps/desktop/src/shared/sessionSource.ts@@ -3,6 +3,7 @@ export const SESSION_SOURCES = ['feishu','slack','telegram',+ 'x','discord','wechat','dingtalk',@@ -17,6 +18,7 @@ export type SessionSource = (typeof SESSION_SOURCES)[number];// desktop sidebar 展示的会话 source 白名单。// slack: IM 渠道自动建的会话——用户在 Slack 发消息后 desktop 同步可见。// telegram: 共享 Cindy Telegram bot 派发并在本机执行的会话。+// x: 共享 Cindy X (Twitter) bot 派发并在本机执行的会话。// discord: IM 渠道自动建的会话——用户在 Discord 发消息后 desktop 同步可见。// dingtalk: 钉钉机器人私聊与群 lane 自动建的会话。// feishu: IM 渠道自动建的会话——落侧边栏「对话」分组(workspaceKind='dialogue')。@@ -31,6 +33,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = ['feishu','slack','telegram',+ 'x','discord','wechat','dingtalk',@@ -44,6 +47,7 @@ export function normalizeSessionSource(source: unknown): SessionSource {return source === 'feishu' ||source === 'slack' ||source === 'telegram' ||+ source === 'x' ||source === 'discord' ||source === 'wechat' ||source === 'dingtalk' ||diff --git a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts b/apps/desktop/src/test/vitest/clientEndpointsFixture.tsindex d3ca56e6f1..2a857fe768 100644--- a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts+++ b/apps/desktop/src/test/vitest/clientEndpointsFixture.ts@@ -31,6 +31,7 @@ export const TEST_CLIENT_ENDPOINTS: ClientEndpointMap = {ossApiBaseUrl: 'https://oss.test.invalid',heartbeatUrl: 'https://heartbeat.test.invalid',telegramHookWsUrl: 'wss://telegram-hook.test.invalid',+ xHookWsUrl: 'wss://x-hook.test.invalid',slackHookWsUrl: 'wss://slack-hook.test.invalid',websiteUrl: 'https://website.test.invalid',modelAccessApiBaseUrl: 'https://model-access.test.invalid',diff --git a/apps/mobile/src/__tests__/hookSourceRendering.test.ts b/apps/mobile/src/__tests__/hookSourceRendering.test.tsindex 686bb685f4..6af337535c 100644--- a/apps/mobile/src/__tests__/hookSourceRendering.test.ts+++ b/apps/mobile/src/__tests__/hookSourceRendering.test.ts@@ -10,7 +10,9 @@ describe('mobile shared Cindy source card wiring', () => {expect(source).toContain("item.message.kind === 'user' && item.message.hookSource");expect(source).toContain("kind: 'system' as const, align: 'agent' as const");expect(source).toContain('testID="message.hookSource"');- expect(source).toContain("hookSource.im === 'telegram' ? 'Telegram' : 'Slack'");+ expect(source).toContain(+ "hookSource.im === 'telegram' ? 'Telegram' : hookSource.im === 'x' ? 'X' : 'Slack'",+ );expect(source).toContain('{hookSource.channelName}');expect(source).toContain('(isUser || hookSource !== undefined)');expect(source).toContain("(item.message.kind === 'user' || hookSource !== undefined)");diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex c18b655e65..3f66ed342b 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1790,7 +1790,7 @@ function MessageBubble({<View style={styles.hookSourceHeader} testID="message.hookSource"><Send color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.regular} /><Text numberOfLines={1} style={styles.hookSourceTitle}>- {`Cindy · ${hookSource.im === 'telegram' ? 'Telegram' : 'Slack'}`}+ {`Cindy · ${hookSource.im === 'telegram' ? 'Telegram' : hookSource.im === 'x' ? 'X' : 'Slack'}`}</Text>{hookSource.channelName ? (<Text numberOfLines={1} style={styles.hookSourceChannel}>diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 08fee44241..c93b01fb5f 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -108,7 +108,7 @@ export interface NormalizedAutomationOrigin {}export interface NormalizedHookSource {- im: 'slack' | 'telegram';+ im: 'slack' | 'telegram' | 'x';channelName?: string;userText: string;threadContext?: Array<{ author: string; text: string; isBot?: boolean }>;@@ -748,7 +748,9 @@ function readAutomationOrigin(message: RemoteMessage): Pick<NormalizedRemoteMess/** Fail closed on unknown providers and bound all server-controlled display fields. */function readHookSource(message: RemoteMessage, fallbackBody: string): NormalizedHookSource | undefined {const source = readRecord(message.agentMeta?.hookSource);- if (!source || (source.im !== 'slack' && source.im !== 'telegram')) return undefined;+ if (!source || (source.im !== 'slack' && source.im !== 'telegram' && source.im !== 'x')) {+ return undefined;+ }const userText = (typeof source.userText === 'string' ? source.userText : fallbackBody).slice(0, 20_000);diff --git a/packages/lizi-mcps/src/__tests__/feishuBotChannelRouting.test.ts b/packages/lizi-mcps/src/__tests__/feishuBotChannelRouting.test.tsindex 5e3c88692a..f9a84d28f6 100644--- a/packages/lizi-mcps/src/__tests__/feishuBotChannelRouting.test.ts+++ b/packages/lizi-mcps/src/__tests__/feishuBotChannelRouting.test.ts@@ -16,6 +16,7 @@ import {createFeishuBotMcpServer,SLACK_HOOK_SESSION_CHANNEL_NOTE,TELEGRAM_HOOK_SESSION_CHANNEL_NOTE,+ X_HOOK_SESSION_CHANNEL_NOTE,type FeishuBotMcpDeps,} from '../cindy_feishuBotMcpServer';@@ -74,6 +75,7 @@ describe('cindy_feishu_bot channel routing note', () => {it.each([['slack-hook', SLACK_HOOK_SESSION_CHANNEL_NOTE],['telegram', TELEGRAM_HOOK_SESSION_CHANNEL_NOTE],+ ['x', X_HOOK_SESSION_CHANNEL_NOTE],] as const)('%s description === base description + fixed note, for every tool',async (source, note) => {@@ -103,6 +105,7 @@ describe('cindy_feishu_bot channel routing note', () => {for (const description of feishuDescs.values()) {expect(description).not.toContain(SLACK_HOOK_SESSION_CHANNEL_NOTE.trim());expect(description).not.toContain(TELEGRAM_HOOK_SESSION_CHANNEL_NOTE.trim());+ expect(description).not.toContain(X_HOOK_SESSION_CHANNEL_NOTE.trim());}} finally {await feishu.cleanup();diff --git a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.tsindex 18fd42591e..648cf590c8 100644--- a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts@@ -52,9 +52,14 @@ export const SLACK_HOOK_SESSION_CHANNEL_NOTE =export const TELEGRAM_HOOK_SESSION_CHANNEL_NOTE ='\n\n⚠️ 当前是 Telegram 会话:文字回复直接输出即可(会自动回贴到当前 Telegram 对话或回复链,无需工具);把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 ``,系统自动作为 Telegram 附件发回,不要用本工具;仅当用户明确说「发飞书或 Lark / 通过飞书或 Lark 通知我」时才走该 IM 通道。';+export const X_HOOK_SESSION_CHANNEL_NOTE =+ '\n\n⚠️ 当前是 X (Twitter) 会话:文字回复直接输出即可(会自动作为单条公开回帖发布在 X 上,无需工具);回帖为纯文本呈现,保持简短聚焦;把文件发给用户是在最终回复文本里写 `[文件名](xdt-file:///绝对路径)`(文件须位于当前工作目录内),图片直接引用其地址 ``;仅当用户明确说「发飞书 / 飞书通知我」时才走飞书通道。';+const NOTE_BY_SOURCE: Record<string, string> = {'slack-hook': SLACK_HOOK_SESSION_CHANNEL_NOTE,telegram: TELEGRAM_HOOK_SESSION_CHANNEL_NOTE,+ // 键与 hook-control/session-runner.ts 的 vendorOptions.source 是一对隐式契约+ x: X_HOOK_SESSION_CHANNEL_NOTE,};/** 按会话来源产出工具描述——无对应 note 的来源原样返回 D,保证字节级不变。 */diff --git a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts b/packages/maker-shared/src/__tests__/clientEndpoints.test.tsindex 6492175349..60dce8d4ff 100644--- a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts+++ b/packages/maker-shared/src/__tests__/clientEndpoints.test.ts@@ -17,6 +17,7 @@ const VALID_MANIFEST = {ossApiBaseUrl: 'https://oss.example.com',heartbeatUrl: 'https://heartbeat.example.com',telegramHookWsUrl: 'wss://telegram-hook.example.com',+ xHookWsUrl: 'wss://x-hook.example.com',slackHookWsUrl: 'wss://slack-hook.example.com',websiteUrl: 'https://www.example.com',modelAccessApiBaseUrl: 'https://model-access.example.com',diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.tsindex 99e81a47c7..bd65740044 100644--- a/packages/maker-shared/src/clientEndpoints.ts+++ b/packages/maker-shared/src/clientEndpoints.ts@@ -99,6 +99,10 @@ export const CLIENT_ENDPOINT_KEYS = [// Telegram hook is deployed independently from Slack; empty means the// current environment has not rolled out Telegram yet.'telegramHookWsUrl',+ // X (Twitter) hook, same deployment model as Telegram; empty (or a manifest+ // that omits the key entirely) means X has not rolled out yet — the Settings+ // card stays hidden, which is the intended gradual-rollout switch.+ 'xHookWsUrl','slackHookWsUrl','websiteUrl',// model-access-server(登录后自动下发 LLM 网关凭据)的 API 基址。@@ -165,6 +169,7 @@ const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {ossApiBaseUrl: ['https:'],heartbeatUrl: ['https:'],telegramHookWsUrl: ['wss:'],+ xHookWsUrl: ['wss:'],slackHookWsUrl: ['wss:'],websiteUrl: ['https:'],modelAccessApiBaseUrl: ['https:'],