Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bots): 将官方 X 提问绑定给伙伴 (#6493)
Chris Zhangc216f8d45e14
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.tsindex e539fcb10e..927e6b3522 100644--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts@@ -5721,3 +5721,46 @@ describe('渠道 /stop 走统一明确停止', () => {await deactivated;});});++// Official X companion routing: an authenticated dispatch uses only the host's+// public lane, never the supplied private session. Revocation also stops queued+// work. Ordinary workspace tests have no companion binding (unit).+describe('official X companion assignment', () => {+ it('routes to the companion lane and rejects queued work after unbinding', async () => {+ const config = { ...CONFIG, id: 'account:x', workspaces: {}, companionBotId: 'bot-one' as string | null };+ const fake = fakeRunner();+ const out = collector();+ const resolver = vi.fn(async () => ({ sessionId: 'public-lane', workingDir: '/companion/home' }));+ const dispatcher = createHookDispatcher({ getConnection: () => config, bindings: memoryBindings(),+ runner: fake.runner, resolveCompanionTarget: resolver, log: noopLog });+ const payload = dispatch({ externalKey: 'x:thread:principal', source: { im: 'x' }, sessionId: 'private-chat' });+ dispatcher.handleDispatch(config.id, payload, out.send);+ await tick(30);+ expect(fake.calls).toHaveLength(1);+ expect(fake.calls[0]).toMatchObject({ sessionId: 'public-lane', companionBotId: 'bot-one', isNew: false });+ expect(fake.calls[0].isDirAuthorized?.('/companion/home')).toBe(true);+ expect(fake.calls[0].isDirAuthorized?.('/another/private/path')).toBe(false);+ dispatcher.handleDispatch(config.id, { ...payload, requestId: 'req-2' }, out.send);+ await tick(30);+ config.companionBotId = null;+ expect(fake.calls[0].isDirAuthorized?.('/companion/home')).toBe(false);+ fake.finish();+ await tick(60);+ expect(fake.calls).toHaveLength(1);+ expect(out.ofType('turn.end').some(frame => frame.payload.requestId === 'req-2' && frame.payload.status === 'error')).toBe(true);+ dispatcher.dispose();+ });+ it('does not fall back to ordinary tasks when the assigned companion is unavailable', async () => {+ const fake = fakeRunner();+ const out = collector();+ const dispatcher = createHookDispatcher({+ getConnection: () => ({ ...CONFIG, companionBotId: 'missing-bot' }), bindings: memoryBindings(),+ runner: fake.runner, resolveCompanionTarget: async () => { throw new Error('Companion unavailable'); }, log: noopLog,+ });+ dispatcher.handleDispatch('account:x', dispatch({ source: { im: 'x' }, externalKey: 'x:thread:principal' }), out.send);+ await tick(30);+ expect(fake.calls).toHaveLength(0);+ expect(out.last('task.ack')?.payload.result).toBe('rejected');+ dispatcher.dispose();+ });+});diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex a92d3f2422..97a44a319b 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -30,7 +30,9 @@ const h = vi.hoisted(() => {const calls: string[] = [];return {calls,+ bridgeHandle: vi.fn(async (_args: unknown) => undefined),followPolicy: vi.fn(),+ prepareBot: vi.fn(async (): Promise<string | null> => null),syncDefaultRoute: vi.fn(async () => false),writeDefaultRecord: vi.fn(async (_id: string, _fingerprint: string) => undefined),acquirePendingAgentSwitch: vi.fn(async (_id: string, _sync: () => Promise<boolean>): Promise<() => void> => () => {}),@@ -153,6 +155,7 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({vi.mock('../../maker-ipc/register.js', () => ({acquirePendingAgentSwitchForImSend: h.acquirePendingAgentSwitch,beginTurnChangeSetAtDispatch: h.beginTurnChangeSetAtDispatch,+ prepareBotSessionForImSend: h.prepareBot,prepareUnhealthySessionForSend: vi.fn(async () => undefined),wireSessionToIpc: vi.fn(),isSessionInTurn: () => false,@@ -189,9 +192,21 @@ vi.mock('../../localDb/ipc/sessions.js', () => ({touchUserSendInDb: h.touchUserSendInDb,}));vi.mock('../../maker-host/session-provider-store.js', () => ({+ getSessionProvider: () => null,setSessionProvider: h.setSessionProvider,hydrateSessionProvider: h.hydrateSessionProvider,}));+vi.mock('../../maker-host/anthropic-responses-bridge-host.js', () => ({+ getResponsesBridgeHandler: () => ({ handle: h.bridgeHandle }),+ getPiNativeSubscriptionHandler: vi.fn(),+}));+vi.mock('../../maker-host/claude-fast-mode-log.js', () => ({+ createClaudeFastModeRequestTransform: () => () => null,+ createClaudeFastModeResponseObserver: () => () => undefined,+}));+vi.mock('../../maker-host/runtime-configs.js', () => ({+ claudeUpstreamEndpoint: () => 'http://127.0.0.1:1',+}));vi.mock('../../maker-host/session-storage.js', () => ({desktopSessionStorage: { create: h.createSessionRow },}));@@ -318,6 +333,7 @@ function makeFakeSession(id: string) {const permission = makePermissionModeFake();return {id,+ ...({ instanceId: `instance-${id}` } as { instanceId?: string }),workDir: 'D:/repo',get permissionModeState() {return permission.permissionModeState;@@ -368,6 +384,7 @@ const fakeMaker = {getSessionMeta: vi.fn(async () => ({workDir: 'D:/repo',model: 'meta-model',+ ...({ effort: 'high', fastMode: true } as { effort?: Effort; fastMode?: boolean }),sdkSessionId: 'sdk-1',agentKind: 'claude-code' as const,permissionMode: undefined as 'ask' | 'bypassPermissions' | undefined,@@ -402,6 +419,8 @@ import { getResolvedMainLocale } from '../../i18n.js';import { buildUiLanguageErrorNote } from '../../maker-ipc/uiLanguageErrorNote.js';import { resolveSafe as resolveXdtImage } from '../../imageCacheStore.js';import { isHeadlessGhostSetupTurn } from '../../mcp-integrations/ghostSetupInteractionSurface.js';+import { createModelRoutingTransform, setClaudeProxySessionIdResolver } from '../../maker-host/anthropic-compat-proxy-host.js';+import { clearAllSessionRuntimeAxes, setSessionEffort, setSessionFastMode } from '../../maker-host/session-effort-store.js';const log = { info: vi.fn(), warn: vi.fn() };@@ -461,6 +480,8 @@ function baseReq(beforeEach(() => {vi.clearAllMocks();+ clearAllSessionRuntimeAxes();+ setClaudeProxySessionIdResolver(() => null);h.acquirePendingAgentSwitch.mockReset();h.acquirePendingAgentSwitch.mockResolvedValue(() => {});h.calls.length = 0;@@ -493,6 +514,55 @@ beforeEach(() => {});describe('hook task model selection on next send', () => {+ // Regression #6493: createSession options do not hydrate Claude's bridge.+ // Exercise the production runner + routing transform at provider startup,+ // with no profile switch, both after restart and when clearing old axes (unit).+ it.each([+ { model: 'chatgpt/gpt-5.4', effort: 'high' as const, fastMode: true, stale: false },+ { model: 'xai/grok-4.6', effort: undefined, fastMode: false, stale: true },+ ])('hydrates X companion bridge preferences for $model', async ({ model, effort, fastMode, stale }) => {+ const req = baseReq({ isNew: false, companionBotId: 'bot-one', source: { im: 'x' } });+ if (stale) {+ setSessionEffort(req.sessionId, 'high');+ setSessionFastMode(req.sessionId, true);+ }+ const meta = await fakeMaker.getSessionMeta();+ fakeMaker.getSessionMeta.mockResolvedValueOnce({ ...meta, model, effort, fastMode });+ setClaudeProxySessionIdResolver(() => req.sessionId);+ fakeMaker.createSession.mockImplementationOnce(async (opts) => {+ const parsedBody = { model, messages: [{ role: 'user', content: 'hello' }] };+ const route = await createModelRoutingTransform()(parsedBody, {+ reqId: 1, method: 'POST', url: '/v1/messages',+ headers: { 'x-claude-code-session-id': 'sdk-fixture' },+ });+ expect(route?.localHandler).toBeTypeOf('function');+ await route!.localHandler!({ parsedBody } as Parameters<NonNullable<NonNullable<typeof route>['localHandler']>>[0]);+ expect(h.bridgeHandle).toHaveBeenCalledWith(expect.objectContaining({+ prefs: { reasoningEffort: effort, fast: fastMode },+ }));+ return makeFakeSession(opts.id ?? req.sessionId);+ });+ expect((await createMakerHookSessionRunner({ log }).run(req)).status).toBe('ok');+ expect(h.bridgeHandle).toHaveBeenCalledOnce();+ });++ // A companion lane inherits its current profile route and owner tool scope;+ // a paused profile must never reach the provider (unit, production runner).+ it('preserves X companion model options and blocks unavailable companions', async () => {+ const runner = createMakerHookSessionRunner({ log });+ const req = baseReq({ isNew: false, companionBotId: 'bot-one', source: { im: 'x' } });+ expect((await runner.run(req)).status).toBe('ok');+ expect(h.prepareBot).toHaveBeenCalledWith(req.sessionId);+ expect(fakeMaker.createSession).toHaveBeenCalledWith(expect.objectContaining({+ model: 'meta-model', effort: 'high', fastMode: true,+ vendorOptions: expect.objectContaining({ source: 'x' }),+ }));+ fakeMaker.createSession.mockClear();+ h.prepareBot.mockResolvedValueOnce('Companion paused');+ expect(await runner.run(req)).toMatchObject({ status: 'error', errorMessage: 'Companion paused' });+ expect(fakeMaker.createSession).not.toHaveBeenCalled();+ });+it('runs default following under the send lock before reading metadata', async () => {const readMeta = fakeMaker.getSessionMeta.getMockImplementation()!;h.acquirePendingAgentSwitch.mockImplementationOnce(async (id, sync) => {diff --git a/apps/desktop/src/main/hook-control/__tests__/store.test.ts b/apps/desktop/src/main/hook-control/__tests__/store.test.tsindex 6a1fd28cd6..55d0e08955 100644--- a/apps/desktop/src/main/hook-control/__tests__/store.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/store.test.ts@@ -51,6 +51,7 @@ describe('默认态与持久化', () => {enabled: false,telegramEnabled: false,xEnabled: false,+ xCompanionBotId: null,urlOverride: null,workspaces: {},bindingsCache: [],@@ -174,6 +175,7 @@ describe('旧多连接文件迁移', () => {enabled: false,telegramEnabled: false,xEnabled: false,+ xCompanionBotId: null,urlOverride: null,workspaces: {},bindingsCache: [],@@ -443,3 +445,19 @@ describe('provider 与 Cindy 账号隔离', () => {});});});++// New behavior: explicit X assignment survives restart, is isolated per account,+// and removal restores ordinary tasks. Existing workspace tests do not cover it (unit).+it('persists X companion assignment only for the current account', () => {+ let owner = 'owner-one';+ const store = makeStore(undefined, () => owner);+ store.setXCompanionBotId('bot-one');+ expect(makeStore(undefined, () => owner).get().xCompanionBotId).toBe('bot-one');+ owner = 'owner-two';+ expect(store.get().xCompanionBotId).toBeNull();+ store.setXCompanionBotId('bot-two');+ owner = 'owner-one';+ expect(store.get().xCompanionBotId).toBe('bot-one');+ store.setXCompanionBotId(null);+ expect(makeStore(undefined, () => owner).get().xCompanionBotId).toBeNull();+});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 b5b47a5b5e..50ca3b8549 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@@ -121,6 +121,10 @@ function memoryStore(initial: Partial<SlackHookConfigState> & { url: string }):: { ...state, telegramBindingCache: entry ? { ...entry } : null };return state;},+ setXCompanionBotId(botId) {+ state = { ...state, xCompanionBotId: botId };+ return state;+ },setProviderDefaultWorkspace(provider: 'telegram' | 'x', alias: string | null) {state =provider === 'x'diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex 40feed4cf4..5818069a1f 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -179,6 +179,8 @@ export interface HookContinuationWatchRequest {}export interface HookRunRequest {+ /** Host-resolved companion channel lane; never accepted from the wire. */+ companionBotId?: string;/** Untruncated user body for persistence; source.userText is only a bounded display preview. */userText?: string;/** Local display snapshot; not part of the server wire protocol. */@@ -299,6 +301,10 @@ export type PrepareWorktreeResult =| { ok: false; message: string };export interface HookDispatcherDeps {+ resolveCompanionTarget?: (botId: string, externalKey: string) => Promise<{+ sessionId: string;+ workingDir: string;+ }>;getConnection: (id: string) => HookConnectionConfig | null;bindings: HookBindingStore;/** Durable terminal request state, injected by the Electron owner boundary. */@@ -716,6 +722,10 @@ function telegramLegacyLifecycle(}export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {+ // Only lanes resolved by the host receive companion workspace access. A shared Home+ // path is not permission to take over the companion's private canonical task.+ const companionTargets = new Map<string, { connectionId: string; botId: string; workingDir: string }>();+const {getConnection,bindings,@@ -1599,7 +1609,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {if (running.has(sessionId) || activeContinuations.has(sessionId)) return;if (!supportsReopen(entry.connectionId)) return;// 目录授权按现场重算(与 execute 同一道收口): 等待期间映射可能已被改删。- if (!dirStillAllowed(entry.connectionId, entry.workingDir)) {+ if (!dirStillAllowed(entry.connectionId, entry.workingDir, sessionId)) {log.info(`hook continuation skipped: the session directory is no longer authorized (reopenOf=${entry.requestId})`,);@@ -1671,7 +1681,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {workingDir: entry.workingDir,...(entry.source ? { source: entry.source } : {}),laneKind: deriveLaneKind(entry.externalKey),- isDirAuthorized: (dir) => dirStillAllowed(entry.connectionId, dir),+ isDirAuthorized: (dir) => dirStillAllowed(entry.connectionId, dir, sessionId),onClaim: () => {if (revoked || !isCurrentGeneration(entry.accountGeneration)) return;const send = sendFns.get(entry.connectionId);@@ -1911,7 +1921,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {* 而空串过 isPathWithin 会 resolve 成 cwd, 那就成了一条假放行。*/const guardDir = task.run.workingDir || null;- if (guardDir !== null && !dirStillAllowed(task.connectionId, guardDir)) {+ if (guardDir !== null && !dirStillAllowed(task.connectionId, guardDir, task.run.sessionId)) {// 路径不进日志(规则: 用集中 PII helper, 而 dispatcher 是不碰 Electron 的// 纯逻辑模块, 拿不到它)—— requestId 足够定位。log.info(@@ -1937,7 +1947,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// This is not another turn.end: the original result remains final.// Only the negotiated Telegram executor can send outside that turn.if (!isCurrentGeneration(task.accountGeneration)- || !dirStillAllowed(task.connectionId, task.run.workingDir)+ || !dirStillAllowed(task.connectionId, task.run.workingDir, task.run.sessionId)|| !serverFeatures.get(task.connectionId)?.includes(HOOK_FEATURE_MESSAGE_OPS)) {return Promise.resolve(false);}@@ -1975,7 +1985,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {: {}),// runner 建/取到 session 后, 拿它真正要跑的那个目录回来问一次 ——// 那个目录可能与这里校验过的不是同一个(见 isDirAuthorized 的说明)。- isDirAuthorized: (dir) => dirStillAllowed(task.connectionId, dir),+ isDirAuthorized: (dir) => dirStillAllowed(task.connectionId, dir, task.run.sessionId),});} catch (err) {runnerThrew = true;@@ -2152,11 +2162,16 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {* 它", 所以必须在这里重新查一次当前映射, 否则排着的消息会在已撤权的目录里* 执行(PR #733 review 指出)。连接本身没了或被停用, 同样按撤权处理。*/- function dirStillAllowed(connectionId: string, dir: string): boolean {+ function dirStillAllowed(connectionId: string, dir: string, sessionId?: string): boolean {const config = getConnection(connectionId);// 连接被停用 = 用户已经切断了这条远端通道。handleDispatch 入口就这么判,// 排队中的任务同样不能因为"目录还在映射里"就照跑(PR #733 review 指出)。if (!config || !config.enabled) return false;+ const companion = sessionId ? companionTargets.get(sessionId) : undefined;+ if (config.companionBotId || companion) {+ return !!companion && companion.connectionId === connectionId+ && companion.botId === config.companionBotId && path.resolve(companion.workingDir) === path.resolve(dir);+ }if (Object.values(config.workspaces).some((root) => isPathWithin(root, dir))) return true;return dialogue !== undefined && (dialogue.rootDirs?.() ?? [dialogue.rootDir()]).some((root) => isPathWithin(root, dir));@@ -2243,6 +2258,23 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {connectionName: config.name,externalKey: payload.externalKey,};+ if (config.companionBotId) {+ if (!connectionId.endsWith(':x') || payload.source?.im !== 'x' || !deps.resolveCompanionTarget) {+ return { reject: 'disabled' };+ }+ const target = await deps.resolveCompanionTarget(config.companionBotId, payload.externalKey);+ if (!isCurrentGeneration(generation)+ || getConnection(connectionId)?.companionBotId !== config.companionBotId) {+ return { reject: 'disabled' };+ }+ companionTargets.set(target.sessionId, { connectionId, botId: config.companionBotId, workingDir: target.workingDir });+ bindings.set(connectionId, payload.externalKey, target.sessionId);+ return { run: {+ ...target, companionBotId: config.companionBotId, isNew: false,+ agentKind: null, model: null, effort: null, permissionMode: null,+ title: null, prompt: payload.prompt, attachments: payload.attachments, origin,+ } };+ }/*** 同上, 但每次都重读连接配置 —— 撤权判定必须用**此刻**的映射: `config` 是* 消息进来那一刻的快照, 而下面要 await `runner.inspect()`。用快照判定的话,@@ -2993,6 +3025,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// 不在这里清的话, 每次切账号都永久留下一条 sessionId + 完整工作目录路径// (PR #733 review 指出)。这些会话属于上一个账号, 新账号下本就不该免检。awaitingPersist.clear();+ companionTargets.clear();staleTakeoverReplacements.clear();latestPromptBySession.clear();keyChains.clear();@@ -3026,12 +3059,12 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// (PR #733 review 指出)。if (info === null) {const pendingDir = awaitingPersist.get(sessionId);- return pendingDir !== undefined && dirStillAllowed(connectionId, pendingDir);+ return pendingDir !== undefined && dirStillAllowed(connectionId, pendingDir, sessionId);}return (info.usable === true &&info.workingDir !== null &&- dirStillAllowed(connectionId, info.workingDir)+ dirStillAllowed(connectionId, info.workingDir, sessionId));};let bindingNamespace = connectionId;@@ -3140,7 +3173,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {isCurrentGeneration(admittedGeneration) &&info?.usable === true &&info.workingDir !== null &&- dirStillAllowed(connectionId, info.workingDir)+ dirStillAllowed(connectionId, info.workingDir, previous)) {await archiveSessionRow(previous).catch((err) => {log.warn(diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex c1ca5b0ad9..bf7b5bfe54 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -10,6 +10,9 @@* 即连即断。没有密钥概念, 旧 safeStorage secret 文件由 store 迁移时清理。*/+import { requireXCompanion, resolveXCompanionTarget } from './xCompanion.js';+import { captureChannelAccount } from '../im/shared/openChannelSession.js';+import path from 'node:path';import fs from 'node:fs';import os from 'node:os';@@ -524,6 +527,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManagername: meta.name,url: meta.url,enabled: meta.enabled,+ ...(provider === 'x' ? { companionBotId: config.xCompanionBotId ?? null } : {}),workspaces: config.workspaces,createdAt: 0,};@@ -539,6 +543,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager}),mediaStore,runner: createMakerHookSessionRunner({ log }),+ resolveCompanionTarget: resolveXCompanionTarget,buildContextPrefix: buildGroupContextPrefix,// 新建 hook 会话默认预建独立 worktree(并发隔离); deps 组装与// maker-ipc/register.ts 的 use_worktree 分支同款。失败由 dispatcher@@ -929,6 +934,24 @@ export function registerHookControlIpc(): void {},);+ registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.SET_X_COMPANION, async (_e, payload) => {+ requireHookControl();+ const assertAccount = captureChannelAccount();+ const { store: s, manager: m } = ensureInstances();+ const p = requireObject(payload);+ const botId = requireNullableString(p.botId, 'botId');+ const expectedBotId = requireNullableString(p.expectedBotId, 'expectedBotId');+ if (botId !== null) await requireXCompanion(botId);+ assertAccount();+ if ((s.get().xCompanionBotId ?? null) !== expectedBotId) {+ throwIpcError('PRECONDITION_FAILED', 'X companion assignment changed');+ }+ translateValidation(() => s.setXCompanionBotId(botId));+ const hook = m.snapshot();+ broadcastStatus(hook);+ return { hook };+ });+// 发起 Slack 账号绑定(SIWS OIDC): 经已连接的 WS 发 bind.start(无参); server// 回 bind.update(pending, authorizeUrl), main 打开系统浏览器并广播状态。registerTrustedHookControlHandler(HOOK_CONTROL_INVOKE.BIND_START, () => {diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.tsindex ac5a2a5c91..7827fa30bb 100644--- a/apps/desktop/src/main/hook-control/manager.ts+++ b/apps/desktop/src/main/hook-control/manager.ts@@ -1251,6 +1251,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContlane.binding === null ? null : { ...lane.binding, actions: [...lane.binding.actions] },// store 侧已保证读出来的别名仍然有效(目录删掉即归零), 这里直投。defaultWorkspace: defaultWorkspaceOf(store.get(), lane.config.provider),+ ...(lane.config.provider === 'x' ? { companionBotId: store.get().xCompanionBotId ?? null } : {}),};}diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex b411ce3dbd..967dcf5e65 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -27,6 +27,8 @@* 正确。后续要精确区分时再与 maker-core 一起演进。*/+import { beginChannelToolScope } from '../im/shared/channelToolScope.js';+import { randomUUID } from 'node:crypto';import fs from 'node:fs/promises';import path from 'node:path';@@ -53,6 +55,7 @@ import {import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { getMaker } from '../maker-host/index.js';+import { setSessionEffort, setSessionFastMode } from '../maker-host/session-effort-store.js';import { desktopSessionStorage } from '../maker-host/session-storage.js';import { resolveLenientRoute } from '../maker-host/model-route-guard.js';import { resolveLenientSessionRoute } from '../maker-host/model-route-guard-live.js';@@ -60,6 +63,7 @@ import {acquirePendingAgentSwitchForImSend,beginTurnChangeSetAtDispatch,prepareUnhealthySessionForSend,+ prepareBotSessionForImSend,wireSessionToIpc,isSessionInTurn,noteSilentStopUserSend,@@ -631,7 +635,7 @@ export function createMakerHookSessionRunner(deps: {const maker = getMaker();// 新任务的账号代次从读取偏好 / 默认配置之前算起(与个人 IM 同一判据): 中途换账号时// 不拿旧账号读到的配置去新账号的库里建任务。- const assertAccount = req.isNew ? captureChannelAccount() : undefined;+ const assertAccount = req.isNew || req.companionBotId ? captureChannelAccount() : undefined;/** 新任务建行后的补写(来源、发送时间、worktree)同样只写入口账号的库。 */const accountStillCurrent = (): boolean => {try {@@ -667,6 +671,7 @@ export function createMakerHookSessionRunner(deps: {let model: string | undefined = resolved?.model;let effort = resolved?.effort;let resumeSessionId: string | undefined;+ let companionFastMode: boolean | undefined;let effectiveAgentKind: AgentKind = resolved?.agentKind ?? 'claude-code';// 新建路径 resolved 必有值(capabilities 校验过); 复用路径由下方 meta 覆盖let permissionMode: PermissionMode = (resolved?.permissionMode ??@@ -690,7 +695,14 @@ export function createMakerHookSessionRunner(deps: {resumeSessionId = meta.sdkSessionId;effectiveAgentKind = meta.agentKind;}- effort = undefined;+ effort = req.companionBotId ? meta?.effort : undefined;+ companionFastMode = req.companionBotId ? meta?.fastMode : undefined;+ if (req.companionBotId) {+ // This lane bypasses bootstrapSession. Claude subscription bridges read+ // these stores, not createSession options, including on cold resume.+ setSessionEffort(req.sessionId, effort);+ setSessionFastMode(req.sessionId, companionFastMode === true);+ }permissionMode = meta?.permissionMode ?? 'bypassPermissions';rowProviderId = row?.providerId ?? null;agentDeviceId = row?.agentDeviceId ?? meta?.agentDeviceId ?? null;@@ -774,6 +786,7 @@ export function createMakerHookSessionRunner(deps: {...(providerId !== null ? { providerId } : {}),...(effort !== undefined ? { effort } : {}),permissionMode,+ ...(companionFastMode !== undefined ? { fastMode: companionFastMode } : {}),// chat 伪目录新会话: 标记 dialogue, 落侧边栏「对话」分组而非按// dialogues/<日期>/<id> 目录名聚成项目节点...(req.isNew && req.workspaceKind !== undefined@@ -789,7 +802,7 @@ export function createMakerHookSessionRunner(deps: {// 进程生命周期(对齐 im/turnRunner「attached 不传 vendorOptions」// 的裁决)。hook turn 本身的渠道说明由逐 turn 的// provider-aware hook prompt note 全覆盖,不依赖这里。- ...(req.isNew+ ...((req.isNew || req.companionBotId)? {vendorOptions: {source:@@ -1046,7 +1059,10 @@ export function createMakerHookSessionRunner(deps: {};};/** turn 收口清扫: 未决交互按默认自决 + 释放中央 route。幂等。 */+ let releaseXCompanionScope: (() => void) | undefined;const finalizeInteractions = (): void => {+ releaseXCompanionScope?.();+ releaseXCompanionScope = undefined;headlessTurn.closed = true;headlessTurn.release?.();headlessTurn.release = null;@@ -1255,7 +1271,10 @@ export function createMakerHookSessionRunner(deps: {// 渲染层展示的用户消息保持来源 IM 原话。逐 turn 追加固定文本,教模型// 用 xdt-file 引用回传文件而非误用 cindy_feishu_bot(规则 9,实踩背景// 见 outbound.ts 的常量注释)。- const promptWithNote = `${req.prompt}\n\n${buildHookPromptNote(req.source?.im)}\n\n${buildUiLanguageErrorNote(getResolvedMainLocale())}`;+ const publicCompanionNote = req.companionBotId+ ? '\n[渠道说明] 本轮是主人通过官方 X 账号绑定发起的公开提问,最终回答将公开回帖。请勿公开伙伴记忆或工作目录中的私人信息。回复由当前 X 通道投递,不要另用 X Manager 发帖。'+ : '';+ const promptWithNote = `${req.prompt}\n\n${buildHookPromptNote(req.source?.im)}${publicCompanionNote}\n\n${buildUiLanguageErrorNote(getResolvedMainLocale())}`;let replacementHandoff: string | null = null;if (req.isNew && req.replacementOfSessionId && req.source?.im === 'slack') {try {@@ -1432,6 +1451,14 @@ export function createMakerHookSessionRunner(deps: {scope: req.groupHistoryAccess,});}+ if (req.companionBotId && req.source?.im === 'x') {+ releaseXCompanionScope = beginChannelToolScope({+ sessionId: session.id, sessionInstanceId: session.instanceId,+ scope: { channel: 'x', botId: req.companionBotId, companion: true,+ chatId: req.origin.externalKey, laneUserId: req.origin.externalKey,+ chatKind: 'group', requesterIsOwner: true },+ });+ }const routeOrigin: RoutedTurnOrigin =req.source?.im === 'slack'? { kind: 'im', channel: 'slack' }@@ -1627,6 +1654,10 @@ export function createMakerHookSessionRunner(deps: {...runner,async run(req) {if (req.isNew) return runner.run(req);+ if (req.companionBotId) {+ const blocked = await prepareBotSessionForImSend(req.sessionId);+ if (blocked) return { status: 'error' as const, finalText: '', errorMessage: blocked, durationMs: 0 };+ }// 切换可能重建引擎,必须先应用选择,再读 meta、建会话和挂观察器。// 与创建任务共用取值链:迁移前保留 server 偏好,迁移后由本机正本忽略旧便签。const overrides: HookDispatchOverrides = {diff --git a/apps/desktop/src/main/hook-control/store.ts b/apps/desktop/src/main/hook-control/store.tsindex cdc2285034..e4bbbfe10d 100644--- a/apps/desktop/src/main/hook-control/store.ts+++ b/apps/desktop/src/main/hook-control/store.ts@@ -54,6 +54,8 @@ export interface SlackHookConfigState {telegramEnabled: boolean;/** X (Twitter) provider 独立开关。 */xEnabled: boolean;+ /** Explicit companion assignment; absent preserves ordinary X tasks. */+ xCompanionBotId?: string | null;/** 服务器地址覆写(高级/调试用, 无 UI 入口); null = 跟随内置默认。 */urlOverride: string | null;/** 别名 -> 本地绝对路径。 */@@ -110,6 +112,7 @@ export interface HookConnectionConfig {name: string;url: string;enabled: boolean;+ companionBotId?: string | null;workspaces: Record<string, string>;createdAt: number;}@@ -190,6 +193,7 @@ export interface SlackHookStore {provider: 'telegram' | 'x',alias: string | null,): SlackHookConfigState;+ setXCompanionBotId(botId: string | null): SlackHookConfigState;}export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {@@ -208,6 +212,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {};x: {enabled: boolean;+ companionBotId?: string | null;bindingCache: ProviderBindingCacheEntry | null;defaultWorkspace: string | null;};@@ -366,6 +371,8 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {},x: {enabled: x.enabled === true,+ companionBotId: typeof x.companionBotId === 'string' && x.companionBotId.length <= 200+ ? x.companionBotId : null,bindingCache: parseProviderBindingCache(x.bindingCache),// 成员关系不在这里卡: 解析时 workspaces 还没读进来。留给 viewOf 复核,// 那里才同时握有两者。@@ -540,6 +547,7 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {enabled: account.slack.enabled,telegramEnabled: account.telegram.enabled,xEnabled: account.x.enabled,+ xCompanionBotId: account.x.companionBotId ?? null,urlOverride: document.urlOverride,workspaces: { ...document.workspaces },bindingsCache: account.slack.bindingsCache.map((entry) => ({ ...entry })),@@ -633,5 +641,13 @@ export function createSlackHookStore(deps: SlackHookStoreDeps): SlackHookStore {account[provider].defaultWorkspace = normalized;});},+ setXCompanionBotId(botId) {+ if (botId !== null && (typeof botId !== 'string' || !botId.trim() || botId.length > 200)) {+ throw new HookConnectionValidationError('invalid companion id');+ }+ return mutateAccount((account) => {+ account.x.companionBotId = botId;+ });+ },};}diff --git a/apps/desktop/src/main/hook-control/xCompanion.ts b/apps/desktop/src/main/hook-control/xCompanion.tsnew file mode 100644index 0000000000..f5c82c40ca--- /dev/null+++ b/apps/desktop/src/main/hook-control/xCompanion.ts@@ -0,0 +1,32 @@+import { isCompanionShadowed } from '../companion-cloud/homes';+import { createHash } from 'node:crypto';+import { eq } from 'drizzle-orm';+import { getDbClient } from '../localDb/client/current';+import { botProfiles, sessions } from '../localDb/schema';+import { ensureBotChannelLaneSession } from '../localDb/ipc/bots';+import { captureChannelAccount } from '../im/shared/openChannelSession';+import { throwIpcError } from '../utils/ipcValidate';++/** The official X transport already authenticates the connected principal. */+export async function requireXCompanion(botId: string): Promise<void> {+ const [profile] = await getDbClient().drizzle.select({ status: botProfiles.status })+ .from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);+ if (profile?.status !== 'active' || isCompanionShadowed(botId)) throwIpcError('INVALID_PARAMS', 'Companion is unavailable');+}++export async function resolveXCompanionTarget(botId: string, externalKey: string) {+ const assertAccount = captureChannelAccount();+ await requireXCompanion(botId);+ assertAccount();+ // Public threads never reuse the private canonical conversation. Hash the full+ // transport key (including its principal/thread scope), not a truncated tweet id.+ const key = createHash('sha256').update(externalKey).digest('hex');+ const lane = await ensureBotChannelLaneSession({ botId, routeKey: `im:x:official:${key}`, title: 'X' });+ if (!lane.ok) throw new Error(lane.message);+ assertAccount();+ const [row] = await getDbClient().drizzle.select({ workingDir: sessions.workingDir })+ .from(sessions).where(eq(sessions.id, lane.sessionId)).limit(1);+ assertAccount();+ if (!row?.workingDir) throw new Error('Companion workspace is unavailable');+ return { sessionId: lane.sessionId, workingDir: row.workingDir };+}diff --git a/apps/desktop/src/main/im/shared/channelToolScope.ts b/apps/desktop/src/main/im/shared/channelToolScope.tsindex 7d38cd0ae7..d027551a71 100644--- a/apps/desktop/src/main/im/shared/channelToolScope.ts+++ b/apps/desktop/src/main/im/shared/channelToolScope.ts@@ -91,7 +91,7 @@ export interface FeishuToolScope {* 「当前在哪个对话、这一轮是不是主人触发」(伙伴技能读写按它授权)。*/export interface LaneTurnScope {- channel: 'wecom' | 'dingtalk' | 'discord';+ channel: 'wecom' | 'dingtalk' | 'discord' | 'x';/** 连接的 botContextId。 */botId: string;laneUserId: string;@@ -105,7 +105,7 @@ export interface LaneTurnScope {export type LaneTurnScopeChannel = LaneTurnScope['channel'];export function isLaneTurnScopeChannel(channel: string): channel is LaneTurnScopeChannel {- return channel === 'wecom' || channel === 'dingtalk' || channel === 'discord';+ return channel === 'wecom' || channel === 'dingtalk' || channel === 'discord' || channel === 'x';}export type ChannelToolScope = TelegramToolScope | FeishuToolScope | LaneTurnScope;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex c93bb1da38..f7cb0c9c0c 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5186,6 +5186,8 @@ contextBridge.exposeInMainWorld('electronAPI', {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 }),+ setXCompanion: (botId: string | null, expectedBotId: string | null): Promise<{ hook: unknown }> =>+ ipcRenderer.invoke('maker:hook-control:set-x-companion', { botId, expectedBotId }),setProviderDefaultWorkspace: (provider: 'telegram' | 'x',alias: string | null,diff --git a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsxindex 6448817fa2..3c554d8a5f 100644--- a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx@@ -1,4 +1,3 @@-import { Button } from '@/components/ui/button';/*** HookConnectionsSection —— 「IM 机器人」页「官方」栏(Cindy 渠道)。* i18n key 刻意留在 settings.remoteControl.hook.* 命名空间(50+ 条 × 4 语言的@@ -36,6 +35,8 @@ import { Button } from '@/components/ui/button';* 颜色全部走主题 token; 状态徽章沿用「个人」栏的 --settings-badge-* 语义色。*/+import { Button } from '@/components/ui/button';+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, Plus, Trash2 } from 'lucide-react';@@ -451,7 +452,7 @@ export function workspaceRowsToMap(return workspaces;}-export function HookConnectionsSection() {+export function HookConnectionsSection({ companion }: { companion?: { id: string; name: string } } = {}) {const { t } = useTranslation();const { entry, activation } = useSettingsSearchNavigation();const [hook, setHook] = useState<SlackHookView | null>(null);@@ -467,10 +468,11 @@ export function HookConnectionsSection() {const targetCard = (['slack', 'telegram', 'x'] as const).find((card) => entry?.targetId === 'cindy-im-' + card,) ?? null;- const [expandedCard, setExpandedCard] = useState<CindyImCard | null>(targetCard);+ const [expandedCard, setExpandedCard] = useState<CindyImCard | null>(companion ? 'x' : targetCard);useLayoutEffect(() => {if (targetCard) setExpandedCard(targetCard);}, [targetCard, activation]);+ const [companionPending, setCompanionPending] = useState(false);const [slackAuthActionPending, setSlackAuthActionPending] = useState(false);const slackAuthActionInFlightRef = useRef(false);const toggleCard = (card: CindyImCard) =>@@ -792,7 +794,7 @@ export function HookConnectionsSection() {void (async () => {const ok = await confirm({title: t('settings.remoteControl.hook.x.guide.ackTitle'),- content: <XUsageGuide />,+ content: <XUsageGuide companion={!!hookRef.current?.x.companionBotId} />,confirmText: t('settings.remoteControl.hook.x.guide.ackConfirm'),showCancel: false,// 主操作非破坏性(只是"我明白"), 焦点直接落在它上面@@ -1377,6 +1379,29 @@ export function HookConnectionsSection() {* 子树 remount)。动作按钮完全由 binding.actions 数据驱动 —— X 的 actions* 里没有 add_to_group, 加群按钮自然不渲染。*/+ const changeXCompanion = async () => {+ if (companionPending) return;+ const previous = hookRef.current?.x.companionBotId ?? null;+ if (!companion && !previous) return;+ const removing = !companion || previous === companion.id;+ setCompanionPending(true);+ try {+ const ok = await confirm({+ title: t(`bots.channels.officialX.${removing ? 'removeTitle' : 'bindTitle'}`, { name: companion?.name }),+ description: t(`bots.channels.officialX.${removing ? 'removeBody' : 'bindBody'}`, { name: companion?.name }),+ confirmText: t(`bots.channels.officialX.${removing ? 'remove' : 'bind'}`),+ });+ if (!ok) return;+ const requestedAtRevision = ++viewRevisionRef.current;+ const result = await window.electronAPI.hookControl.setXCompanion(removing ? null : companion!.id, previous);+ if (viewRevisionRef.current === requestedAtRevision) applyView(result.hook);+ } catch {+ toast.error(t('settings.remoteControl.hook.toast.actionFailed'));+ } finally {+ setCompanionPending(false);+ }+ };+const renderProviderCard = (provider: NeutralCardProvider) => {const view = hook[provider] as ProviderHookView | undefined;if (view === undefined) return null; // 旧 main 快照尚无该 provider 字段时不渲染@@ -1392,7 +1417,7 @@ export function HookConnectionsSection() {: 'settings.tina.prefs.providerX',)}description={t(`settings.remoteControl.hook.${provider}.description`)}- routeSummary={cs.bindingLine}+ routeSummary={companion ? null : cs.bindingLine}status={<ChannelStatusBadge tone={cs.badge.tone} label={cs.badge.label} />}headerAction={<Switch@@ -1414,7 +1439,7 @@ export function HookConnectionsSection() {{/* 绑定进度/结果一行(完成关联引导、失败原因等; 已关联的摘要由收起行承载, 展开区不重复) */}- {cs.bindingLine !== null && !cs.confirmed ? (+ {cs.bindingLine !== null && (!cs.confirmed || companion) ? (<spanclassName={`text-11 leading-relaxed ${cs.state === 'failed' ||@@ -1536,10 +1561,30 @@ export function HookConnectionsSection() {确认门弹窗, 那里根本没有目录选择器;· **不按 view.enabled / cs.confirmed 收起**: 正在评估要不要打开的人最需要看到「回帖是公开的」, 那时候两个条件都还不成立。 */}- {provider === 'x' ? <XUsageGuide /> : null}+ {provider === 'x' ? <>+ <XUsageGuide companion={!!view.companionBotId} />+ {companion ? (+ <div className="flex flex-col gap-2 border-t border-[var(--border-default)] pt-3">+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">+ {t(view.companionBotId === companion.id ? 'bots.channels.officialX.bound'+ : view.companionBotId ? 'bots.channels.officialX.boundElsewhere' : 'bots.channels.officialX.unbound', { name: companion.name })}+ </p>+ <Button variant="secondary" size="sm" type="button" disabled={companionPending}+ onClick={() => void changeXCompanion()}>+ {t(view.companionBotId === companion.id ? 'bots.channels.officialX.remove' : 'bots.channels.officialX.bind')}+ </Button>+ </div>+ ) : view.companionBotId ? (+ <div className="flex flex-col gap-2 border-t border-[var(--border-default)] pt-3">+ <p className="text-12 leading-relaxed text-[var(--text-secondary)]">{t('bots.channels.officialX.managed')}</p>+ <Button variant="secondary" size="sm" type="button" disabled={companionPending}+ onClick={() => void changeXCompanion()}>{t('bots.channels.officialX.remove')}</Button>+ </div>+ ) : null}+ </> : null}{/* 工作目录映射(清单共享, 偏好取本 provider 那份) */}- {view.enabled+ {view.enabled && !view.companionBotId? renderWorkdirSection(prefsState, undefined, {value: view.defaultWorkspace,// Telegram 的目录本来就一行一个, 行内选中比再开一个下拉更直白;@@ -1551,7 +1596,7 @@ export function HookConnectionsSection() {{/* 存量 global override 的收尾入口。刻意不按 provider 也不按 cs.confirmed 收:global scope 是 Telegram 与 X 共用的那一份, 旧设置在绑定确认之前就已经在盘上影响解析了 —— 要能看见才谈得上"可管理"。从未改过的设备一次都不会渲染。 */}- {view.enabled ? (+ {view.enabled && !view.companionBotId ? (<LegacyGlobalDefaultsNoticestate={legacyGlobalDefaults.state}pending={legacyGlobalDefaults.pending}@@ -1584,12 +1629,12 @@ export function HookConnectionsSection() {return (<div className="flex flex-col gap-3">- <p className="text-12 text-[var(--text-tertiary)]">+ {!companion ? <p className="text-12 text-[var(--text-tertiary)]">{t('settings.remoteControl.hook.description')}- </p>+ </p> : null}{/* ── Slack 渠道卡 ─────────────────────────────────────────────── */}- <ImChannelSettingsCard+ {!companion ? <ImChannelSettingsCardid="cindy-im-slack"title={t('settings.tina.prefs.providerSlack')}description={t('settings.remoteControl.hook.slackDescription')}@@ -2027,10 +2072,10 @@ export function HookConnectionsSection() {{/* 工作目录映射(清单共享, 偏好取 Slack 那份) */}{hook.enabled ? renderWorkdirSection(slackPrefsState, 6) : null}</div>- </ImChannelSettingsCard>+ </ImChannelSettingsCard> : null}{/* ── provider-neutral 渠道卡(Telegram / X, 同构渲染) ─────────── */}- {renderProviderCard('telegram')}+ {!companion ? renderProviderCard('telegram') : null}{renderProviderCard('x')}</div>);diff --git a/apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx b/apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsxindex f84f11317c..81eff85e4b 100644--- a/apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx+++ b/apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx@@ -102,9 +102,9 @@ export function ImChannelSettingsCard({</span><span className="flex min-w-0 shrink-0 items-center gap-3">- <span className="hidden w-[220px] truncate text-right text-12 text-[var(--text-secondary)] md:block">+ {routeSummary ? <span className="hidden w-[220px] truncate text-right text-12 text-[var(--text-secondary)] md:block">{routeSummary}- </span>+ </span> : null}{status}<ChevronDownsize={17}diff --git a/apps/desktop/src/renderer/components/settings/XUsageGuide.tsx b/apps/desktop/src/renderer/components/settings/XUsageGuide.tsxindex 9287630b46..f50ad55815 100644--- a/apps/desktop/src/renderer/components/settings/XUsageGuide.tsx+++ b/apps/desktop/src/renderer/components/settings/XUsageGuide.tsx@@ -78,7 +78,7 @@ function GuideBody({ children }: { children: React.ReactNode }) {return <span className="text-12 leading-[1.45] text-[var(--text-tertiary)]">{children}</span>;}-export function XUsageGuide() {+export function XUsageGuide({ companion = false }: { companion?: boolean } = {}) {const { t } = useTranslation();const k = (name: string) => `settings.remoteControl.hook.x.guide.${name}`;@@ -119,7 +119,7 @@ export function XUsageGuide() {{t(k('riskPublicBody'))}</span><span className="text-12 leading-[1.45] text-[var(--text-primary)]">- {t(k('riskWorkdirBody'))}+ {t(companion ? 'bots.channels.officialX.riskBody' : k('riskWorkdirBody'))}</span></div></div>diff --git a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsxindex b229d01771..68ee7a486d 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx@@ -21,6 +21,7 @@ const ipc = vi.hoisted(() => ({openProviderAction: vi.fn(),openExternal: vi.fn(),setProviderDefaultWorkspace: vi.fn(),+ setXCompanion: vi.fn(),imDefaultSettingsGet: vi.fn(),imDefaultSettingsReset: vi.fn(),}));@@ -194,6 +195,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {revokeTeam: ipc.revokeTeam,openProviderAction: ipc.openProviderAction,setProviderDefaultWorkspace: ipc.setProviderDefaultWorkspace,+ setXCompanion: ipc.setXCompanion,},maker: {imDefaultSettingsGet: ipc.imDefaultSettingsGet,@@ -205,6 +207,42 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {afterEach(() => cleanup());+ // The real settings component must assign/revoke with the previously observed+ // owner, and cancellation must not write (new companion entry, unit DOM).+ it('assigns and removes X without disconnecting the account', async () => {+ const unbound = { ...BASE_HOOK, x: { ...BASE_HOOK.x, url: 'wss://x.example.test' } };+ const bound = { ...unbound, x: { ...unbound.x, companionBotId: 'bot-fixture' } };+ ipc.get.mockResolvedValue({ hook: unbound });+ ipc.setXCompanion.mockResolvedValueOnce({ hook: bound }).mockResolvedValueOnce({ hook: unbound });+ render(<HookConnectionsSection companion={{ id: 'bot-fixture', name: 'Fixture' }} />);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.officialX.bind' }));+ await waitFor(() => expect(ipc.setXCompanion).toHaveBeenCalledWith('bot-fixture', null));+ expect(screen.queryByRole('button', { name: SLACK_CARD })).toBeNull();+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.officialX.remove' }));+ await waitFor(() => expect(ipc.setXCompanion).toHaveBeenLastCalledWith(null, 'bot-fixture'));+ expect(ipc.providerBindRevoke).not.toHaveBeenCalled();+ });++ it('can remove an orphaned assignment from the global X settings', async () => {+ const unbound = { ...BASE_HOOK, x: { ...BASE_HOOK.x, url: 'wss://x.example.test' } };+ ipc.get.mockResolvedValue({ hook: { ...unbound, x: { ...unbound.x, companionBotId: 'deleted-bot' } } });+ ipc.setXCompanion.mockResolvedValue({ hook: unbound });+ render(<HookConnectionsSection />);+ await expandChannelCard(X_CARD);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.officialX.remove' }));+ await waitFor(() => expect(ipc.setXCompanion).toHaveBeenCalledWith(null, 'deleted-bot'));+ expect(ipc.providerBindRevoke).not.toHaveBeenCalled();+ });++ it('keeps the X assignment unchanged when confirmation is cancelled', async () => {+ ipc.get.mockResolvedValue({ hook: { ...BASE_HOOK, x: { ...BASE_HOOK.x, url: 'wss://x.example.test' } } });+ dialog.confirm.mockResolvedValue(false);+ render(<HookConnectionsSection companion={{ id: 'bot-fixture', name: 'Fixture' }} />);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.officialX.bind' }));+ await waitFor(() => expect(dialog.confirm).toHaveBeenCalled());+ expect(ipc.setXCompanion).not.toHaveBeenCalled();+ });+it('never derives prototype or built-in chat aliases from a selected folder', () => {expect(deriveAlias('/tmp/chat', new Set())).toBe('chat-2');expect(deriveAlias('/tmp/__proto__', new Set())).toBe('__proto__-2');diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsxindex c8e854be62..29f51e11a3 100644--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx@@ -7,6 +7,8 @@* 与 设置 → IM 机器人 里那份个人 bot 各用各的凭证; 添加时也可以把那份个人 bot 一次性移过来* (个人 bot 随之清空)。远端伙伴没有这一页。*/++import { HookConnectionsSection } from '@/components/settings/HookConnectionsSection';import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';import * as Dialog from '@radix-ui/react-dialog';import { Briefcase, Gamepad2, MessageSquare, Plus, Send, Zap, type LucideIcon } from 'lucide-react';@@ -147,6 +149,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {return (<section className="flex flex-col gap-4 pt-3" aria-label={t('bots.channels.title')}>+ {typeof window.electronAPI.hookControl?.setXCompanion === 'function' ? <HookConnectionsSection companion={{ id: bot.id, name: bot.name }} /> : null}{loading && !payload ? (<div className="flex justify-center py-6 text-[var(--text-tertiary)]"><Spinner size={16} />diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 80b3b23731..cb0345123d 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10073,6 +10073,19 @@"cancel": "Cancel","failed": "Couldn’t remove it. Try again later.","ok": "OK"+ },+ "officialX": {+ "bind": "Assign to this teammate",+ "remove": "Remove teammate assignment",+ "bindTitle": "Let {{name}} handle X questions?",+ "bindBody": "Your public questions to @askmycindy will use {{name}}’s identity, tools, shared memory and workspace. Replies are public. The X thread is separate from your private chat history. This replaces any existing teammate assignment.",+ "removeTitle": "Remove the X assignment?",+ "removeBody": "Your X account stays connected. Future questions become ordinary tasks. Replies already in progress will finish.",+ "bound": "X questions are assigned to {{name}}. Enable X and authorize your account to start.",+ "boundElsewhere": "X is assigned to another teammate. Assigning it here replaces that teammate.",+ "unbound": "Let {{name}} handle your questions to the official @askmycindy bot.",+ "managed": "A teammate handles X questions. Change the assignment in that teammate’s message platform settings.",+ "riskBody": "X questions use the teammate’s shared memory, tools and workspace, and replies are public. Do not use X for private information. The X thread does not directly use your private chat history."}}},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 0c35c4bb97..9493c54434 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10033,6 +10033,19 @@"cancel": "キャンセル","failed": "削除できませんでした。しばらくしてからもう一度お試しください","ok": "OK"+ },+ "officialX": {+ "bind": "このパートナーに割り当てる",+ "remove": "パートナーの割り当てを解除",+ "bindTitle": "X の質問を {{name}} に任せますか?",+ "bindBody": "公式 @askmycindy への公開の質問を、{{name}} の個性、ツール、共有メモリ、作業フォルダーを使って処理します。返信は公開されます。X の履歴はプライベートチャットとは別です。既存のパートナーの割り当ては置き換わります。",+ "removeTitle": "X の割り当てを解除しますか?",+ "removeBody": "X アカウントの連携は維持され、以降の質問は通常のタスクになります。進行中の返信は完了まで続きます。",+ "bound": "X の質問は {{name}} が担当します。X を有効にしてアカウントを認証すると利用できます。",+ "boundElsewhere": "X は別のパートナーに割り当てられています。ここに割り当てると置き換わります。",+ "unbound": "公式 @askmycindy への質問を {{name}} に任せられます。",+ "managed": "X の質問はパートナーが担当しています。そのパートナーのメッセージプラットフォーム設定で変更できます。",+ "riskBody": "X の質問にはパートナーの共有メモリ、ツール、作業フォルダーを使用し、返信は公開されます。個人情報を扱う用途には使用しないでください。プライベートチャットの履歴は直接使用しません。"}}},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex a9d6e0b1b2..cb8372aada 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10033,6 +10033,19 @@"cancel": "취소","failed": "제거하지 못했어요. 잠시 후 다시 시도해 주세요","ok": "확인"+ },+ "officialX": {+ "bind": "이 파트너에게 연결",+ "remove": "파트너 연결 해제",+ "bindTitle": "X 질문을 {{name}}에게 맡길까요?",+ "bindBody": "공식 @askmycindy에 보낸 공개 질문을 {{name}}의 정체성, 도구, 공유 기억과 작업 폴더로 처리합니다. 답글은 공개됩니다. X 대화 기록은 비공개 채팅과 분리됩니다. 기존 파트너 연결이 있으면 교체됩니다.",+ "removeTitle": "X 파트너 연결을 해제할까요?",+ "removeBody": "X 계정 연결은 유지되며 이후 질문은 일반 작업으로 처리됩니다. 이미 진행 중인 답변은 완료됩니다.",+ "bound": "{{name}}이 X 질문을 담당합니다. X를 켜고 계정을 인증하면 사용할 수 있습니다.",+ "boundElsewhere": "X가 다른 파트너에 연결되어 있습니다. 여기에 연결하면 기존 파트너를 교체합니다.",+ "unbound": "공식 @askmycindy에 보낸 질문을 {{name}}에게 맡길 수 있습니다.",+ "managed": "파트너가 X 질문을 담당합니다. 해당 파트너의 메시지 플랫폼 설정에서 연결을 변경할 수 있습니다.",+ "riskBody": "X 질문에는 파트너의 공유 기억, 도구와 작업 폴더가 사용되며 답글은 공개됩니다. 개인 정보를 다루는 용도로 사용하지 마세요. 비공개 채팅 기록을 직접 사용하지 않습니다."}}},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex d5eb416c96..9b28b9aa25 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10033,6 +10033,19 @@"cancel": "取消","failed": "没能移除,请稍后再试","ok": "知道了"+ },+ "officialX": {+ "bind": "绑定给这位伙伴",+ "remove": "取消伙伴绑定",+ "bindTitle": "让 {{name}} 处理 X 提问?",+ "bindBody": "你对官方 @askmycindy 的公开提问将交给 {{name}},使用伙伴的身份、能力、共享记忆和工作目录;回答会公开回帖。X 专线与私聊记录分开。若已绑定其他伙伴,本次将替换原绑定。",+ "removeTitle": "取消伙伴的 X 绑定?",+ "removeBody": "保留 X 账号授权,后续提问恢复为普通任务。已开始的回复继续完成。",+ "bound": "X 提问已交给 {{name}}。启用 X 并完成账号授权后即可使用。",+ "boundElsewhere": "X 已交给另一位伙伴。绑定到这里会替换原伙伴。",+ "unbound": "可将官方 @askmycindy 收到的你的提问交给 {{name}}。",+ "managed": "X 提问由伙伴处理。可在该伙伴的消息平台设置中更改绑定。",+ "riskBody": "X 提问会使用伙伴的共享记忆、能力和工作目录,回答会公开。请勿通过 X 处理私人信息。专线不会直接使用伙伴的私聊记录。"}}},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex e095e76436..2af5f9adf4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10033,6 +10033,19 @@"cancel": "取消","failed": "未能移除,請稍後再試","ok": "知道了"+ },+ "officialX": {+ "bind": "連結至這位夥伴",+ "remove": "取消夥伴連結",+ "bindTitle": "讓 {{name}} 處理 X 提問?",+ "bindBody": "你對官方 @askmycindy 的公開提問將交給 {{name}},使用夥伴的身分、能力、共享記憶和工作目錄;回答會公開回覆。X 專線與私聊記錄分開。若已連結其他夥伴,本次將替換原連結。",+ "removeTitle": "取消夥伴的 X 連結?",+ "removeBody": "保留 X 帳號授權,後續提問恢復為一般任務。已開始的回覆會繼續完成。",+ "bound": "X 提問已交給 {{name}}。啟用 X 並完成帳號授權後即可使用。",+ "boundElsewhere": "X 已交給另一位夥伴。連結到這裡會替換原夥伴。",+ "unbound": "可將官方 @askmycindy 收到的你的提問交給 {{name}}。",+ "managed": "X 提問由夥伴處理。可在該夥伴的訊息平台設定中更改連結。",+ "riskBody": "X 提問會使用夥伴的共享記憶、能力和工作目錄,回答會公開。請勿透過 X 處理私人資訊。專線不會直接使用夥伴的私聊記錄。"}}},diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1b9a9fa485..b0ee1c06ed 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4411,7 +4411,9 @@ interface ElectronAPI {setWorkspaces: (workspaces: Record<string, string>,) => Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;- /** 该 provider 派发任务的默认工作目录别名(null = 内置「对话」伪目录)。 */+ /** Official X assignment, compared with the caller's last observed value. */+ setXCompanion: (botId: string | null, expectedBotId: string | null) =>+ Promise<{ hook: import('../shared/hookControlIpc').SlackHookView }>;setProviderDefaultWorkspace: (provider: 'telegram' | 'x',alias: string | null,diff --git a/apps/desktop/src/shared/hookControlIpc.ts b/apps/desktop/src/shared/hookControlIpc.tsindex 7054863b9b..11e1163738 100644--- a/apps/desktop/src/shared/hookControlIpc.ts+++ b/apps/desktop/src/shared/hookControlIpc.ts@@ -38,6 +38,7 @@ export const HOOK_CONTROL_INVOKE = {* 进程内通道, 没有跨版本兼容问题 —— 原 set-x-default-workspace 直接改名。*/SET_PROVIDER_DEFAULT_WORKSPACE: 'maker:hook-control:set-provider-default-workspace',+ SET_X_COMPANION: 'maker:hook-control:set-x-companion',/** 发起 Slack 账号绑定(bind.start; SIWS OIDC, 无参数)。 */BIND_START: 'maker:hook-control:bind-start',/** 解除 Slack 账号绑定(bind.revoke)。 */@@ -140,6 +141,8 @@ export interface ProviderBindingView {/** provider-neutral(Telegram / X)的独立设置与绑定视图。 */export interface ProviderHookView {+ /** Local companion assignment, currently only used by the official X provider. */+ companionBotId?: string | null;enabled: boolean;/** 该 provider 平级 hook 服务的运行期端点;空值表示当前环境尚未部署。 */url: string;diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.mdindex 3dc6d98ebc..cc5e9e5a6e 100644--- a/docs/dev-rules/im-turn-flow.md+++ b/docs/dev-rules/im-turn-flow.md@@ -184,3 +184,11 @@ inbound ──► admitted ──► queued? ──► dispatching ──► run| 模型准入(`openSession`) | 只做凭证检查 | 新任务做路由检查 | 已按 Dash 指定改走 `openSession` 准入:新任务的模型 / 来源 / 推理强度 / Fast 不被支持时直接拒绝(文案「不会自动更换模型或供应商」),准入还会规范化来源与推理强度;渠道默认配置若指向已停用的模型,新任务会建不出来(以前会照建) || live session 改走 `bootstrapSession` | 不注入项目上下文 / Orca 指令 | 同左 | 未改:改了等于给 IM / hook 任务新增项目上下文与 Orca 指令注入、目录授权准备等行为,属产品决定 || 缺口 2b / 2e / 2f / 默认配置取值链 | 见台账 | 见台账 | 各自保留,合并只共享实现骨架 |++### 官方 X 的伙伴路由++`hook-control/xCompanion.ts` 通过既有 `ensureBotChannelLaneSession` 创建 X 公开专线。+绑定正本为账号隔离的 hook store `x.companionBotId`,不修改跨端 wire 或数据库 schema。+Dispatcher 只接受宿主解析的专线 ID 和精确工作目录,忽略入站指定的任务 ID;执行与排队恢复时+重新核对绑定。Runner 在获取切模锁前执行伙伴模型/能力刷新,provider 启动前登记 X 的+`LaneTurnScope`,终态释放;source 仍保留 `bot`,渠道说明逐轮追加。普通未绑定 X 路由保持原样。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex c2a2da66dc..6a7005efbb 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -955,3 +955,10 @@ Desktop 的 Bot Market 随安装包提供预制原生包入口,复用同一 im- 全量保留来源资料、技能及自动化(包括原生 Heartbeat、未知触发条件、空标记文件),仅排除用户主动取消的项目。暂不能转换的自动化仍保存为可见的停用任务和加密原始定义,明确提示待适配项;不能因 Cindy 暂缺能力或原投放渠道不可用而过滤。验收对照来源总清单,不以过滤后的已选数量冒充完整。- 单项读取或写入失败保留重试记录,不中止其它内容;导入成功数量与自动化启用状态分别计算。文件字节保护仍适用,不截断文件冒充完整导入。- 原任务在验证及接管完成前保持原状。明确选用 Cindy 模型和工具设置后可解除相应兼容性待办,仍须验证数据并确认原任务已暂停,才能启用 Cindy 任务。++## 官方 X 连接交给伙伴++- 本机伙伴的「消息平台」复用设置页已有的官方 `@askmycindy` 连接,可将当前账号在该电脑上的 X 提问交给一位伙伴;绑定与 X OAuth 授权、启停相互独立。取消伙伴绑定保留 X 账号授权,后续回到普通 X 任务。+- 每条服务端 X 路由建立伙伴 `role=channel` 专线,使用同一身份、能力、记忆、工作目录与模型配置,不接续伙伴私聊的模型历史。公开回帖风险在绑定确认和卡片中明确展示。+- 伙伴选择按账号保存;更换使用当前绑定做比较,避免迟到确认覆盖新选择。停用、删除或已交出主力电脑的伙伴不可接收新 X 提问;解除绑定后已排队的旧专线请求拒绝执行,不转给另一位伙伴。+- 复用官方 X 的认证、收发与媒体回帖,不接入 X Manager 搜索/发帖插件,不新增 X 私信机器人或个人 API 凭证入口。消息平台设置仍为本机桌面入口,远程伙伴与 Mobile 沿用现有入口边界。