Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(bots): bind personal WeChat to a teammate

Chrisc01405422b05
diff --git a/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs b/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs
new file mode 100644
index 0000000000..a9e68eb67a
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs
@@ -0,0 +1,16 @@
+export default {
+ name: 'wechat-companion',
+ entry: './wechat-companion-fixture.tsx',
+ viewport: { width: 620, height: 900 },
+ real: 'BotChannelsPage, WechatBotSection, useWechatBot, existing connection accordion and translations',
+ notCovered: 'Real account login, Tencent scan authorization, persisted binding and message delivery',
+ cases: {
+ default: { about: 'New WeChat connection for a teammate', data: {} },
+ existing: { about: 'Reuse the already authorized personal WeChat connection', data: { bound: true } },
+ assigned: { about: 'Connected teammate and remove-link action', data: { bound: true, companionBotId: 'fixture-cindy' } },
+ other: { about: 'Another teammate owns this connection', data: { bound: true, companionBotId: 'fixture-other' } },
+ },
+ async check(page) {
+ await page.locator('#companion-im-wechat-trigger').click();
+ },
+};
diff --git a/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx b/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx
new file mode 100644
index 0000000000..12fbc82906
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx
@@ -0,0 +1,27 @@
+import { BotChannelsPage } from '../../../src/renderer/features/bots/BotChannelsPage';
+import type { BotProfile } from '../../../src/renderer/features/bots/botStore';
+import { mountPage, subscription, forbid } from '../../ui-page/harness';
+
+mountPage({
+ host: (ctx) => ({
+ botImConnection: {
+ list: async () => ({ connections: [] }),
+ onChanged: subscription('connections'),
+ },
+ maker: {
+ imDefaultSettingsGet: async () => ({ agentKind: 'codex', agents: { codex: { model: 'gpt-6.1-sol' } } }),
+ },
+ wechatBot: {
+ getState: async () => ({ phase: ctx.data.bound ? 'connected' : 'disconnected', bound: !!ctx.data.bound, queuedTasks: 0 }),
+ getChannelSettings: async () => ({ version: 1, workingDir: null, workingDirAvailable: true, companionBotId: ctx.data.companionBotId }),
+ onStateChange: subscription('wechatState'),
+ onChannelSettingsChange: subscription('wechatSettings'),
+ setCompanion: forbid('wechatBot.setCompanion'),
+ authorize: forbid('wechatBot.authorize'),
+ unbind: forbid('wechatBot.unbind'),
+ },
+ }),
+ render: () => <div className="mx-auto max-w-2xl p-4"><BotChannelsPage bot={{
+ id: 'fixture-cindy', name: 'Cindy', status: 'active',
+ } as BotProfile} /></div>,
+});
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index 448c95a941..8221ea2d0d 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -64,7 +64,7 @@ import {
captureSessionRuntimeControlOwnerEpoch,
sessionRuntimeControlOwnerEpochMatches,
} from '../maker-ipc/sessionRuntimeControl.js';
-import { sessions } from '../localDb/schema';
+import { botProfiles, sessions } from '../localDb/schema';
import {
im,
feishuIm,
@@ -122,10 +122,12 @@ import { getUpdateStatus, isUpdateRelaunchImminent } from '../updateService';
import { createLogger } from '../logger';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';
+import { throwIpcError } from '../utils/ipcValidate';
import {
readWechatChannelSettings,
resetWechatWorkingDir,
writeWechatWorkingDir,
+ writeWechatCompanionBinding,
} from './wechat/channelSettings';
/** 伙伴「消息平台」的 IPC: 连接增删 / 群聊 / 隐藏任务, 以及把个人 bot 移给伙伴。 */
@@ -400,6 +402,36 @@ export function startImOrchestrators(): void {
assertTrustedAppRendererEvent(event);
return readWechatChannelSettings();
});
+ ipcMain.handle('wechatBot:set-companion', (event, botId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (botId !== null && (typeof botId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(botId))) {
+ throwIpcError('INVALID_ARGUMENT', 'Invalid teammate');
+ }
+ return connectionLifecycle.runWhileStarted(async () => {
+ const generation = captureImAccountGeneration();
+ if (generation === null) throwIpcError('PRECONDITION_FAILED', 'Account unavailable');
+ if (botId) {
+ const [profile] = await getDbClient().drizzle.select({ status: botProfiles.status })
+ .from(botProfiles).where(eq(botProfiles.id, botId as string)).limit(1);
+ if (profile?.status !== 'active') throwIpcError('PRECONDITION_FAILED', 'BOT_INACTIVE');
+ const current = readWechatChannelSettings().companionBotId;
+ if (current && current !== botId) throwIpcError('PRECONDITION_FAILED', 'WECHAT_COMPANION_IN_USE');
+ }
+ try {
+ await wechatIm.updateCompanionBinding(() => {
+ if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');
+ writeWechatCompanionBinding(botId as string | null);
+ });
+ } catch (error) {
+ throwIpcError('PRECONDITION_FAILED', error instanceof Error && error.message === 'WECHAT_CONNECTION_BUSY'
+ ? 'WECHAT_CONNECTION_BUSY' : 'WECHAT_COMPANION_UPDATE_FAILED');
+ }
+ BrowserWindow.getAllWindows().forEach((window) => {
+ if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', readWechatChannelSettings());
+ });
+ return readWechatChannelSettings();
+ });
+ });
ipcMain.handle('wechatBot:choose-working-directory', async (event) => {
assertTrustedAppRendererEvent(event);
const owner = BrowserWindow.fromWebContents(event.sender);
diff --git a/apps/desktop/src/main/im/shared/channelToolScope.ts b/apps/desktop/src/main/im/shared/channelToolScope.ts
index 7d38cd0ae7..23b8d0adcb 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' | 'wechat';
/** 连接的 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 === 'wechat';
}
export type ChannelToolScope = TelegramToolScope | FeishuToolScope | LaneTurnScope;
diff --git a/apps/desktop/src/main/im/shared/imBotBindingRuntime.ts b/apps/desktop/src/main/im/shared/imBotBindingRuntime.ts
index d2de80831e..6d1ce0569d 100644
--- a/apps/desktop/src/main/im/shared/imBotBindingRuntime.ts
+++ b/apps/desktop/src/main/im/shared/imBotBindingRuntime.ts
@@ -8,7 +8,7 @@
* - 群 / 话题 / 外部用户私聊 → bots.ts 的 channel 专线(幂等创建);
* - 发送前守卫 → register.ts 的 prepareBotSessionForImSend(与桌面发送同源)。
*
- * 一份连接实例只属于一位伙伴, 所以归属解析就是常量 botId。
+ * 独立连接使用固定归属;个人微信单实例通过回调读取当前伙伴归属。
*/
import { eq } from 'drizzle-orm';
@@ -42,9 +42,9 @@ async function isActiveSession(sessionId: string): Promise<boolean> {
return row?.status === 'active' && row.source === 'bot';
}
-export function createImCompanionRouteDeps(ownerBotId: string): ImCompanionRouteDeps {
+export function createImCompanionRouteDeps(ownerBotId: string | (() => string | null)): ImCompanionRouteDeps {
return {
- readBinding: () => ownerBotId,
+ readBinding: () => typeof ownerBotId === 'function' ? ownerBotId() : ownerBotId,
async resolveSession({ botId, target, create }): Promise<ImCompanionSessionResult | null> {
if (!create) {
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index 2fe7802660..a98367028f 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -59,7 +59,7 @@ export interface CreateImOrchestratorOptions {
* 这条连接属于哪位伙伴: 主人私聊进伙伴主任务, 群 / 话题 / 外部私聊进伙伴的隐藏
* 专线(需 adapter.companionLane)。缺省 = 渠道自己的路由。
*/
- companionBotId?: string;
+ companionBotId?: string | (() => string | null);
}
/**
diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.ts
index 68174c9561..e9aede8132 100644
--- a/apps/desktop/src/main/im/wechat/WechatIM.ts
+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts
@@ -193,6 +193,38 @@ export class WechatIM extends BaseIM implements RichChannelIM {
return { ...this.#state, bound: this.#hasBinding };
}
+ isOwner(userId: string): boolean {
+ return !!this.#epoch && this.#epoch.credentials.userId === userId;
+ }
+
+ /** Change routing only between messages; credentials and the authorization epoch stay intact. */
+ updateCompanionBinding(update: () => void): Promise<void> {
+ return this.#queueLifecycle(async () => {
+ if (this.#authorizationAbort || this.#activeTasks.size || this.#pendingInteractions.size) {
+ throw new Error('WECHAT_CONNECTION_BUSY');
+ }
+ const epoch = this.#epoch;
+ if (epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {
+ throw new Error('WECHAT_CONNECTION_BUSY');
+ }
+ if (this.#activeTasks.size) throw new Error('WECHAT_CONNECTION_BUSY');
+ const revision = this.#compatibilityRevision;
+ await this.#stopEpoch();
+ try {
+ // A poll already in flight may have persisted a message while we drained it.
+ if (epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {
+ throw new Error('WECHAT_CONNECTION_BUSY');
+ }
+ update();
+ } finally {
+ if (epoch && this.#isCompatibilityRevisionAllowed(revision)) {
+ const binding = await this.#requireStore().getActiveBinding();
+ if (binding) await this.#startEpoch(binding, epoch.credentials, revision);
+ }
+ }
+ });
+ }
+
async init(): Promise<void> {
await this.setCompatibilityDisabled(this.#deps.isCompatibilityDisabled());
const revision = this.#compatibilityRevision;
@@ -912,6 +944,8 @@ export class WechatIM extends BaseIM implements RichChannelIM {
if (!message || !task || (command !== '/stop' && command !== '/stop all')) {
continue;
}
+ if (this.#turnRuntime?.runner.companionBotIdFor?.(this.#epoch?.credentials.ilinkBotId ?? '')
+ && !this.isOwner(message.senderId)) continue;
await this.#requireStore().cancelForCommand({
bindingEpoch: binding.bindingEpoch,
commandTaskId: task.id,
@@ -1059,17 +1093,38 @@ export class WechatIM extends BaseIM implements RichChannelIM {
}
const turnInput = prepareWechatTaskTurn(payload);
+ const botContextId = this.#epoch?.credentials.ilinkBotId ?? '';
+ const companion = runtime.runner.companionBotIdFor?.(botContextId);
+ const requesterIsOwner = this.isOwner(task.peerId);
const active: ActiveTask = { task, terminalCommitted: false };
this.#activeTasks.set(task.peerId, active);
const stopTyping = await this.#startTyping(task);
let dispatch;
try {
dispatch = await runtime.runner.dispatchAgentTurn({
- botContextId: this.#epoch?.credentials.ilinkBotId ?? '',
+ botContextId,
userId: task.peerId,
userMessageId: task.id,
// 个人微信只有私聊;渠道说明、引用与投递事实只进模型,落库保留原文。
- channelNoteSource: { chatKind: 'direct', chatId: task.peerId },
+ channelNoteSource: {
+ chatKind: 'direct', chatId: task.peerId,
+ ...(companion ? {
+ senderId: task.peerId, senderIsOwner: requesterIsOwner,
+ } : {}),
+ },
+ ...(companion ? {
+ requesterIsOwner,
+ messageOrigin: { chat: { kind: 'direct' as const }, sender: { id: task.peerId, isOwner: requesterIsOwner } },
+ channelToolScope: {
+ channel: 'wechat' as const,
+ botId: botContextId,
+ laneUserId: task.peerId,
+ chatId: task.peerId,
+ chatKind: 'direct' as const,
+ requesterIsOwner,
+ companion: true as const,
+ },
+ } : {}),
...turnInput,
attachments: payload.attachments,
queueMode: 'external',
@@ -1257,6 +1312,16 @@ export class WechatIM extends BaseIM implements RichChannelIM {
async #processCommand(task: WechatTask, command: string): Promise<void> {
const runtime = this.#turnRuntime;
if (!runtime) throw new Error('WECHAT_TURN_RUNTIME_NOT_ATTACHED');
+ const botContextId = this.#epoch?.credentials.ilinkBotId ?? '';
+ const companion = runtime.runner.companionBotIdFor?.(botContextId);
+ if (companion && !this.isOwner(task.peerId)) {
+ await this.#commitSimpleReply(task, '只有主人可以使用机器人命令。');
+ return;
+ }
+ if (companion && /^\/(?:permission|model|project)(?:\s|$)/.test(command)) {
+ await this.#commitSimpleReply(task, '请在 Cindy 的伙伴设置中调整模型和权限。');
+ return;
+ }
if (/^\/permission(?:\s|$)/.test(command)) {
await this.#processPermissionCommand(task, command, runtime);
return;
@@ -1279,6 +1344,13 @@ export class WechatIM extends BaseIM implements RichChannelIM {
await this.#commitSimpleReply(task, '已停止任务。');
return;
case '/new': {
+ if (companion) {
+ const result = await runtime.runner.rotateCompanionLane?.(botContextId, task.peerId);
+ if (result === 'owner-dm') {
+ await this.#commitSimpleReply(task, '这里与伙伴共用同一条长期任务,记录和记忆会保留。需要整理上下文时,请在 Cindy 中重启伙伴。');
+ return;
+ }
+ }
const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);
if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');
const prepared = await runtime.repo.prepareNewSession(
@@ -1545,10 +1617,15 @@ export class WechatIM extends BaseIM implements RichChannelIM {
const runtime = this.#turnRuntime;
if (!runtime) throw new Error('WECHAT_TURN_RUNTIME_NOT_ATTACHED');
const botId = this.#epoch?.credentials.ilinkBotId ?? 'wechat';
- const prepared = await runtime.repo.prepareNewSession(botId, message.senderId);
- const existing = await runtime.repo.findActiveSession(botId, message.senderId);
- const session =
- existing ?? (await runtime.repo.createSession(botId, message.senderId, undefined, prepared));
+ // Resolve the companion before staging media and persisting the durable task: its
+ // message/media ownership must be the same as the session used by dispatch.
+ const companion = runtime.runner.companionBotIdFor?.(botId);
+ const target = companion ? await runtime.runner.resolveRouteTarget(botId, message.senderId) : null;
+ const session = target?.row ?? await (async () => {
+ const prepared = await runtime.repo.prepareNewSession(botId, message.senderId);
+ return await runtime.repo.findActiveSession(botId, message.senderId)
+ ?? await runtime.repo.createSession(botId, message.senderId, undefined, prepared);
+ })();
const epoch = await this.#requireStore().getConversationEpoch(bindingEpoch, message.senderId);
const taskId = randomUUID();
const staged = await stageWechatTaskMedia({
diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
index f7ca78c2fa..209be0d506 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
@@ -462,6 +462,58 @@ describe('WechatIM host boundary', () => {
await im.dispose();
});
+ // Regression: changing a teammate must retain credentials and cannot reroute queued messages.
+ // tier: unit; exercise the public lifecycle with a restored authorization and real task store.
+ it('switches an idle connection without reauthorizing and refuses queued work', async () => {
+ let queued = 0;
+ const { im, transport, testHost } = restoredConnection(() => queued);
+ await im.init();
+ try {
+ expect(im.isOwner('owner')).toBe(true);
+ expect(im.isOwner('guest')).toBe(false);
+ const update = vi.fn();
+ queued = 1;
+ await expect(im.updateCompanionBinding(update)).rejects.toThrow('WECHAT_CONNECTION_BUSY');
+ expect(update).not.toHaveBeenCalled();
+ expect(transport.notifyStop).not.toHaveBeenCalled();
+ queued = 0;
+ await im.updateCompanionBinding(update);
+ expect(update).toHaveBeenCalledOnce();
+ expect(im.getState().phase).toBe('connected');
+ expect(transport.notifyStart).toHaveBeenCalledTimes(2);
+ expect(testHost.secrets.write).not.toHaveBeenCalled();
+ expect(testHost.secrets.remove).not.toHaveBeenCalled();
+ } finally { await im.dispose(); }
+ });
+
+ // Regression: the durable inbox used to claim a personal session even for companion messages.
+ // tier: unit; feed transport ingress and inspect the real task-store transaction boundary.
+ it('persists companion ingress against the resolved task before dispatch', async () => {
+ const { im, transport, db } = restoredConnection(() => 0);
+ let receive!: (result: Awaited<ReturnType<WechatTransport['poll']>>) => void;
+ vi.mocked(transport.poll).mockImplementationOnce(() => new Promise((resolve) => { receive = resolve; }));
+ const resolveRouteTarget = vi.fn(async (_bot: string, peer: string) => ({ row: { id: `companion-${peer}` } }));
+ const prepareNewSession = vi.fn();
+ im.attachTurnRuntime({
+ runner: { companionBotIdFor: () => 'cindy', resolveRouteTarget },
+ repo: { prepareNewSession }, config: {}, resetSessionToDefaults: vi.fn(),
+ } as never);
+ await im.init();
+ try {
+ receive({ cursor: 'next', messages: ['owner', 'guest'].map((senderId) => ({
+ senderId, messageId: senderId, text: 'hello', contextToken: 'context', media: [],
+ })) });
+ await vi.waitFor(() => expect(db.tx).toHaveBeenCalledWith('wechatCommitPollBatch', expect.objectContaining({
+ messages: expect.arrayContaining([
+ expect.objectContaining({ peerId: 'owner', sessionId: 'companion-owner' }),
+ expect.objectContaining({ peerId: 'guest', sessionId: 'companion-guest' }),
+ ]),
+ })));
+ expect(prepareNewSession).not.toHaveBeenCalled();
+ expect(resolveRouteTarget).toHaveBeenCalledTimes(2);
+ } finally { await im.dispose(); }
+ });
+
it('removes staged files returned while replacing the previous binding', async () => {
const previous = { bindingEpoch: 'binding-previous', cursor: 'cursor-previous' };
const released = ['C:\\wechat-staged\\old-file.pdf'];
@@ -608,3 +660,20 @@ function blockingLiveTransport(): WechatTransport {
),
} as unknown as WechatTransport;
}
+
+function restoredConnection(queued: () => number) {
+ const credentials = { bindingEpoch: 'epoch', botToken: 'test-token', ilinkBotId: 'wechat-bot',
+ userId: 'owner', baseUrl: 'https://ilinkai.weixin.qq.com', boundAt: 1 };
+ const testHost = host({ secretRead: (name) => name === 'wechat_data_key_v1'
+ ? Buffer.alloc(32, 3).toString('base64') : name === 'wechat_credentials_epoch' ? JSON.stringify(credentials) : null });
+ const db = fakeDb({
+ queryOne: vi.fn(async (sql: string) => sql.includes('FROM wechat_sync_state')
+ ? { bindingEpoch: 'epoch', cursor: '' } : sql.includes('COUNT(*)') ? { count: queued() } : undefined) as DbClient['queryOne'],
+ query: vi.fn(async () => []),
+ tx: vi.fn(async (name: string) => name === 'wechatCommitPollBatch'
+ ? { committed: false, reason: 'stale-cursor' } : null),
+ });
+ const transport = blockingLiveTransport();
+ const im = new WechatIM(deps({ host: testHost, getDbClient: () => db, createTransport: () => transport }));
+ return { im, transport, db, testHost };
+}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts b/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts
index 2d841ab562..fb8d7bc4cf 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/channelSettings.test.ts
@@ -9,6 +9,7 @@ import {
resetWechatWorkingDir,
resolveWechatWorkingDir,
writeWechatWorkingDir,
+ writeWechatCompanionBinding,
} from '../channelSettings';
let root = '';
@@ -22,6 +23,25 @@ afterEach(() => {
});
describe('personal WeChat channel settings', () => {
+ // Teammate routing must survive changing/resetting the independent channel's directory.
+ // Existing directory-only cases did not cover this new persisted override (unit tier).
+ it('preserves teammate binding across directory changes and removes only the requested override', () => {
+ const selected = path.join(root, 'project');
+ fs.mkdirSync(selected);
+ writeWechatCompanionBinding('bot-cindy', root);
+ expect(writeWechatWorkingDir(selected, root).companionBotId).toBe('bot-cindy');
+ expect(resetWechatWorkingDir(root).companionBotId).toBe('bot-cindy');
+ writeWechatWorkingDir(selected, root);
+ const detached = writeWechatCompanionBinding(null, root);
+ expect(detached.companionBotId).toBeUndefined();
+ expect(detached.workingDir).toBe(fs.realpathSync.native(selected).replace(/\\/g, '/'));
+ });
+
+ it('rejects malformed teammate identities without replacing the existing binding', () => {
+ writeWechatCompanionBinding('bot-cindy', root);
+ expect(() => writeWechatCompanionBinding('../another', root)).toThrow('WECHAT_COMPANION_INVALID');
+ expect(readWechatChannelSettings(root).companionBotId).toBe('bot-cindy');
+ });
it('persists only a directory selected from an absolute existing path', () => {
const selected = path.join(root, 'project');
const replacement = path.join(root, 'replacement');
diff --git a/apps/desktop/src/main/im/wechat/adapter.ts b/apps/desktop/src/main/im/wechat/adapter.ts
index ca35e5200d..3483046f20 100644
--- a/apps/desktop/src/main/im/wechat/adapter.ts
+++ b/apps/desktop/src/main/im/wechat/adapter.ts
@@ -21,6 +21,9 @@ export function buildWechatAdapter(
},
config,
ui,
+ companionLane: (userId) => wechatIm.isOwner(userId)
+ ? { kind: 'owner-dm' }
+ : { kind: 'guest-dm', userId },
sessions: {
source: 'wechat',
sessionIdFor,
diff --git a/apps/desktop/src/main/im/wechat/channelSettings.ts b/apps/desktop/src/main/im/wechat/channelSettings.ts
index 37c2a7bdd9..79a4a5d775 100644
--- a/apps/desktop/src/main/im/wechat/channelSettings.ts
+++ b/apps/desktop/src/main/im/wechat/channelSettings.ts
@@ -20,6 +20,8 @@ const SETTINGS_VERSION = 1;
export interface WechatChannelSettings {
version: typeof SETTINGS_VERSION;
workingDir: string | null;
+ /** Absent means the original independent personal WeChat routing. */
+ companionBotId?: string;
}
export interface WechatChannelSettingsState extends WechatChannelSettings {
@@ -61,11 +63,16 @@ export function writeWechatWorkingDir(
rootPath?: string,
): WechatChannelSettingsState {
const workingDir = normalizeSelectedDirectory(selectedPath);
- writeSettings({ ...DEFAULTS, workingDir }, rootPath);
+ writeSettings({ ...normalizeSettings(readWechatChannelSettings(rootPath)), workingDir }, rootPath);
return readWechatChannelSettings(rootPath);
}
export function resetWechatWorkingDir(rootPath?: string): WechatChannelSettingsState {
+ const current = readWechatChannelSettings(rootPath);
+ if (current.companionBotId) {
+ writeSettings({ version: SETTINGS_VERSION, workingDir: null, companionBotId: current.companionBotId }, rootPath);
+ return readWechatChannelSettings(rootPath);
+ }
const file = settingsFilePath(rootPath);
try {
fs.rmSync(file, { force: true });
@@ -79,6 +86,19 @@ export function resetWechatWorkingDir(rootPath?: string): WechatChannelSettingsS
return { ...DEFAULTS, workingDirAvailable: true };
}
+export function writeWechatCompanionBinding(botId: string | null, rootPath?: string): WechatChannelSettingsState {
+ if (botId !== null && (typeof botId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(botId))) {
+ throw new Error('WECHAT_COMPANION_INVALID');
+ }
+ const current = readWechatChannelSettings(rootPath);
+ writeSettings({
+ version: SETTINGS_VERSION,
+ workingDir: current.workingDir,
+ ...(botId ? { companionBotId: botId } : {}),
+ }, rootPath);
+ return readWechatChannelSettings(rootPath);
+}
+
export function resolveWechatWorkingDir(botId: string, rootPath?: string): string {
const configured = readWechatChannelSettings(rootPath);
if (configured.workingDir && configured.workingDirAvailable) return configured.workingDir;
@@ -118,6 +138,8 @@ function normalizeSettings(raw: unknown): WechatChannelSettings {
return {
version: SETTINGS_VERSION,
workingDir,
+ ...(typeof input.companionBotId === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(input.companionBotId)
+ ? { companionBotId: input.companionBotId } : {}),
};
}
diff --git a/apps/desktop/src/main/im/wechat/index.ts b/apps/desktop/src/main/im/wechat/index.ts
index d3ce65bbb7..a1d027c386 100644
--- a/apps/desktop/src/main/im/wechat/index.ts
+++ b/apps/desktop/src/main/im/wechat/index.ts
@@ -3,9 +3,12 @@ import { createImOrchestrator } from '../shared/orchestrator';
import { resetImSessionToChannelDefaults } from '../shared/channelDefaultRouteSync';
import { buildWechatAdapter } from './adapter';
import type { WechatIM } from './WechatIM';
+import { readWechatChannelSettings } from './channelSettings';
export function wireWechatOrchestrator(wechatIm: WechatIM, config: ImOrchestratorConfig): void {
- const orchestrator = createImOrchestrator(buildWechatAdapter(wechatIm, config));
+ const orchestrator = createImOrchestrator(buildWechatAdapter(wechatIm, config), {
+ companionBotId: () => readWechatChannelSettings().companionBotId ?? null,
+ });
wechatIm.attachTurnRuntime({
runner: orchestrator.turnRunner,
repo: orchestrator.repo,
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 6b8d8c5285..b7296ccbc6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -668,6 +668,7 @@ const fanOutDingTalkBotOwnerChange = createIpcFanOut('dingtalkBot:owner-change')
const fanOutWecomBotStatusChange = createIpcFanOut('wecomBot:status-changed');
// Personal WeChat: main owns auth/polling and broadcasts a credential-free state snapshot.
const fanOutWechatBotStateChange = createIpcFanOut('wechatBot:state-changed');
+const fanOutWechatChannelSettingsChange = createIpcFanOut('wechatBot:channel-settings-changed');
const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');
const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut(
'voice-input:global-shortcut-trigger',
@@ -2563,18 +2564,22 @@ contextBridge.exposeInMainWorld('electronAPI', {
getChannelSettings: (): Promise<{
version: 1;
workingDir: string | null;
- workingDirAvailable: boolean;
+ workingDirAvailable: boolean; companionBotId?: string;
}> => ipcRenderer.invoke('wechatBot:get-channel-settings'),
+ setCompanion: (botId: string | null): Promise<{
+ version: 1; workingDir: string | null; workingDirAvailable: boolean; companionBotId?: string;
+ }> => ipcRenderer.invoke('wechatBot:set-companion', botId),
chooseWorkingDirectory: (): Promise<{
canceled: boolean;
- state: { version: 1; workingDir: string | null; workingDirAvailable: boolean };
+ state: { version: 1; workingDir: string | null; workingDirAvailable: boolean; companionBotId?: string };
}> => ipcRenderer.invoke('wechatBot:choose-working-directory'),
resetWorkingDirectory: (): Promise<{
version: 1;
workingDir: string | null;
- workingDirAvailable: boolean;
+ workingDirAvailable: boolean; companionBotId?: string;
}> => ipcRenderer.invoke('wechatBot:reset-working-directory'),
onStateChange: fanOutWechatBotStateChange,
+ onChannelSettingsChange: fanOutWechatChannelSettingsChange,
},
// Renderer → main 的 "用户已登录 + localDb 已就绪" 信号。LocalDbGate 在
diff --git a/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
index f67da4289e..5842dc9b49 100644
--- a/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WechatBotSection.tsx
@@ -44,9 +44,11 @@ function statusTextColor(phase: WechatBotPhase): string {
export function WechatBotSection({
expanded,
onToggle,
+ companion,
}: {
expanded: boolean;
onToggle: () => void;
+ companion?: { id: string; name: string };
}) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
@@ -61,8 +63,13 @@ export function WechatBotSection({
unbind,
chooseWorkingDirectory,
resetWorkingDirectory,
+ setCompanion,
+ isUpdatingCompanion,
} = useWechatBot();
const [routeSummary, setRouteSummary] = useImChannelSettingsSummary('wechat');
+ const assigned = channelSettings?.companionBotId;
+ const otherCompanion = !!companion && !!assigned && assigned !== companion.id;
+ const needsAssignment = !!companion && assigned !== companion.id;
const authorizationSteps = (
<ol className="mt-1 grid gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 leading-[1.55] text-[var(--text-secondary)]">
@@ -94,8 +101,11 @@ export function WechatBotSection({
maxWidth: 440,
autoFocusConfirm: true,
});
- if (accepted) await authorize();
- }, [authorizationSteps, authorize, confirm, state.bound, t]);
+ if (accepted) {
+ if (companion && !(await setCompanion(companion.id))) return;
+ await authorize();
+ }
+ }, [authorizationSteps, authorize, companion, confirm, setCompanion, state.bound, t]);
const handleUnbind = useCallback(async () => {
const accepted = await confirm({
@@ -113,13 +123,13 @@ export function WechatBotSection({
return (
<ImChannelSettingsCard
- id="personal-im-wechat"
+ id={companion ? 'companion-im-wechat' : 'personal-im-wechat'}
title={t('settings.wechatBot.title')}
description={t('settings.wechatBot.description')}
routeSummary={
- routeSummary
- ? `${t(`settings.imBot.defaults.agents.${routeSummary.agentKind}`)} · ${routeSummary.model}`
- : null
+ companion ? (assigned === companion.id ? companion.name : null)
+ : assigned ? t('settings.wechatBot.companion.assigned')
+ : routeSummary ? `${t(`settings.imBot.defaults.agents.${routeSummary.agentKind}`)} · ${routeSummary.model}` : null
}
expanded={expanded}
onToggle={onToggle}
@@ -146,6 +156,29 @@ export function WechatBotSection({
</span>
}
>
+ {companion || assigned ? (
+ <div className="flex flex-col items-start gap-3">
+ <p className="text-13 leading-[1.5] text-[var(--text-secondary)]">
+ {t(otherCompanion ? 'settings.wechatBot.companion.other'
+ : companion ? 'settings.wechatBot.companion.description' : 'settings.wechatBot.companion.assigned',
+ { name: companion?.name })}
+ </p>
+ <p className="text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {t('settings.wechatBot.companion.permissionNote')}
+ </p>
+ {!otherCompanion && assigned ? (
+ <Button variant="secondary" size="sm" loading={isUpdatingCompanion}
+ onClick={() => void setCompanion(null)}>
+ {t('settings.wechatBot.companion.remove')}
+ </Button>
+ ) : !otherCompanion && state.bound && companion ? (
+ <Button variant="secondary" size="sm" loading={isUpdatingCompanion}
+ disabled={!channelSettings} onClick={() => void setCompanion(companion.id)}>
+ {t('settings.wechatBot.companion.useExisting', { name: companion.name })}
+ </Button>
+ ) : null}
+ </div>
+ ) : <>
<ImDefaultSettingsSection channel="wechat" embedded onSummaryChange={setRouteSummary} />
<div className="h-px w-full bg-[var(--border-default)]" />
@@ -156,10 +189,11 @@ export function WechatBotSection({
onChoose={() => void chooseWorkingDirectory()}
onReset={() => void resetWorkingDirectory()}
/>
+ </>}
<div className="h-px w-full bg-[var(--border-default)]" />
- {authorizationPending ? (
+ {otherCompanion || (needsAssignment && state.bound) ? null : authorizationPending ? (
<div className="flex flex-col items-center gap-3 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] px-5 py-6 text-center">
<span className="inline-flex animate-spin text-[var(--text-secondary)] motion-reduce:animate-none">
<Loader2 size={22} />
@@ -207,7 +241,7 @@ export function WechatBotSection({
loading={isAuthorizing}
type="button"
onClick={() => void handleAuthorize()}
- disabled={isAuthorizing || disabledByPolicy}
+ disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}
className="flex-1"
>
<RotateCw size={13} />
@@ -246,7 +280,7 @@ export function WechatBotSection({
loading={isAuthorizing}
type="button"
onClick={() => void handleAuthorize()}
- disabled={isAuthorizing || disabledByPolicy}
+ disabled={isAuthorizing || isUpdatingCompanion || !channelSettings || disabledByPolicy}
className="w-full"
>
{t('settings.wechatBot.actions.connect')}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx
index 110bd325dd..649b8f8687 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WechatBotSection.test.tsx
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
unbind: vi.fn(),
chooseWorkingDirectory: vi.fn(),
resetWorkingDirectory: vi.fn(),
+ setCompanion: vi.fn(),
+ companionBotId: undefined as string | undefined,
state: {
phase: 'disconnected',
bound: false,
@@ -35,6 +37,7 @@ vi.mock('@/hooks/useWechatBot', () => ({
version: 1,
workingDir: null,
workingDirAvailable: true,
+ companionBotId: mocks.companionBotId,
},
isAuthorizing: false,
isUnbinding: false,
@@ -44,6 +47,8 @@ vi.mock('@/hooks/useWechatBot', () => ({
unbind: mocks.unbind,
chooseWorkingDirectory: mocks.chooseWorkingDirectory,
resetWorkingDirectory: mocks.resetWorkingDirectory,
+ setCompanion: mocks.setCompanion,
+ isUpdatingCompanion: false,
}),
}));
@@ -81,6 +86,36 @@ describe('WechatBotSection', () => {
mocks.confirm.mockResolvedValue(true);
mocks.authorize.mockResolvedValue(true);
mocks.unbind.mockResolvedValue(true);
+ mocks.companionBotId = undefined;
+ mocks.setCompanion.mockResolvedValue(true);
+ });
+
+ // The teammate entry must use the existing authorization and binding APIs, without
+ // exposing independent model defaults or replacing another teammate's connection.
+ it('adopts an already connected WeChat account without reauthorizing it', async () => {
+ mocks.state = { phase: 'connected', bound: true, queuedTasks: 0 };
+ render(<WechatBotSection expanded onToggle={vi.fn()} companion={{ id: 'bot-cindy', name: 'Cindy' }} />);
+ expect(screen.queryByTestId('defaults')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.companion.useExisting' }));
+ await waitFor(() => expect(mocks.setCompanion).toHaveBeenCalledWith('bot-cindy'));
+ expect(mocks.authorize).not.toHaveBeenCalled();
+ expect(mocks.unbind).not.toHaveBeenCalled();
+ });
+
+ it('does not expose authorization or unbind controls for another teammate', () => {
+ mocks.state = { phase: 'connected', bound: true, queuedTasks: 0 };
+ mocks.companionBotId = 'bot-other';
+ render(<WechatBotSection expanded onToggle={vi.fn()} companion={{ id: 'bot-cindy', name: 'Cindy' }} />);
+ expect(screen.getByText('settings.wechatBot.companion.other')).toBeTruthy();
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('does not open authorization if assigning the teammate fails', async () => {
+ mocks.setCompanion.mockResolvedValue(false);
+ render(<WechatBotSection expanded onToggle={vi.fn()} companion={{ id: 'bot-cindy', name: 'Cindy' }} />);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.wechatBot.actions.connect' }));
+ await waitFor(() => expect(mocks.setCompanion).toHaveBeenCalledWith('bot-cindy'));
+ expect(mocks.authorize).not.toHaveBeenCalled();
});
it('explains the external Tencent authorization flow before starting it', async () => {
diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
index c8e854be62..4530401694 100644
--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx
@@ -19,6 +19,7 @@ import { Input } from '@/components/ui/input';
import { SegmentedControl } from '@/components/ui/segmented-control';
import { Select } from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
+import { WechatBotSection } from '@/components/settings/WechatBotSection';
import { cn } from '@/lib/utils';
import { formatRelative } from '@/hooks/useRelativeTime';
import { extractIpcError } from '@/utils/ipcError';
@@ -104,6 +105,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {
const { payload, loading, apply } = useBotImConnections();
const { confirm } = useConfirmDialog();
const [adding, setAdding] = useState(false);
+ const [wechatExpanded, setWechatExpanded] = useState(false);
const [removingId, setRemovingId] = useState<string | null>(null);
const mine = (payload?.connections ?? []).filter((item) => item.botId === bot.id);
@@ -226,6 +228,10 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {
{t('bots.channels.add.button')}
</Button>
</div>
+ {typeof window.electronAPI.wechatBot?.setCompanion === 'function' ? (
+ <WechatBotSection companion={{ id: bot.id, name: bot.name }} expanded={wechatExpanded}
+ onToggle={() => setWechatExpanded((expanded) => !expanded)} />
+ ) : null}
<p className="px-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
{t('bots.channels.externalNote', { name: bot.name })}
</p>
diff --git a/apps/desktop/src/renderer/hooks/useWechatBot.ts b/apps/desktop/src/renderer/hooks/useWechatBot.ts
index 6b64191c38..aabb9f832b 100644
--- a/apps/desktop/src/renderer/hooks/useWechatBot.ts
+++ b/apps/desktop/src/renderer/hooks/useWechatBot.ts
@@ -26,6 +26,8 @@ export interface UseWechatBotReturn {
unbind: () => Promise<boolean>;
chooseWorkingDirectory: () => Promise<void>;
resetWorkingDirectory: () => Promise<void>;
+ setCompanion: (botId: string | null) => Promise<boolean>;
+ isUpdatingCompanion: boolean;
}
export function useWechatBot(): UseWechatBotReturn {
@@ -37,7 +39,10 @@ export function useWechatBot(): UseWechatBotReturn {
const [isAuthorizing, setIsAuthorizing] = useState(false);
const [isUnbinding, setIsUnbinding] = useState(false);
const [isUpdatingWorkingDir, setIsUpdatingWorkingDir] = useState(false);
+ const [isUpdatingCompanion, setIsUpdatingCompanion] = useState(false);
const pushVersionRef = useRef(0);
+ const settingsVersionRef = useRef(0);
+ const companionBusyRef = useRef(false);
useEffect(() => {
let cancelled = false;
@@ -47,7 +52,14 @@ export function useWechatBot(): UseWechatBotReturn {
cachedState = next;
setState(next);
});
+ const unsubscribeSettings = window.electronAPI.wechatBot.onChannelSettingsChange?.((settings) => {
+ if (cancelled) return;
+ settingsVersionRef.current += 1;
+ cachedChannelSettings = settings;
+ setChannelSettings(settings);
+ });
const initialPushVersion = pushVersionRef.current;
+ const initialSettingsVersion = settingsVersionRef.current;
void Promise.all([
window.electronAPI.wechatBot.getState(),
window.electronAPI.wechatBot.getChannelSettings(),
@@ -58,8 +70,10 @@ export function useWechatBot(): UseWechatBotReturn {
cachedState = nextState;
setState(nextState);
}
- cachedChannelSettings = nextChannelSettings;
- setChannelSettings(nextChannelSettings);
+ if (settingsVersionRef.current === initialSettingsVersion) {
+ cachedChannelSettings = nextChannelSettings;
+ setChannelSettings(nextChannelSettings);
+ }
})
.catch(() => {
if (cancelled) return;
@@ -68,6 +82,7 @@ export function useWechatBot(): UseWechatBotReturn {
return () => {
cancelled = true;
unsubscribe();
+ unsubscribeSettings?.();
};
}, []);
@@ -143,6 +158,25 @@ export function useWechatBot(): UseWechatBotReturn {
}
}, [isUpdatingWorkingDir, t]);
+ const setCompanion = useCallback(async (botId: string | null): Promise<boolean> => {
+ if (companionBusyRef.current) return false;
+ companionBusyRef.current = true;
+ setIsUpdatingCompanion(true);
+ try {
+ const next = await window.electronAPI.wechatBot.setCompanion(botId);
+ settingsVersionRef.current += 1;
+ cachedChannelSettings = next;
+ setChannelSettings(next);
+ return true;
+ } catch {
+ toast.error(t('settings.wechatBot.companion.updateFailed'));
+ return false;
+ } finally {
+ companionBusyRef.current = false;
+ setIsUpdatingCompanion(false);
+ }
+ }, [t]);
+
return {
state,
channelSettings,
@@ -154,6 +188,8 @@ export function useWechatBot(): UseWechatBotReturn {
unbind,
chooseWorkingDirectory,
resetWorkingDirectory,
+ setCompanion,
+ isUpdatingCompanion,
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8059012e83..8cc3c010c9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3962,6 +3962,15 @@
"workingDirSaved": "Working directory for new WeChat conversations updated",
"workingDirReset": "New WeChat conversations now use the default directory",
"workingDirFailed": "Could not update the working directory. Select it again."
+ },
+ "companion": {
+ "assigned": "Replies come from the linked teammate",
+ "description": "Chat with {{name}} on WeChat, sharing memory and the main task. This computer’s WeChat connection can belong to one teammate at a time.",
+ "other": "WeChat is linked to another teammate. Remove that link in their connection settings or Personal WeChat settings first.",
+ "permissionNote": "WeChat keeps per-action permission checks. Choose Claude Code or Codex for this teammate, with Auto-review or Ask permissions.",
+ "remove": "Remove teammate link",
+ "useExisting": "Use connected WeChat with {{name}}",
+ "updateFailed": "Could not update the link. Wait for WeChat tasks to finish, then retry and check that the teammate is available."
}
},
"discordBot": {
@@ -9952,7 +9961,7 @@
},
"remove": "Remove",
"removeAria": "Remove {{platform}}",
- "empty": "{{name}} has no messaging platform yet. Add a bot you created on Telegram, Feishu, WeCom, DingTalk or Discord, and {{name}} will reply there.",
+ "empty": "Add a bot you already have, or connect personal WeChat below, and {{name}} will reply there.",
"externalNote": "Anyone who messages this bot is talking to {{name}}. Your own messages run with {{name}}’s permissions; everyone else gets a separate hidden task with restricted permissions.",
"sharedMemoryNote": "{{name}} uses information from here and from other conversations together. To keep memories separate, use another teammate.",
"groups": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index dfdc6ea1e0..9f8c4de960 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3931,6 +3931,15 @@
"workingDirSaved": "WeChat の新しい会話の作業ディレクトリを更新しました",
"workingDirReset": "WeChat の新しい会話はデフォルトディレクトリを使用します",
"workingDirFailed": "作業ディレクトリを更新できませんでした。もう一度選択してください。"
+ },
+ "companion": {
+ "assigned": "連携したチームメイトが返信します",
+ "description": "WeChat で {{name}} と話し、記憶とメインタスクを共有します。このパソコンの WeChat 接続を連携できるチームメイトは一度に 1 人です。",
+ "other": "WeChat は別のチームメイトと連携しています。そのチームメイトの接続設定、または個人 WeChat の設定で先に連携を解除してください。",
+ "permissionNote": "WeChat では操作ごとの権限確認を維持します。チームメイトに Claude Code または Codex を選び、権限を自動審査または確認に設定してください。",
+ "remove": "チームメイトとの連携を解除",
+ "useExisting": "接続済みの WeChat で {{name}} と話す",
+ "updateFailed": "連携を更新できませんでした。WeChat のタスクが終わってから再試行し、チームメイトが利用可能か確認してください。"
}
},
"discordBot": {
@@ -9913,7 +9922,7 @@
},
"remove": "削除",
"removeAria": "{{platform}} を削除",
- "empty": "{{name}} にはまだメッセージプラットフォームがありません。Telegram、飛書、WeCom、DingTalk、Discord で作成したボットを追加すると、{{name}} がそこで返信します。",
+ "empty": "既存のボットを追加するか、下で個人用 WeChat を接続すると、{{name}} がそこで返信します。",
"externalNote": "このボットにメッセージを送る人は全員 {{name}} と話すことになります。あなた自身のメッセージは {{name}} の権限で実行され、それ以外の人には権限を制限した非表示のタスクが個別に用意されます。",
"sharedMemoryNote": "{{name}} はここでの情報と他の会話の情報をまとめて使います。記憶を分けたい場合は別の仲間を使ってください。",
"groups": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f06b817167..c9ec8419a9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3931,6 +3931,15 @@
"workingDirSaved": "WeChat 새 대화 작업 디렉터리가 업데이트되었습니다",
"workingDirReset": "WeChat 새 대화가 기본 디렉터리를 사용합니다",
"workingDirFailed": "작업 디렉터리를 업데이트하지 못했습니다. 다시 선택하세요."
+ },
+ "companion": {
+ "assigned": "연결된 팀메이트가 답장합니다",
+ "description": "WeChat에서 {{name}}와 대화하며 기억과 기본 작업을 공유합니다. 이 컴퓨터의 WeChat 연결은 한 번에 한 팀메이트에게만 연결할 수 있습니다.",
+ "other": "WeChat이 다른 팀메이트에게 연결되어 있습니다. 해당 팀메이트의 연결 설정이나 개인 WeChat 설정에서 먼저 연결을 해제하세요.",
+ "permissionNote": "WeChat은 작업별 권한 확인을 유지합니다. 팀메이트에 Claude Code 또는 Codex를 선택하고 권한을 자동 검토 또는 확인으로 설정하세요.",
+ "remove": "팀메이트 연결 해제",
+ "useExisting": "연결된 WeChat으로 {{name}}와 대화",
+ "updateFailed": "연결을 변경하지 못했습니다. WeChat 작업이 끝난 뒤 다시 시도하고 팀메이트를 사용할 수 있는지 확인하세요."
}
},
"discordBot": {
@@ -9913,7 +9922,7 @@
},
"remove": "제거",
"removeAria": "{{platform}} 제거",
- "empty": "{{name}}에게는 아직 메시지 플랫폼이 없습니다. Telegram, Feishu, WeCom, DingTalk, Discord에서 만든 봇을 추가하면 {{name}}이(가) 그곳에서 답합니다.",
+ "empty": "기존 봇을 추가하거나 아래에서 개인 WeChat을 연결하면 {{name}}이 그곳에서 답장합니다.",
"externalNote": "이 봇에게 메시지를 보내는 사람은 모두 {{name}}과(와) 대화하게 됩니다. 내 메시지는 {{name}}의 권한으로 실행되고, 다른 사람에게는 권한이 제한된 숨겨진 작업이 따로 만들어집니다.",
"sharedMemoryNote": "{{name}}은(는) 여기의 정보와 다른 대화의 정보를 함께 사용합니다. 기억을 분리하려면 다른 동료를 사용하세요.",
"groups": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 92263d3a19..638a8f2714 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3931,6 +3931,15 @@
"workingDirSaved": "微信新对话工作目录已更新",
"workingDirReset": "微信新对话已恢复使用默认目录",
"workingDirFailed": "更新工作目录失败,请重新选择"
+ },
+ "companion": {
+ "assigned": "由绑定的伙伴回复",
+ "description": "在微信中与 {{name}} 对话,共用记忆和主任务。此电脑上的微信连接一次只能交给一位伙伴。",
+ "other": "微信已交给另一位伙伴。请先在该伙伴的连接设置或个人微信设置中移除绑定。",
+ "permissionNote": "微信继续使用逐次权限确认。请为伙伴选择 Claude Code 或 Codex,并使用自动审查或询问模式。",
+ "remove": "移除伙伴绑定",
+ "useExisting": "使用已连接的微信与 {{name}} 对话",
+ "updateFailed": "未能更新绑定。请等待微信中的任务结束后重试,并确认伙伴仍可用。"
}
},
"discordBot": {
@@ -9913,7 +9922,7 @@
},
"remove": "移除",
"removeAria": "移除 {{platform}}",
- "empty": "{{name}} 还没有消息平台。把你在 Telegram、飞书、企业微信、钉钉或 Discord 申请的机器人加进来,{{name}} 就会在那里回复。",
+ "empty": "把你已有的机器人添加到平台,或在下方连接个人微信,{{name}} 就会在那里回复。",
"externalNote": "给这个机器人发消息的人都是在和 {{name}} 对话。你自己的消息按 {{name}} 的权限执行;其他人各有一条隐藏任务,权限受限。",
"sharedMemoryNote": "{{name}} 会把这里和其它对话里的信息放在一起用。想隔开记忆,请换一位伙伴。",
"groups": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 41c838463c..a22957bb7d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3931,6 +3931,15 @@
"workingDirSaved": "微信新對話工作目錄已更新",
"workingDirReset": "微信新對話已恢復使用預設目錄",
"workingDirFailed": "更新工作目錄失敗,請重新選擇"
+ },
+ "companion": {
+ "assigned": "由綁定的夥伴回覆",
+ "description": "在微信中與 {{name}} 對話,共用記憶和主要任務。此電腦上的微信連線一次只能交給一位夥伴。",
+ "other": "微信已交給另一位夥伴。請先在該夥伴的連線設定或個人微信設定中移除綁定。",
+ "permissionNote": "微信繼續使用逐次權限確認。請為夥伴選擇 Claude Code 或 Codex,並使用自動審查或詢問模式。",
+ "remove": "移除夥伴綁定",
+ "useExisting": "使用已連線的微信與 {{name}} 對話",
+ "updateFailed": "無法更新綁定。請等微信中的工作結束後重試,並確認夥伴仍可用。"
}
},
"discordBot": {
@@ -9913,7 +9922,7 @@
},
"remove": "移除",
"removeAria": "移除 {{platform}}",
- "empty": "{{name}} 還沒有訊息平台。把你在 Telegram、飛書、企業微信、釘釘或 Discord 申請的機器人加進來,{{name}} 就會在那裡回覆。",
+ "empty": "新增你已有的機器人,或在下方連接個人微信,{{name}} 就會在那裡回覆。",
"externalNote": "傳訊息給這個機器人的人都是在和 {{name}} 對話。你自己的訊息依 {{name}} 的權限執行;其他人各有一條隱藏任務,權限受限。",
"sharedMemoryNote": "{{name}} 會把這裡和其它對話裡的資訊一起使用。想隔開記憶,請換一位夥伴。",
"groups": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 9ea64823c7..34b9d7bd8f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -527,6 +527,7 @@ interface WechatChannelSettingsState {
version: 1;
workingDir: string | null;
workingDirAvailable: boolean;
+ companionBotId?: string;
}
type DiscordBotSessionAuthCheckResult = {
@@ -2439,6 +2440,8 @@ interface ElectronAPI {
cancelAuthorization: () => Promise<{ ok: true }>;
unbind: () => Promise<{ ok: true }>;
getChannelSettings: () => Promise<WechatChannelSettingsState>;
+ setCompanion: (botId: string | null) => Promise<WechatChannelSettingsState>;
+ onChannelSettingsChange: (callback: (state: WechatChannelSettingsState) => void) => () => void;
chooseWorkingDirectory: () => Promise<{
canceled: boolean;
state: WechatChannelSettingsState;
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index c2a2da66dc..1ffe82a9b1 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -56,7 +56,10 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或
再走同一个 `addBotImConnection`;成功后个人 bot 清空(设置页按既有广播显示未配置),失败则把个人 bot 的凭证原样写回并
重新起来。随连接带过去的:Telegram / Discord 的主人 id、企业微信 / 钉钉 / 飞书已认定的主人(不再重新 TOFU)、
Telegram 设为全响应的群;设置页的人格与行为配置不带。移过去之后没有共用,想再要个人 bot 需另配一个。
-个人微信不在此列:它是扫码绑定用户本人账号的服务端通道,不是用户申请的机器人。
+个人微信复用既有扫码授权通道:伙伴设置「消息平台」可连接或接管当前个人微信,单个本地账号只绑定一位伙伴;
+绑定只保存伙伴归属,不复制凭证、不创建第二份轮询。主人私聊进入主任务,其他私聊进入渠道专线。
+解除伙伴关联恢复个人微信独立路由,保留微信授权与原工作目录;有排队消息或运行中的任务时拒绝切换。
+微信仍沿用渠道的逐轮权限确认约束,模型需为 Claude Code / Codex,权限需为自动审查或询问。
每条连接一份传输层实例(复用个人 bot 的各渠道适配器,凭证按连接 id 前缀隔离在本机安全存储),
它说什么、记得什么、会什么、用什么模型,全部来自伙伴。主人私聊进该伙伴的 canonical 主任务;每个群 / 话题与
每位外部用户的私聊各一条隐藏的渠道专线 Session(`role = 'channel'`,