Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bots): 导入伙伴时消息机器人单独勾选,并从原 Agent 停用后由伙伴接管
Chris1864b3b0ad78
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.mdindex 448436505a..3284cd0f01 100644--- a/apps/desktop/src/main/bot-import/README.md+++ b/apps/desktop/src/main/bot-import/README.md@@ -427,7 +427,54 @@ runtime interpreter parses the selected script without executing business actionThis checks availability and syntax, not a full business execution; scripts withexternal data still require actual read evidence.-## Telegram and Discord bots become the teammate's own connections+## Messaging bots move to the teammate (`companion-import-bots-v1`)++Controllers that advertise `companion-import-bots-v1` (the local renderer and+`import_agent` always do; Mobile sends it) get a separate `bots` category:+`inspectImportSource(..., { bots: true })` emits one entry per bot with `platform`, the most+human name available and, when evident, `owner`. Hermes covers Telegram, Discord, Feishu /+Lark, WeCom and DingTalk (env first, then `platforms.<name>.extra`); OpenClaw covers+Telegram, Discord and Feishu with OpenClaw's own account inheritance, and lists a bot only+for the agent its account routes to (a channel-wide binding, else the default agent). A bot+that other agents also route through is listed unselected. OpenClaw WeCom / DingTalk are+external plugins without a known config shape and are not read. A platform the source has+disabled is listed unselected and shown as already off.++Owners: Telegram uses the single allowed user, else the allowed user that is the home+channel, else the only admin who is also allowed; Discord the single allowed user; Feishu+the single `ou_` admin (Hermes) or the single `feishu:` owner / allowFrom entry (OpenClaw);+WeCom / DingTalk only a single explicit allowed user. Two to five Telegram / Discord+candidates become exclusive per-owner alternatives with none preselected; none or more than+five gives one entry with `IMPORT_IM_BOT_OWNER_MISSING`.++`botTakeover.ts` runs the handover from the transfer's connections pass, after the teammate+exists and the environment is saved. It persists `receipt.bots[entryId]` (`stopping` →+`stopped` → `connected`, the original switch value, whether it was live, whether it+restarted) before and after each native mutation, mirroring the automation `phase`:++1. An existing connection for the same platform identity on this teammate completes the+ entry; one on another teammate returns `IMPORT_IM_BOT_IN_USE`.+2. A fresh attempt first runs `assertBotImConnectionAddable`, so nothing is stopped for a+ teammate that could not take the bot.+3. The switch is turned off with the source's own command (Hermes+ `config set platforms.<name>.enabled false`; OpenClaw `config patch --stdin` on the+ account or channel `enabled`) and re-read; an unconfirmed change returns+ `IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED` without connecting.+4. A live Hermes bot (`gateway_state.json`, including the host's `<profile>:<platform>`+ entry, with a running writer) gets `gateway restart`, never for a parked profile (a+ restart would unpark it); then `gateway_state.json` is polled about every 2 s for up to+ 120 s. A bot that is still live keeps the switch off and returns+ `IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED`. OpenClaw relies on hot reload with a 3 s settle.+5. The connection is added through `addBotImConnection` (owner carried for Feishu / WeCom /+ DingTalk, the 5 s Telegram conflict window). If it fails, the original switch is restored+ (unset when it was absent) and a restarted gateway is restarted again.++Background reconciliation resumes an interrupted takeover but never retries a reported+outcome; an explicit retry resumes from the saved record. A missing CLI returns+`SOURCE_COMMAND_UNAVAILABLE`. Commands never carry credentials. Deleting the teammate does+not re-enable bots in the source.++## Telegram and Discord bots become the teammate's own connections (legacy controllers)`sources.ts` reads Telegram tokens (`channels.telegram[.accounts.<id>].botToken` or`tokenFile`; Hermes `TELEGRAM_BOT_TOKEN`) and Discord tokens (`channels.discord[.accounts.<id>].token`,diff --git a/apps/desktop/src/main/bot-import/__tests__/botTakeover.test.ts b/apps/desktop/src/main/bot-import/__tests__/botTakeover.test.tsnew file mode 100644index 0000000000..e56dffc724--- /dev/null+++ b/apps/desktop/src/main/bot-import/__tests__/botTakeover.test.ts@@ -0,0 +1,146 @@+import { afterEach, expect, it, vi } from 'vitest';+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { discoverImportSources, inspectImportSource } from '../sources.js';+import { takeOverImportedBot, type ImportBotRecord } from '../botTakeover.js';+import type { ImportedImBotTarget } from '../imBotConnections.js';++// Fake native CLIs only: the host's real hermes / openclaw are never reachable (home/.local/bin is searched first).+const FAKE = `+const fs = require('node:fs'), path = require('node:path');+const home = process.env.HERMES_HOME || process.env.OPENCLAW_STATE_DIR;+const file = process.env.OPENCLAW_CONFIG_PATH || path.join(home, 'config.yaml');+const args = process.argv.slice(2);+fs.appendFileSync(path.join(home, 'cli.log'), JSON.stringify(args) + '\\n');+if (fs.existsSync(path.join(home, 'fail-config')) && args[0] === 'config') process.exit(1);+const config = JSON.parse(fs.readFileSync(file, 'utf8'));+const walk = keys => keys.reduce((node, key) => (node[key] ??= {}), config);+if (args[0] === 'config' && args[1] === 'set') { const keys = args[2].split('.'); walk(keys.slice(0, -1))[keys.at(-1)] = args[3] === 'true' ? true : args[3] === 'false' ? false : args[3]; }+else if (args[0] === 'config' && args[1] === 'unset') { const keys = args[2].split('.'); delete walk(keys.slice(0, -1))[keys.at(-1)]; }+else if (args[0] === 'config' && args[1] === 'patch') {+ const merge = (node, patch) => { for (const [key, value] of Object.entries(patch)) { if (value === null) delete node[key]; else if (typeof value === 'object') merge(node[key] ??= {}, value); else node[key] = value; } };+ merge(config, JSON.parse(fs.readFileSync(0, 'utf8')));+} else if (args[0] === 'gateway' && args[1] === 'restart') {+ const stateFile = path.join(home, 'gateway_state.json');+ if (!fs.existsSync(path.join(home, 'restart-keeps-live'))) {+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));+ for (const [name, platform] of Object.entries(state.platforms)) if (config.platforms?.[name]?.enabled === false) platform.state = 'disconnected';+ fs.writeFileSync(stateFile, JSON.stringify(state));+ }+ process.exit(0);+} else process.exit(2);+fs.writeFileSync(file, JSON.stringify(config));+`;++let root: string;+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(root, { recursive: true, force: true }); });++async function setup(kind: 'hermes' | 'openclaw', config: Record<string, unknown>, options: { profile?: string; live?: boolean; parked?: boolean; env?: string } = {}) {+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-bot-takeover-test-'));+ const host = path.join(root, `.${kind}`);+ const state = options.profile ? path.join(host, 'profiles', options.profile) : host;+ const bin = path.join(root, '.local', 'bin');+ await fs.mkdir(state, { recursive: true }); await fs.mkdir(bin, { recursive: true });+ await fs.writeFile(path.join(host, kind === 'hermes' ? 'config.yaml' : 'openclaw.json'), JSON.stringify(options.profile ? {} : config));+ if (options.profile) await fs.writeFile(path.join(state, 'config.yaml'), JSON.stringify(config));+ if (options.env) await fs.writeFile(path.join(state, '.env'), options.env);+ if (options.parked) await fs.writeFile(path.join(state, 'gateway.parked'), '');+ // A named profile is served by the host gateway under "<profile>:<platform>".+ const key = options.profile ? `${options.profile}:telegram` : 'telegram';+ await fs.writeFile(path.join(host, 'gateway_state.json'), JSON.stringify({ pid: process.pid, platforms: { [key]: { state: options.live ? 'connected' : 'disconnected', writer_pid: process.pid } } }));+ await fs.writeFile(path.join(bin, kind), `#!${process.execPath}\n${FAKE}`, { mode: 0o700 });+ const readers = { home: root, env: { PATH: path.join(root, 'empty-path') }, readCronDatabase: async () => [] };+ const source = (await discoverImportSources(readers)).find(item => item.agentId === (options.profile ?? (kind === 'hermes' ? 'default' : 'main')))!;+ const item = (await inspectImportSource(source, readers, undefined, { bots: true })).items.find(entry => entry.view.category === 'bots')!;+ const saves: Array<ImportBotRecord | undefined> = [];+ const target = { channel: 'telegram' as const, existing: vi.fn<ImportedImBotTarget['existing']>(() => undefined),+ preflight: vi.fn(async () => undefined), connect: vi.fn<ImportedImBotTarget['connect']>(async () => undefined) };+ const sleep = vi.fn(async () => {});+ let clock = 0;+ const run = (record?: ImportBotRecord, timing = {}) => takeOverImportedBot({ source, item, target, record, readers, assertOwner: () => {},+ save: async next => { saves.push(next); }, timing: { pollMs: 2_000, timeoutMs: 6_000, settleMs: 3_000, sleep, now: () => (clock += 1_000), ...timing } });+ const readConfig = async () => JSON.parse(await fs.readFile(kind === 'hermes' ? path.join(state, 'config.yaml') : path.join(host, 'openclaw.json'), 'utf8'));+ const calls = async () => (await fs.readFile(path.join(state, 'cli.log'), 'utf8').catch(() => '')).trim().split('\n').filter(Boolean).map(line => JSON.parse(line).join(' '));+ return { state, host, item, target, saves, sleep, run, readConfig, calls };+}++const telegramEnv = 'TELEGRAM_BOT_TOKEN=12345:fake-telegram-token\nTELEGRAM_ALLOWED_USERS=424242';++it('stops a live Hermes bot, restarts the gateway, waits for it to let go, then connects', async () => {+ const t = await setup('hermes', { name: 'Ada' }, { live: true, env: telegramEnv });+ expect(await t.run()).toBeUndefined();+ expect(await t.calls()).toEqual(['config set platforms.telegram.enabled false', 'gateway restart']);+ expect((await t.readConfig()).platforms.telegram.enabled).toBe(false);+ expect(t.target.connect).toHaveBeenCalledTimes(1);+ expect(t.saves.map(record => record?.phase)).toEqual(['stopping', 'stopping', 'stopped', 'stopped', 'connected']);+ expect(t.saves.at(-1)).toEqual({ phase: 'connected', original: { present: false }, wasLive: true, changed: true, restarted: true });+ for (const call of await t.calls()) expect(call).not.toContain('fake-telegram-token');+});++it('never restarts a parked Hermes profile and waits for the host to drop the bot', async () => {+ const t = await setup('hermes', { name: 'Family' }, { profile: 'family', parked: true, live: true, env: telegramEnv });+ // The host rescan drops the bot after the second poll.+ t.sleep.mockImplementationOnce(async () => {}).mockImplementationOnce(async () => {+ await fs.writeFile(path.join(t.host, 'gateway_state.json'), JSON.stringify({ platforms: { 'family:telegram': { state: 'disconnected' } } }));+ });+ expect(await t.run()).toBeUndefined();+ expect(await t.calls()).toEqual(['config set platforms.telegram.enabled false']);+ expect(t.sleep).toHaveBeenCalledTimes(2);+ expect(t.target.connect).toHaveBeenCalledTimes(1);+});++it.each([+ { original: undefined, restore: 'config unset platforms.telegram.enabled' },+ { original: true, restore: 'config set platforms.telegram.enabled true' },+])('restores the original Hermes switch ($original) and gateway when the companion cannot connect', async ({ original, restore }) => {+ const t = await setup('hermes', { name: 'Ada', ...(original === undefined ? {} : { platforms: { telegram: { enabled: original } } }) }, { live: true, env: telegramEnv });+ t.target.connect.mockResolvedValueOnce('IMPORT_IM_BOT_GATEWAY_RUNNING');+ expect(await t.run()).toBe('IMPORT_IM_BOT_GATEWAY_RUNNING');+ expect(await t.calls()).toEqual(['config set platforms.telegram.enabled false', 'gateway restart', restore, 'gateway restart']);+ expect(object((await t.readConfig()).platforms?.telegram).enabled).toBe(original);+ // A later retry starts from scratch.+ expect(t.saves.at(-1)).toBeUndefined();+});++it('does not connect when the source switch or the live bot does not stop', async () => {+ const t = await setup('hermes', { name: 'Ada' }, { live: true, env: telegramEnv });+ await fs.writeFile(path.join(t.state, 'fail-config'), '');+ expect(await t.run()).toBe('IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED');+ expect(t.saves.at(-1)).toBeUndefined();+ await fs.rm(path.join(t.state, 'fail-config'));+ await fs.writeFile(path.join(t.state, 'restart-keeps-live'), '');+ t.saves.length = 0;+ expect(await t.run()).toBe('IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED');+ expect(t.target.connect).not.toHaveBeenCalled();+ // The switch stays off: the user moved the bot, the gateway has just not let go yet.+ expect(t.saves.at(-1)).toMatchObject({ phase: 'stopped', changed: true, restarted: true });+ expect((await t.readConfig()).platforms.telegram.enabled).toBe(false);+});++it('resumes an interrupted takeover without stopping or restarting twice', async () => {+ const t = await setup('hermes', { name: 'Ada', platforms: { telegram: { enabled: false } } }, { env: telegramEnv });+ const record: ImportBotRecord = { phase: 'stopped', original: { present: false }, wasLive: true, changed: true, restarted: true };+ expect(await t.run(record)).toBeUndefined();+ expect(await t.calls()).toEqual([]);+ expect(t.target.connect).toHaveBeenCalledTimes(1);+ // A connection created just before the crash is recognized instead of added again.+ t.target.existing.mockReturnValue('self');+ expect(await t.run(record)).toBeUndefined();+ expect(await t.run({ ...record, phase: 'connected' })).toBeUndefined();+ expect(t.target.connect).toHaveBeenCalledTimes(1);+ expect(await t.calls()).toEqual([]);+});++it('disables an OpenClaw account through a stdin patch and removes it again on failure', async () => {+ const t = await setup('openclaw', { commands: { ownerAllowFrom: ['telegram:424242'] }, channels: { telegram: { accounts: { default: { botToken: '1234567:fake-telegram-token' } } } } });+ t.target.connect.mockResolvedValueOnce('IMPORT_IM_BOT_CONNECT_FAILED');+ expect(await t.run()).toBe('IMPORT_IM_BOT_CONNECT_FAILED');+ expect(await t.calls()).toEqual(['config patch --stdin', 'config patch --stdin']);+ expect(t.sleep).toHaveBeenCalledWith(3_000);+ expect((await t.readConfig()).channels.telegram.accounts.default).toEqual({ botToken: '1234567:fake-telegram-token' });+ expect(await t.run()).toBeUndefined();+ expect((await t.readConfig()).channels.telegram.accounts.default.enabled).toBe(false);+});++function object(value: unknown): Record<string, unknown> { return value && typeof value === 'object' ? value as Record<string, unknown> : {}; }diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.tsindex 7a12402a3a..d7e196d226 100644--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts@@ -525,7 +525,10 @@ it.each([false, true])('publishes command env/argv/stdin credentials safely (comconst [source] = await listCompanionImportSources('fixture');const remote = await readRemoteCompanionImport(`preview:${source!.id}`, 'fixture', false);for (const value of [secret, nested, ...urlSecrets, ...literalSecrets]) expect(JSON.stringify(remote)).not.toContain(value);+ // A remote controller that did not advertise the bots category gets the legacy projection; local previews get bots.+ expect(vi.mocked(inspectImportSource).mock.calls.at(-1)?.[3]).toEqual({ bots: false });const preview = await previewCompanionImport(source!.id, 'fixture');+ expect(vi.mocked(inspectImportSource).mock.calls.at(-1)?.[3]).toEqual({ bots: true });const requestId = 'fixture-json-command-publication';const result = await startCompanionImport({ requestId, previewId: preview.id, name: 'Ada',entryIds: ['source-env', 'memory', 'skill', ...(selected ? ['task'] : [])], takeover: false }, 'fixture');diff --git a/apps/desktop/src/main/bot-import/__tests__/registration.test.ts b/apps/desktop/src/main/bot-import/__tests__/registration.test.tsindex 700396e1da..a8d7bc9ab0 100644--- a/apps/desktop/src/main/bot-import/__tests__/registration.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/registration.test.ts@@ -44,11 +44,12 @@ it('continues to hide unexpected provider failures from mobile', async () => {await expect(invoke()).rejects.toThrow('[INTERNAL] remote resource provider failed');});-it.each([false, true])('negotiates chunk reads without changing the legacy resource (%s)', async supported => {+it.each([false, true])('negotiates chunk reads and the bots category without changing the legacy resource (%s)', async supported => {h.channel = 'maker:remote-resources:get';h.remote.mockResolvedValueOnce({ preview: { id: 'preview', entries: [] } });- await h.handlers.get('maker:remote-resources:get')!({}, { ref: { collectionId: 'companion-import', kind: 'import', id: 'preview:source' }, client: { protocolVersion: 1, primitives: ['companion-import', ...(supported ? ['companion-import-chunks-v1'] : [])] } });- expect(h.remote).toHaveBeenLastCalledWith('preview:source', 'phone', supported);+ await h.handlers.get('maker:remote-resources:get')!({}, { ref: { collectionId: 'companion-import', kind: 'import', id: 'preview:source' }, client: { protocolVersion: 1, primitives: ['companion-import', ...(supported ? ['companion-import-chunks-v1', 'companion-import-bots-v1'] : [])] } });+ // A controller that never advertised the bots category keeps receiving bots under connections.+ expect(h.remote).toHaveBeenLastCalledWith('preview:source', 'phone', supported, supported);});it('acknowledges a selection chunk without navigating before the host accepts the full import', async () => {diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.tsindex 67d96ff213..db20f87ecb 100644--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts@@ -221,6 +221,75 @@ describe('installed agent imports', () => {expect(snapshot.items.find(item => item.credential?.format === 'telegram')?.credential?.value).toEqual({ token: '${TELEGRAM_BOT_TOKEN}', account: 'default', ownerUserId: '424242' });expect(snapshot.items.find(item => item.credential?.format === 'discord')?.credential?.value).toEqual({ token: '${DISCORD_BOT_TOKEN}', account: 'default' });});+ // Bots category (companion-import-bots-v1): one entry per bot, preselected unless the source disabled it.+ it('lists Hermes bots on every platform with the inferred owner, and keeps legacy previews unchanged', async () => {+ await write('.hermes/config.yaml', [+ 'name: Ada', 'platforms:', ' feishu:', ' enabled: false', ' extra:', ' admins: [ou_fixtureowner]',+ ' telegram:', ' extra:', ' group_allow_admin_from: [424242]',+ ].join('\n'));+ await write('.hermes/.env', ['TELEGRAM_BOT_TOKEN=12345:fake-telegram-token', 'TELEGRAM_ALLOWED_USERS=424242,515151', 'TELEGRAM_HOME_CHANNEL=515151',+ 'FEISHU_APP_ID=cli_fixture', 'FEISHU_APP_SECRET=fake-feishu-secret', 'FEISHU_BOT_NAME=Ada Lark', 'FEISHU_DOMAIN=lark',+ 'WECOM_BOT_ID=fixture-wecom', 'WECOM_SECRET=fake-wecom-secret', 'WECOM_ALLOWED_USERS=alice'].join('\n'));+ const reader = deps(); const [source] = await discoverImportSources(reader);+ const snapshot = await inspectImportSource(source!, reader, undefined, { bots: true });+ const bots = snapshot.items.filter(item => item.view.category === 'bots');+ expect(bots.map(({ view }) => ({ platform: view.platform, name: view.name, selected: view.selected, enabled: view.enabled, owner: view.owner }))).toEqual([+ // Two allowed users: the one that is also the home chat is the owner.+ { platform: 'telegram', name: 'Ada', selected: true, enabled: undefined, owner: '515151' },+ { platform: 'feishu', name: 'Ada Lark', selected: false, enabled: false, owner: 'ou_fixtureowner' },+ { platform: 'wecom', name: 'Ada', selected: true, enabled: undefined, owner: 'alice' },+ ]);+ expect(bots[1]!.credential?.value).toEqual({ appId: '${FEISHU_APP_ID}', appSecret: '${FEISHU_APP_SECRET}', account: 'default', service: 'lark', ownerUserId: 'ou_fixtureowner' });+ expect(bots[1]!.bot).toEqual({ platform: 'feishu', account: 'default', enabledPath: ['platforms', 'feishu', 'enabled'] });+ for (const bot of bots) expect(bot.view.dependsOn!.every(id => snapshot.items.some(item => item.view.id === id && item.view.selected))).toBe(true);+ expect(JSON.stringify(bots.map(item => item.view))).not.toMatch(/fake-|cli_fixture|fixture-wecom/);+ // Controllers without the bots category keep today's Telegram / Discord connections and no others.+ const legacy = await inspectImportSource(source!, reader);+ expect(legacy.items.some(item => item.view.category === 'bots' || ['feishu', 'wecom'].includes(item.credential?.format ?? ''))).toBe(false);+ expect(legacy.items.find(item => item.credential?.format === 'telegram')?.view).toMatchObject({ category: 'connections', name: 'Telegram · default' });+ });++ it('offers exclusive owner alternatives for a few allowed users and asks for an owner beyond five', async () => {+ await write('.hermes/config.yaml', 'name: Ada\n');+ await write('.hermes/.env', ['TELEGRAM_BOT_TOKEN=12345:fake-telegram-token', 'TELEGRAM_ALLOWED_USERS=1111,2222,3333',+ 'DISCORD_BOT_TOKEN=fake-discord-token', `DISCORD_ALLOWED_USERS=${Array.from({ length: 6 }, (_, index) => `11111111111111111${index}`).join(',')}`].join('\n'));+ const reader = deps(); const [source] = await discoverImportSources(reader);+ const snapshot = await inspectImportSource(source!, reader, undefined, { bots: true });+ const telegram = snapshot.items.filter(item => item.view.platform === 'telegram');+ expect(telegram.map(item => [item.view.owner, item.view.selected, item.view.exclusiveWith?.length])).toEqual([['1111', false, 2], ['2222', false, 2], ['3333', false, 2]]);+ expect(telegram[0]!.view.exclusiveWith).toEqual([telegram[1]!.view.id, telegram[2]!.view.id]);+ expect(snapshot.items.filter(item => item.view.platform === 'discord').map(item => item.view.issues)).toEqual([['IMPORT_IM_BOT_OWNER_MISSING']]);+ const selection = { requestId: 'fixture-owner-request', previewId: 'preview', name: 'Ada', takeover: false };+ const env = snapshot.items.filter(item => item.env?.TELEGRAM_BOT_TOKEN).map(item => item.view.id);+ expect(validateImportSelection({ ...selection, entryIds: [...env, telegram[1]!.view.id] }, snapshot)).toHaveLength(2);+ expect(() => validateImportSelection({ ...selection, entryIds: [...env, telegram[0]!.view.id, telegram[1]!.view.id] }, snapshot)).toThrow('INVALID_SELECTION');+ });++ it('lists an OpenClaw bot only for the agent its account routes to, unselected when other agents share it', async () => {+ await write('.openclaw/openclaw.json', JSON.stringify({+ agents: { list: [{ id: 'main', default: true }, { id: 'email' }, { id: 'quiet' }] },+ commands: { ownerAllowFrom: ['telegram:424242', 'feishu:ou_fixtureowner'] },+ bindings: [{ agentId: 'email', match: { channel: 'telegram', accountId: 'default', peer: { kind: 'direct', id: '1' } } }, { agentId: 'main', match: { channel: 'telegram' } },+ { agentId: 'quiet', match: { channel: 'feishu', accountId: 'work' } }],+ channels: {+ telegram: { botToken: '1234567:fixture-channel', accounts: { default: { name: 'Ada Bot', enabled: true } } },+ feishu: { appSecret: { source: 'env', provider: 'default', id: 'FEISHU_APP_SECRET' }, domain: 'lark', accounts: { work: { appId: 'cli_fixture', name: 'Work' } } },+ },+ }));+ const reader = deps(); const sources = await discoverImportSources(reader);+ const bots = async (agent: string) => (await inspectImportSource(sources.find(source => source.agentId === agent)!, reader, undefined, { bots: true }))+ .items.filter(item => item.view.category === 'bots');+ const [telegram, ...others] = await bots('main');+ expect(others).toEqual([]);+ // The account inherits the channel token; the email agent's peer route shares this bot.+ expect(telegram).toMatchObject({ view: { platform: 'telegram', name: 'Ada Bot', selected: false, owner: '424242' },+ credential: { value: { token: '1234567:fixture-channel', account: 'default', ownerUserId: '424242' } },+ bot: { enabledPath: ['channels', 'telegram', 'accounts', 'default', 'enabled'] } });+ expect(await bots('email')).toEqual([]);+ const [feishu] = await bots('quiet');+ expect(feishu).toMatchObject({ view: { platform: 'feishu', name: 'Work', selected: true, owner: 'ou_fixtureowner' },+ credential: { value: { appId: 'cli_fixture', appSecret: '${FEISHU_APP_SECRET}', service: 'lark' } } });+ });it('keeps secret references unexpanded until the final env and connection selection', async () => {await write('.hermes/config.yaml', 'name: Ada\nmcp_servers:\n data:\n url: https://example.invalid/mcp\n headers:\n Authorization: Bearer ${DATA_TOKEN}\n');await write('.hermes/.env', 'DATA_TOKEN=fake-selected-secret\nTELEGRAM_BOT_TOKEN=12345:fake-telegram-token');diff --git a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts b/apps/desktop/src/main/bot-import/__tests__/transfer.test.tsindex 7927082ffd..22e598b2f7 100644--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts@@ -114,6 +114,29 @@ it('reports an imported bot that could not become its own connection without bloexpect(result.checks.find(check => check.entryId === task.view.id)?.status).not.toBe('needs-attention');});+it('hands a bots entry to the source takeover with its durable record, and keeps its advisory outcome while reconciling', async () => {+ const bot = { view: { id: 'bot', name: 'Ada', category: 'bots' as const, platform: 'feishu' as const, selected: true }, credential: { format: 'feishu', value: { account: 'default', appId: 'cli_fixture', appSecret: 'fake-secret' } },+ bot: { platform: 'feishu' as const, account: 'default', enabledPath: ['platforms', 'feishu', 'enabled'] } };+ const items = [snapshot.items[0]!, bot];+ const { deps, receipt } = harness();+ deps.connectImBot = vi.fn(async () => undefined);+ deps.takeOverImBot = vi.fn(async (_botId, _item, _record, save) => { await save({ phase: 'stopped', changed: true }); return 'IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED'; });+ const chosen = { ...selection, entryIds: ['memory', 'bot'] };+ const result = await transferCompanion({ ...snapshot, items }, chosen, deps);+ expect(deps.connectImBot).not.toHaveBeenCalled();+ expect(deps.importItem).not.toHaveBeenCalledWith(expect.anything(), bot, expect.anything());+ expect(result.checks.find(check => check.entryId === 'bot')).toMatchObject({ status: 'needs-attention', message: 'IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED' });+ expect(result.savedEntryIds).toContain('bot');+ expect(receipt()?.bots).toEqual({ bot: { phase: 'stopped', changed: true } });+ // Background reconciliation never stops or restarts a source on its own.+ await transferCompanion({ ...snapshot, items }, chosen, deps, true);+ expect(deps.takeOverImBot).toHaveBeenCalledTimes(1);+ // An explicit retry resumes from the persisted record.+ vi.mocked(deps.takeOverImBot).mockResolvedValueOnce(undefined);+ expect((await transferCompanion({ ...snapshot, items }, chosen, deps)).checks.find(check => check.entryId === 'bot')?.status).toBe('taken-over');+ expect(vi.mocked(deps.takeOverImBot).mock.calls[1]![2]).toEqual({ phase: 'stopped', changed: true });+});+it.each(['personal', 'missing'])('uses local delivery even when the source names Telegram account %s', async accountId => {const source = { ...snapshot.source, kind: 'openclaw' as const };const accounts = ['work', 'personal'].map(account => ({diff --git a/apps/desktop/src/main/bot-import/botTakeover.ts b/apps/desktop/src/main/bot-import/botTakeover.tsnew file mode 100644index 0000000000..0e675f7452--- /dev/null+++ b/apps/desktop/src/main/bot-import/botTakeover.ts@@ -0,0 +1,188 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import { readImportSourceBot, type SourceReaderDeps } from './sources.js';+import { resolveSourceCli } from './takeover.js';+import { importedProcessEnvironment, runImportedProcess } from './process.js';+import { CompanionImportError, object, string, type ImportItem, type ImportSource } from './types.js';+import type { ImportedImBotTarget } from './imBotConnections.js';++/** Durable per-bot progress in the import receipt; a retry resumes from it instead of stopping twice. */+export interface ImportBotRecord {+ phase: 'stopping' | 'stopped' | 'connected';+ /** The source switch before this import, restored when the companion cannot connect. */+ original?: { present: boolean; value?: unknown };+ /** This import turned the source switch off. */+ changed?: boolean;+ /** The source gateway was serving the bot when the import began. */+ wasLive?: boolean;+ restarted?: boolean;+}++export interface BotTakeoverTiming { pollMs: number; timeoutMs: number; settleMs: number; sleep(ms: number): Promise<void>; now(): number }++const TIMING: BotTakeoverTiming = {+ pollMs: 2_000, timeoutMs: 120_000, settleMs: 3_000,+ // real-wait: the source gateway is a separate process; there is no event to wait on.+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)), now: Date.now,+};+const LIVE_STATES = new Set(['connected', 'connecting', 'retrying']);+const STATE_FILE_LIMIT = 4 * 1024 * 1024;++export interface BotTakeoverInput {+ source: ImportSource;+ item: ImportItem;+ target: ImportedImBotTarget;+ record?: ImportBotRecord;+ /** Persist before and after each native mutation; undefined clears the record. */+ save(record: ImportBotRecord | undefined): Promise<void>;+ readers: SourceReaderDeps;+ assertOwner(): void;+ timing?: Partial<BotTakeoverTiming>;+ alive?(pid: number): boolean;+}++function processAlive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; }+}++/** Hermes: a named profile is served by the host gateway (`<profile>:<platform>`) unless parked. */+async function hermesLiveness(source: ImportSource, platform: string, alive: (pid: number) => boolean): Promise<{ live: boolean; parked: boolean }> {+ const named = source.agentId !== 'default' && path.basename(path.dirname(source.root)) === 'profiles';+ let parked = false;+ if (named) try { await fs.access(path.join(source.root, 'gateway.parked')); parked = true; } catch { /* Not parked. */ }+ const files: Array<[string, string]> = [[path.join(source.root, 'gateway_state.json'), platform]];+ if (named) files.push([path.join(path.dirname(path.dirname(source.root)), 'gateway_state.json'), `${source.agentId}:${platform}`]);+ let live = false;+ for (const [file, key] of files) {+ let state: Record<string, unknown>;+ try {+ if ((await fs.stat(file)).size > STATE_FILE_LIMIT) continue;+ state = object(JSON.parse(await fs.readFile(file, 'utf8')));+ } catch { continue; }+ const entry = object(object(state.platforms)[key]);+ const pid = Number(entry.writer_pid ?? state.pid);+ // A crashed gateway leaves its last state behind; only a running writer serves the bot.+ if (LIVE_STATES.has(string(entry.state)) && (!Number.isSafeInteger(pid) || pid <= 0 || alive(pid))) live = true;+ }+ return { live, parked };+}++function nested(keys: string[], value: unknown): Record<string, unknown> {+ return keys.reduceRight<unknown>((child, key) => ({ [key]: child }), value) as Record<string, unknown>;+}++/**+ * Stop an imported bot in its source agent, then connect it as the companion's own. Mirrors the+ * automation handover: native commands only, re-read to confirm, restore on failure. Resolves to+ * an advisory issue code; nothing here throws for an ordinary platform or source failure.+ */+export async function takeOverImportedBot(input: BotTakeoverInput): Promise<string | undefined> {+ const { source, item, target, readers, assertOwner } = input;+ const timing = { ...TIMING, ...input.timing };+ const alive = input.alive ?? processAlive;+ const bot = item.bot;+ if (!bot) return 'IMPORT_IM_BOT_CONNECT_FAILED';+ let record = input.record ? { ...input.record } : undefined;+ const save = async (next: ImportBotRecord | undefined) => { record = next; await input.save(next ? { ...next } : undefined); assertOwner(); };+ if (record?.phase === 'connected') return undefined;+ const key = bot.enabledPath.join('.');+ let cli: Awaited<ReturnType<typeof resolveSourceCli>> | undefined;+ const run = async (args: string[], stdin?: string, timeoutMs = 30_000): Promise<boolean> => {+ cli ??= await resolveSourceCli(source, readers.home, readers.env); assertOwner();+ const env = importedProcessEnvironment(source.kind === 'hermes' ? { HERMES_HOME: source.root }+ : { OPENCLAW_STATE_DIR: source.root, OPENCLAW_CONFIG_PATH: source.configFile }, readers.env);+ try {+ const result = await runImportedProcess({ command: cli.interpreter ?? cli.executable,+ args: cli.interpreter ? ['/d', '/s', '/c', `""${cli.executable}" ${args.join(' ')}"`] : args,+ windowsVerbatimArguments: !!cli.interpreter, cwd: source.root, env, timeoutMs, signal: new AbortController().signal, assertOwner,+ ...(stdin === undefined ? {} : { input: stdin }) });+ assertOwner();+ return result.exitCode === 0;+ } catch (error) {+ assertOwner();+ if (error instanceof CompanionImportError && error.code === 'OWNER_CHANGED') throw error;+ return false;+ }+ };+ // Flags never carry credentials; OpenClaw patches go through stdin.+ const setSwitch = (value: unknown, present = true) => source.kind === 'hermes'+ ? run(present ? ['config', 'set', key, String(value)] : ['config', 'unset', key])+ : run(['config', 'patch', '--stdin'], JSON.stringify(nested(bot.enabledPath, present ? value : null)));+ const liveness = () => source.kind === 'hermes' ? hermesLiveness(source, bot.platform, alive) : Promise.resolve({ live: false, parked: false });+ const restartGateway = () => run(['gateway', 'restart'], undefined, 120_000);+ /** Only undo what this import did; a still-unknown restore keeps the record for the next retry. */+ const restore = async () => {+ if (!record) return;+ if (record.changed && record.original) {+ try {+ await setSwitch(record.original.value, record.original.present);+ // The switch was on when this import turned it off.+ if (!(await readImportSourceBot(source, bot)).enabled) return;+ const { parked } = await liveness();+ if (record.restarted && !parked) await restartGateway();+ } catch (error) {+ if (error instanceof CompanionImportError && error.code === 'OWNER_CHANGED') throw error;+ return;+ }+ }+ await save(undefined);+ };++ try {+ const existing = target.existing();+ if (existing === 'self') { await save({ ...(record ?? {}), phase: 'connected' }); return undefined; }+ if (existing === 'other') { await restore(); return 'IMPORT_IM_BOT_IN_USE'; }+ if (!record) {+ // Nothing changes in the source before the companion side is known to be addable.+ const blocked = await target.preflight(); assertOwner();+ if (blocked) return blocked;+ const before = await readImportSourceBot(source, bot); assertOwner();+ const { live } = await liveness();+ await save({ phase: 'stopping', original: { present: before.present, ...(before.present ? { value: before.value } : {}) },+ wasLive: source.kind === 'hermes' ? live : before.enabled });+ }+ if (record!.phase === 'stopping') {+ if ((await readImportSourceBot(source, bot)).enabled) {+ cli ??= await resolveSourceCli(source, readers.home, readers.env); assertOwner();+ await save({ ...record!, changed: true });+ await setSwitch(false);+ if ((await readImportSourceBot(source, bot)).enabled) {+ // The switch did not change; there is nothing of ours to restore.+ await save(undefined);+ return 'IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED';+ }+ }+ await save({ ...record!, phase: 'stopped' });+ }+ if (record!.wasLive && source.kind === 'hermes') {+ let state = await liveness();+ // A restart would unpark a parked profile, so a parked bot is never restarted.+ if (state.live && !state.parked && !record!.restarted) {+ await save({ ...record!, restarted: true });+ await restartGateway();+ state = await liveness();+ }+ const deadline = timing.now() + timing.timeoutMs;+ while (state.live && timing.now() < deadline) {+ await timing.sleep(timing.pollMs); assertOwner();+ state = await liveness();+ }+ // Keep the switch off: the user asked to move the bot, the source just has not let go yet.+ if (state.live) return 'IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED';+ } else if (record!.wasLive && record!.changed) {+ // OpenClaw hot-reloads channel config; Telegram's conflict window still catches a slow stop.+ await timing.sleep(timing.settleMs); assertOwner();+ }+ const issue = await target.connect(); assertOwner();+ if (!issue) { await save({ ...record!, phase: 'connected' }); return undefined; }+ await restore();+ return issue;+ } catch (error) {+ if (error instanceof CompanionImportError && error.code === 'SOURCE_COMMAND_UNAVAILABLE') {+ // Nothing was changed without the native command.+ if (record && !record.changed) await save(undefined);+ return 'SOURCE_COMMAND_UNAVAILABLE';+ }+ throw error;+ }+}diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.tsindex 439807c483..d9fdf9a8cd 100644--- a/apps/desktop/src/main/bot-import/host.ts+++ b/apps/desktop/src/main/bot-import/host.ts@@ -39,7 +39,7 @@ import { projectImportedSkill } from './skillResources.js';import { assertImportedAutomationReady } from './automationRuntime.js';/** Bot tokens saved resolved, so delivery and the companion's own connection read the real value. */-const IM_BOT_CREDENTIAL_FORMATS = new Set(['telegram', 'discord']);+const IM_BOT_CREDENTIAL_FORMATS = new Set(['telegram', 'discord', 'feishu', 'wecom', 'dingtalk']);interface Owned<T> { owner: string; controller: string; value: T; createdAt: number }const sources = new Map<string, Owned<ImportSource>>();@@ -115,10 +115,14 @@ async function retainPreview(id: string, entry: Owned<ImportSnapshot>, assertOwnpreviews.set(id, { ...entry, bytes });}-export async function previewCompanionImport(sourceId: string, controller: string): Promise<CompanionImportPreview> {+/**+ * `bots`: the controller renders the bots category (local UI, `import_agent`, remote clients that+ * advertise it). The retained snapshot keeps that choice in each item's category, through start and recovery.+ */+export async function previewCompanionImport(sourceId: string, controller: string, bots = true): Promise<CompanionImportPreview> {const scope = owner();const source = owned(sources, sourceId, controller);- const inspected = await inspectImportSource(source, readers()); scope.assert();+ const inspected = await inspectImportSource(source, readers(), undefined, { bots }); scope.assert();const snapshot = { ...inspected, items: inspected.items.map((item, index) => ({ ...item, sourceIndex: index })) };if (snapshot.avatarImageBase64) {const original = Buffer.from(snapshot.avatarImageBase64, 'base64');@@ -140,7 +144,7 @@ export async function previewCompanionImport(sourceId: string, controller: strin/** Freeze each public read while transferring it; never re-inspect a source between chunks.* UTF-16 slices are at most 1.5 MiB after JSON escaping, well below a 2 MiB frame. */-export async function readRemoteCompanionImport(id: string, controller: string, chunked: boolean): Promise<Record<string, unknown>> {+export async function readRemoteCompanionImport(id: string, controller: string, chunked: boolean, bots = false): Promise<Record<string, unknown>> {const scope = owner();const chunk = (token: string, text: string, offset: number) => ({chunk: { id: token, offset, total: text.length, text: text.slice(offset, offset + COMPANION_IMPORT_CHUNK_LENGTH) },@@ -154,7 +158,7 @@ export async function readRemoteCompanionImport(id: string, controller: string,return chunk(match[1]!, text, offset);}const data = id === 'sources' ? { sources: await listCompanionImportSources(controller) }- : id.startsWith('preview:') ? { preview: await previewCompanionImport(id.slice(8), controller) }+ : id.startsWith('preview:') ? { preview: await previewCompanionImport(id.slice(8), controller, bots) }: id.startsWith('result:') ? { result: await getCompanionImportResult(id.slice(7)) ?? null } : undefined;scope.assert();if (!data) throw new CompanionImportError('INVALID_REQUEST');@@ -814,6 +818,21 @@ export async function startCompanionImport(selection: CompanionImportSelection,const issue = await connectImportedImBot(botId, { format: item.credential.format, value }); scope.assert();return issue;},+ async takeOverImBot(botId, item, record, save) {+ if (!item.credential) return undefined;+ // Loaded lazily so the import pipeline does not pull the IM runtime into its own module graph.+ const [{ importedImBotTarget }, { takeOverImportedBot }] = await Promise.all([import('./imBotConnections.js'), import('./botTakeover.js')]); scope.assert();+ const target = importedImBotTarget(botId, { format: item.credential.format, value: resolveImportReferences(item.credential.value, selectedImportEnvironment(selected)) });+ if (typeof target === 'string') return target;+ try {+ return await takeOverImportedBot({ source: snapshot.source, item, target, record, save, readers: readers(), assertOwner: scope.assert });+ } catch (error) {+ scope.assert();+ if (error instanceof CompanionImportError && error.code === 'OWNER_CHANGED') throw error;+ // The durable record stays as saved; an explicit retry resumes from it.+ return 'IMPORT_IM_BOT_CONNECT_FAILED';+ }+ },pauseSource: (item, source, resumeInterruptedPause) => changeSourceAutomationState(source.source, item, false, readers(), scope.assert, resumeInterruptedPause, selectedImportEnvironment(selected)),resumeSource: (item, source) => changeSourceAutomationState(source.source, item, true, readers(), scope.assert, false, selectedImportEnvironment(selected)),async enableRoutine(botId, routineId, item) {diff --git a/apps/desktop/src/main/bot-import/imBotConnections.ts b/apps/desktop/src/main/bot-import/imBotConnections.tsindex e88a851bfa..71ec8a9a32 100644--- a/apps/desktop/src/main/bot-import/imBotConnections.ts+++ b/apps/desktop/src/main/bot-import/imBotConnections.ts@@ -1,9 +1,11 @@import { createLogger } from '../logger.js';import {addBotImConnection,+ assertBotImConnectionAddable,findBotImConnectionByIdentity,parseBotImConnectionAddInput,} from '../im/shared/botImConnectionRuntime.js';+import type { BotImConnectionAddInput } from '../../shared/botImConnection.js';import { object } from './types.js';const log = createLogger('bot-import:im-bot');@@ -11,33 +13,79 @@ const log = createLogger('bot-import:im-bot');/** Long enough for a still-running source gateway to answer Telegram polling with 409. */const TELEGRAM_CONFLICT_WINDOW_MS = 5_000;+/** The companion's side of one imported bot. Connection runtime errors become advisory issue codes. */+export interface ImportedImBotTarget {+ channel: BotImConnectionAddInput['channel'];+ /** A connection with the same platform identity: this companion's (an earlier attempt) or another's. */+ existing(): 'self' | 'other' | undefined;+ /** Checks that need no network, before the source bot is stopped. */+ preflight(): Promise<string | undefined>;+ connect(): Promise<string | undefined>;+}++const string = (value: unknown) => typeof value === 'string' ? value.trim() : '';++function issueOf(channel: string, error: unknown): string {+ // IPC errors read "[CODE] message"; the runtime's messages carry codes and platform reasons, never the token.+ const message = error instanceof Error ? error.message : '';+ const issue = /\bownerUserId is invalid\b/.test(message) ? 'IMPORT_IM_BOT_OWNER_MISSING'+ : /\b(TOKEN_IN_USE|APP_IN_USE):/.test(message) ? 'IMPORT_IM_BOT_IN_USE'+ : /\bCONNECT_FAILED: conflict$/.test(message) ? 'IMPORT_IM_BOT_GATEWAY_RUNNING'+ : 'IMPORT_IM_BOT_CONNECT_FAILED';+ log.warn(`imported ${channel} bot connection not created: ${issue}`);+ return issue;+}++/**+ * Resolve an imported credential (references already expanded) into the companion's add input.+ * Returns an issue code when it cannot become a connection; secrets never reach logs or the result.+ */+export function importedImBotTarget(botId: string, credential: { format: string; value: unknown }): ImportedImBotTarget | string {+ const value = object(credential.value);+ const channel = credential.format;+ if (!['telegram', 'discord', 'feishu', 'wecom', 'dingtalk'].includes(channel)) return 'IMPORT_IM_BOT_CONNECT_FAILED';+ const owner = string(value.ownerUserId);+ if ((channel === 'telegram' || channel === 'discord') && !owner) return 'IMPORT_IM_BOT_OWNER_MISSING';+ let input: BotImConnectionAddInput;+ try {+ input = parseBotImConnectionAddInput({ botId, channel, token: value.token, ownerUserId: owner, appId: value.appId, appSecret: value.appSecret,+ service: value.service, wecomBotId: value.wecomBotId, secret: value.secret, appKey: value.appKey });+ } catch (error) { return issueOf(channel, error); }+ const identity = input.channel === 'telegram' || input.channel === 'discord' ? input.token+ : input.channel === 'feishu' ? input.appId : input.channel === 'wecom' ? input.wecomBotId : input.appKey;+ return {+ channel: input.channel,+ existing() {+ const found = findBotImConnectionByIdentity(input.channel, identity);+ return found ? found.botId === botId ? 'self' : 'other' : undefined;+ },+ async preflight() {+ try { await assertBotImConnectionAddable(input); return undefined; } catch (error) { return issueOf(input.channel, error); }+ },+ async connect() {+ try {+ // Feishu / WeCom / DingTalk carry the source's owner instead of waiting for the first private chat.+ await addBotImConnection(input, { ...(owner && input.channel !== 'telegram' && input.channel !== 'discord' ? { ownerUserId: owner } : {}),+ rejectConflictWithinMs: input.channel === 'telegram' ? TELEGRAM_CONFLICT_WINDOW_MS : 0 });+ return undefined;+ } catch (error) { return issueOf(input.channel, error); }+ },+ };+}+/**- * Connect an imported Telegram / Discord bot as the companion's own connection.- * Returns an advisory issue code instead of throwing: the import keeps the- * credential for delivery either way. Tokens never reach logs or the result.+ * Connect an imported Telegram / Discord bot as the companion's own connection (controllers+ * without the bots category; the source bot is not stopped). Returns an advisory issue code+ * instead of throwing: the import keeps the credential for delivery either way.*/export async function connectImportedImBot(botId: string, credential: { format: string; value: unknown }): Promise<string | undefined> {if (credential.format !== 'telegram' && credential.format !== 'discord') return undefined;- const channel = credential.format;- const value = object(credential.value);- const token = typeof value.token === 'string' ? value.token.trim() : '';- const ownerUserId = typeof value.ownerUserId === 'string' ? value.ownerUserId.trim() : '';- if (!ownerUserId) return 'IMPORT_IM_BOT_OWNER_MISSING';+ const target = importedImBotTarget(botId, credential);+ if (typeof target === 'string') return target;try {- const existing = token ? findBotImConnectionByIdentity(channel, token) : null;// Retried imports find the connection they already created.- if (existing) return existing.botId === botId ? undefined : 'IMPORT_IM_BOT_IN_USE';- const input = parseBotImConnectionAddInput({ botId, channel, token, ownerUserId });- await addBotImConnection(input, { rejectConflictWithinMs: channel === 'telegram' ? TELEGRAM_CONFLICT_WINDOW_MS : 0 });- return undefined;- } catch (error) {- // IPC errors read "[CODE] message"; the runtime's messages carry codes and platform reasons, never the token.- const message = error instanceof Error ? error.message : '';- const issue = /\bownerUserId is invalid\b/.test(message) ? 'IMPORT_IM_BOT_OWNER_MISSING'- : /\b(TOKEN_IN_USE|APP_IN_USE):/.test(message) ? 'IMPORT_IM_BOT_IN_USE'- : /\bCONNECT_FAILED: conflict$/.test(message) ? 'IMPORT_IM_BOT_GATEWAY_RUNNING'- : 'IMPORT_IM_BOT_CONNECT_FAILED';- log.warn(`imported ${channel} bot connection not created: ${issue}`);- return issue;- }+ const existing = target.existing();+ if (existing) return existing === 'self' ? undefined : 'IMPORT_IM_BOT_IN_USE';+ } catch (error) { return issueOf(target.channel, error); }+ return target.connect();}diff --git a/apps/desktop/src/main/bot-import/registration.ts b/apps/desktop/src/main/bot-import/registration.tsindex cf75cb4339..597d8898c3 100644--- a/apps/desktop/src/main/bot-import/registration.ts+++ b/apps/desktop/src/main/bot-import/registration.ts@@ -1,5 +1,5 @@import { ipcMain } from 'electron';-import { COMPANION_IMPORT_CHUNK_PRIMITIVE, type CompanionImportSelection, type CompanionImportSubmission } from '@cindy/maker-shared/companion-import';+import { COMPANION_IMPORT_BOTS_PRIMITIVE, COMPANION_IMPORT_CHUNK_PRIMITIVE, type CompanionImportSelection, type CompanionImportSubmission } from '@cindy/maker-shared/companion-import';import { remoteResourceRegistry, RemoteResourceRegistryError } from '../device-link/remoteResourceRegistry.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { listCompanionImportSources, previewCompanionImport, startCompanionImport, getCompanionImportResult, readRemoteCompanionImport, submitRemoteCompanionImport } from './host.js';@@ -30,7 +30,7 @@ export function registerCompanionImport(): void {try {const id = request.ref.id;const data = await readRemoteCompanionImport(id, context.controllerDeviceId,- request.client.primitives.includes(COMPANION_IMPORT_CHUNK_PRIMITIVE));+ request.client.primitives.includes(COMPANION_IMPORT_CHUNK_PRIMITIVE), request.client.primitives.includes(COMPANION_IMPORT_BOTS_PRIMITIVE));return { ref: request.ref, revision: '1', display: { title: 'Import' }, links: [],blocks: [{ id: 'import', primitive: 'companion-import', fallbackMarkdown: 'Hermes / OpenClaw', data }],actions: id.startsWith('preview:') ? [{ id: 'import', label: 'Import' }] : [] };diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.tsindex 7ab786bcd3..91ab6a5fc9 100644--- a/apps/desktop/src/main/bot-import/sources.ts+++ b/apps/desktop/src/main/bot-import/sources.ts@@ -10,6 +10,7 @@ import { discoverImportSkills } from './skills.js';import { indexAutomationDependencies, normalizeAutomation } from './sourceAutomations.js';import { memoryFileContent } from './memoryFiles.js';import { CompanionImportError, object, string, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';+import type { CompanionImportBotPlatform } from '@cindy/maker-shared/companion-import';export interface SourceReaderDeps {home: string;@@ -149,10 +150,15 @@ function scalarEnv(value: unknown): Record<string, string> {/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(entry[0]) && !['__proto__', 'prototype', 'constructor'].includes(entry[0]) && typeof entry[1] === 'string'));}-async function connections(items: ImportItem[], source: ImportSource, values: Record<string, unknown>, deps: SourceReaderDeps, budget: ImportReadBudget, readText = optionalText) {+async function sourceEnvironment(source: ImportSource, values: Record<string, unknown>, budget: ImportReadBudget, readText = optionalText): Promise<Record<string, string>> {const dotenv = parseEnv(await readText(source.root, path.join(source.root, '.env'), budget) ?? '');const envConfig = object(values.env);- const env = { ...dotenv, ...scalarEnv(envConfig), ...scalarEnv(envConfig.vars) };+ return { ...dotenv, ...scalarEnv(envConfig), ...scalarEnv(envConfig.vars) };+}++/** `bots`: messaging bots become their own category for controllers that can show it; otherwise legacy connections. */+async function connections(items: ImportItem[], source: ImportSource, values: Record<string, unknown>, deps: SourceReaderDeps, budget: ImportReadBudget, readText = optionalText, bots = false) {+ const env = await sourceEnvironment(source, values, budget, readText);for (const [name, value] of Object.entries(env)) {items.push({ view: { id: entryId('env', name), category: 'connections', name, selected: true }, env: { [name]: value } });}@@ -182,6 +188,32 @@ async function connections(items: ImportItem[], source: ImportSource, values: Remcp: { name, enabled, ...(command ? { command, args: Array.isArray(record.args) ? record.args.map(string) : [], cwd, transport: 'stdio' as const } : { url, transport: record.transport === 'sse' ? 'sse' as const : 'http' as const }),env: scalarEnv(record.env), headers: scalarEnvHeaders(record.headers) } });}+ if (bots) pushBotItems(items, await sourceBots(source, values, env, deps, budget, readText));+ else await legacyImBots(items, source, values, env, deps, budget, readText);+ // Keep native auth metadata without exposing its contents or inventing a refresh protocol.+ // API keys have a direct environment equivalent; provider OAuth needs its native refresh adapter.+ const authFiles = source.kind === 'hermes' ? ['auth.json'] : [`agents/${source.agentId}/agent/auth-profiles.json`];+ for (const name of authFiles) {+ const raw = await readText(source.root, path.join(source.root, name), budget);+ if (!raw) continue;+ let value: Record<string, unknown>;+ try { value = object(JSON.parse(raw)); } catch { throw new CompanionImportError('SOURCE_CREDENTIAL_INVALID'); }+ const profiles = source.kind === 'hermes' ? { ...object(value.providers), ...Object.fromEntries(Object.entries(object(value.credential_pool)).map(([key, records]) => [key, { ...object(object(value.providers)[key]), credential_pool: records }])) } : object(value.profiles);+ for (const [id, record] of Object.entries(profiles)) {+ if (!record || typeof record !== 'object') continue;+ const profile = object(record);+ const provider = string(profile.provider) || id.split(':')[0]!;+ const keyVariables: Record<string, string> = { openai: 'OPENAI_API_KEY', anthropic: 'ANTHROPIC_API_KEY', openrouter: 'OPENROUTER_API_KEY', xai: 'XAI_API_KEY', google: 'GEMINI_API_KEY', deepseek: 'DEEPSEEK_API_KEY' };+ const apiKey = profile.type === 'api_key' || profile.auth_type === 'api_key' ? string(profile.key) || string(profile.api_key) : '';+ const variable = keyVariables[provider];+ items.push({ view: { id: entryId('credential', `${name}:${id}`), category: 'connections', name: `${id} · ${path.basename(name)}`, selected: true,+ ...(apiKey && variable ? {} : { issues: ['NATIVE_AUTH_REFRESH_REQUIRED'] }) }, ...(apiKey && variable ? { env: { [variable]: apiKey } } : {}), credential: { format: 'native-auth', value: { source: source.kind, file: name, profile: id, value: profile } } });+ }+ }+}++/** Telegram / Discord as `connections` for controllers without the bots category; no source stop. */+async function legacyImBots(items: ImportItem[], source: ImportSource, values: Record<string, unknown>, env: Record<string, string>, deps: SourceReaderDeps, budget: ImportReadBudget, readText = optionalText) {const channels = object(values.channels);const ownerAllowFrom = listOf(object(values.commands).ownerAllowFrom);const telegram = object(channels.telegram);@@ -222,26 +254,6 @@ async function connections(items: ImportItem[], source: ImportSource, values: Re?? singleUserId(listOf(inherited), ['discord:', 'user:'], DISCORD_USER_ID);items.push({ view: { id: entryId('discord', account), name: `Discord · ${account}`, category: 'connections', selected: true, dependsOn: references.map(key => entryId('env', key)) }, envDependencies: { names: references, entries: [] }, credential: { format: 'discord', value: { token, account, ...(ownerUserId ? { ownerUserId } : {}) } } });}- // Keep native auth metadata without exposing its contents or inventing a refresh protocol.- // API keys have a direct environment equivalent; provider OAuth needs its native refresh adapter.- const authFiles = source.kind === 'hermes' ? ['auth.json'] : [`agents/${source.agentId}/agent/auth-profiles.json`];- for (const name of authFiles) {- const raw = await readText(source.root, path.join(source.root, name), budget);- if (!raw) continue;- let value: Record<string, unknown>;- try { value = object(JSON.parse(raw)); } catch { throw new CompanionImportError('SOURCE_CREDENTIAL_INVALID'); }- const profiles = source.kind === 'hermes' ? { ...object(value.providers), ...Object.fromEntries(Object.entries(object(value.credential_pool)).map(([key, records]) => [key, { ...object(object(value.providers)[key]), credential_pool: records }])) } : object(value.profiles);- for (const [id, record] of Object.entries(profiles)) {- if (!record || typeof record !== 'object') continue;- const profile = object(record);- const provider = string(profile.provider) || id.split(':')[0]!;- const keyVariables: Record<string, string> = { openai: 'OPENAI_API_KEY', anthropic: 'ANTHROPIC_API_KEY', openrouter: 'OPENROUTER_API_KEY', xai: 'XAI_API_KEY', google: 'GEMINI_API_KEY', deepseek: 'DEEPSEEK_API_KEY' };- const apiKey = profile.type === 'api_key' || profile.auth_type === 'api_key' ? string(profile.key) || string(profile.api_key) : '';- const variable = keyVariables[provider];- items.push({ view: { id: entryId('credential', `${name}:${id}`), category: 'connections', name: `${id} · ${path.basename(name)}`, selected: true,- ...(apiKey && variable ? {} : { issues: ['NATIVE_AUTH_REFRESH_REQUIRED'] }) }, ...(apiKey && variable ? { env: { [variable]: apiKey } } : {}), credential: { format: 'native-auth', value: { source: source.kind, file: name, profile: id, value: profile } } });- }- }}const TELEGRAM_USER_ID = /^\d{4,20}$/;@@ -277,6 +289,207 @@ function scalarEnvHeaders(value: unknown): Record<string, string> {return Object.fromEntries(Object.entries(object(value)).filter((entry): entry is [string, string] => typeof entry[1] === 'string'));}+const REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;+const BOT_OWNER_ALTERNATIVES = 5;+const PLAIN_USER_ID = /^[A-Za-z0-9][A-Za-z0-9_@.:-]{0,127}$/;++interface SourceBot {+ platform: CompanionImportBotPlatform;+ account: string;+ name: string;+ /** Platform credential fields; values may still be `${VAR}` source references. */+ credential: Record<string, string>;+ service?: 'feishu' | 'lark';+ enabled: boolean;+ enabledPath: string[];+ owner?: string;+ /** Telegram / Discord allowed users when no single owner is evident. */+ ownerCandidates?: string[];+ /** Other agents also route through this bot: stopping it affects them, so it is not preselected. */+ shared?: boolean;+}++/** Distinct IDs only; wildcards, access groups and malformed entries are never owners. */+function userIds(entries: unknown[], prefixes: string[], pattern: RegExp): string[] {+ const ids = new Set<string>();+ for (const entry of entries) {+ let value = typeof entry === 'number' && Number.isSafeInteger(entry) ? String(entry) : typeof entry === 'string' ? entry.trim() : '';+ const prefix = prefixes.find(candidate => value.toLowerCase().startsWith(candidate));+ if (prefix) value = value.slice(prefix.length);+ if (pattern.test(value)) ids.add(value);+ }+ return [...ids];+}++/** Single allowed user; else the allowed user that is the home chat; else the only allowed admin. */+function inferOwner(allowed: string[], home = '', admins: string[] = []): Pick<SourceBot, 'owner' | 'ownerCandidates'> {+ if (allowed.length === 1) return { owner: allowed[0] };+ if (home && allowed.includes(home)) return { owner: home };+ const allowedAdmins = admins.filter(id => allowed.includes(id));+ if (allowedAdmins.length === 1) return { owner: allowedAdmins[0] };+ return { ownerCandidates: allowed };+}++function sourceDisabled(value: unknown): boolean {+ return value === false || typeof value === 'string' && /^(?:false|no|off|0)$/i.test(value.trim());+}++function sourceBotName(source: ImportSource, account: string, ...names: unknown[]): string {+ const name = names.map(value => string(value).trim()).find(Boolean);+ if (name) return name;+ if (account !== 'default') return account;+ return source.kind === 'hermes' && source.agentId === 'default' && source.name === 'default' ? 'Hermes' : source.name;+}++function hermesBots(source: ImportSource, values: Record<string, unknown>, env: Record<string, string>): SourceBot[] {+ const platforms = object(values.platforms);+ // Env wins over platforms.<name>.extra, as in Hermes' own env bridge.+ const value = (variable: string, fallback: unknown) => env[variable] ? `\${${variable}}` : secretReference(fallback);+ const bots: SourceBot[] = [];+ for (const platform of ['telegram', 'discord', 'feishu', 'wecom', 'dingtalk'] as const) {+ const block = object(platforms[platform]);+ const extra = object(block.extra);+ const enabled = !sourceDisabled(block.enabled);+ const enabledPath = ['platforms', platform, 'enabled'];+ const allowed = (pattern: RegExp) => userIds(listOf(env[`${platform.toUpperCase()}_ALLOWED_USERS`]), [], pattern);+ if (platform === 'telegram' || platform === 'discord') {+ const token = value(`${platform.toUpperCase()}_BOT_TOKEN`, block.token);+ if (!token) continue;+ const users = allowed(platform === 'telegram' ? TELEGRAM_USER_ID : DISCORD_USER_ID);+ const home = platform === 'telegram' ? string(env.TELEGRAM_HOME_CHANNEL) || string(values.TELEGRAM_HOME_CHANNEL)+ || string(object(block.home_channel).chat_id) || string(block.home_channel) : '';+ const admins = platform === 'telegram' ? userIds([...listOf(extra.group_allow_admin_from), ...listOf(extra.admins)], [], TELEGRAM_USER_ID) : [];+ bots.push({ platform, account: 'default', name: sourceBotName(source, 'default', block.name, extra.bot_name), credential: { token },+ enabled, enabledPath, ...(platform === 'telegram' ? inferOwner(users, home.trim(), admins) : inferOwner(users)) });+ continue;+ }+ const fields: Record<string, string> = platform === 'feishu' ? { appId: value('FEISHU_APP_ID', extra.app_id), appSecret: value('FEISHU_APP_SECRET', extra.app_secret) }+ : platform === 'wecom' ? { wecomBotId: value('WECOM_BOT_ID', extra.bot_id), secret: value('WECOM_SECRET', extra.secret) }+ : { appKey: value('DINGTALK_CLIENT_ID', extra.client_id), appSecret: value('DINGTALK_CLIENT_SECRET', extra.client_secret) };+ if (Object.values(fields).some(field => !field)) continue;+ const domain = string(env.FEISHU_DOMAIN) || string(extra.domain);+ // Feishu: only a single open_id admin; WeCom / DingTalk: only a single explicit allowed user.+ const owners = platform === 'feishu' ? userIds(listOf(extra.admins), [], /^ou_[A-Za-z0-9_-]{1,128}$/) : allowed(PLAIN_USER_ID);+ bots.push({ platform, account: 'default', name: sourceBotName(source, 'default', platform === 'feishu' ? env.FEISHU_BOT_NAME : '', extra.bot_name, block.name),+ credential: fields, ...(platform === 'feishu' ? { service: /lark/i.test(domain) ? 'lark' as const : 'feishu' as const } : {}),+ enabled, enabledPath, ...(owners.length === 1 ? { owner: owners[0] } : {}) });+ }+ return bots;+}++/** OpenClaw route bindings: the agent a bot account delivers to, and whether other agents share it. */+function openclawRoute(values: Record<string, unknown>, platform: string, account: string, defaultAccount: string, groups: unknown): { agent: string; shared: boolean } {+ const rows = agentRows(values);+ const fallback = string((rows.find(row => row.default === true) ?? rows[0])?.id) || 'main';+ const bindings = (Array.isArray(values.bindings) ? values.bindings : []).map(object)+ .filter(binding => (binding.type ?? 'route') === 'route' && string(object(binding.match).channel).toLowerCase() === platform)+ .filter(binding => {+ const id = object(binding.match).accountId;+ // An omitted accountId matches only the default account; "*" matches every account.+ return id === '*' || (id === undefined ? account === defaultAccount : String(id) === account);+ });+ const wide = bindings.filter(binding => Object.keys(object(binding.match)).every(key => key === 'channel' || key === 'accountId'));+ const exact = wide.find(binding => object(binding.match).accountId !== '*') ?? wide.find(binding => object(binding.match).accountId === '*');+ const agent = string(exact?.agentId) || fallback;+ const routed = Object.values(object(groups)).flatMap(group => [object(group).agentId, ...Object.values(object(object(group).topics)).map(topic => object(topic).agentId)]);+ return { agent, shared: bindings.some(binding => string(binding.agentId) !== agent) || routed.some(id => typeof id === 'string' && id !== agent) };+}++async function openclawBots(source: ImportSource, values: Record<string, unknown>, env: Record<string, string>, deps: SourceReaderDeps, budget: ImportReadBudget, readText = optionalText, allAgents = false): Promise<SourceBot[]> {+ const channels = object(values.channels);+ const ownerAllowFrom = listOf(object(values.commands).ownerAllowFrom);+ const bots: SourceBot[] = [];+ for (const platform of ['telegram', 'discord', 'feishu'] as const) {+ if (!Object.hasOwn(channels, platform)) continue;+ const channel = object(channels[platform]);+ const configured = object(channel.accounts);+ const multi = Object.keys(configured).length > 0;+ const defaultAccount = string(channel.defaultAccount) || 'default';+ const { accounts: _accounts, defaultAccount: _default, ...base } = channel;+ for (const account of multi ? Object.keys(configured) : ['default']) {+ // Same inheritance as OpenClaw: authored account fields override channel defaults.+ const own = multi ? object(configured[account]) : {};+ const merged = { ...base, ...own };+ const route = openclawRoute(values, platform, account, defaultAccount, merged.groups);+ if (!allAgents && route.agent !== source.agentId) continue;+ const enabled = !sourceDisabled(channel.enabled) && !sourceDisabled(merged.enabled);+ const enabledPath = multi ? ['channels', platform, 'accounts', account, 'enabled'] : ['channels', platform, 'enabled'];+ const name = sourceBotName(source, account, merged.name);+ const prefixed = (prefix: string, pattern: RegExp) => userIds(ownerAllowFrom.filter(entry => String(entry).toLowerCase().startsWith(`${prefix}:`)), [`${prefix}:`], pattern);+ if (platform === 'feishu') {+ const appId = secretReference(merged.appId), appSecret = secretReference(merged.appSecret);+ if (!appId || !appSecret) continue;+ const domain = string(merged.domain);+ const pattern = /^ou_[A-Za-z0-9_-]{1,128}$/;+ const owners = prefixed('feishu', pattern);+ const allowed = owners.length ? owners : userIds(listOf(merged.allowFrom), ['feishu:', 'lark:'], pattern);+ const owner = allowed.length === 1 ? allowed[0] : undefined;+ bots.push({ platform, account, name, credential: { appId, appSecret }, service: domain === 'lark' || /larksuite/i.test(domain) ? 'lark' : 'feishu',+ enabled, enabledPath, shared: route.shared, ...(owner ? { owner } : {}) });+ continue;+ }+ let token = platform === 'telegram' ? '' : secretReference(merged.token);+ // Telegram: account tokenFile / botToken, then the channel's (OpenClaw's own resolution order).+ if (platform === 'telegram') for (const [tokenFile, value] of [[own.tokenFile, own.botToken], [channel.tokenFile, channel.botToken]]) {+ if (typeof tokenFile === 'string' && tokenFile.trim()) {+ const file = sourcePath(deps.home, tokenFile, source.root);+ token = (await readText(path.dirname(file), file, budget))?.trim() ?? '';+ }+ token ||= secretReference(value);+ if (token) break;+ }+ const variable = `${platform.toUpperCase()}_BOT_TOKEN`;+ if (!token && account === 'default' && env[variable]) token = `\${${variable}}`;+ if (!token) continue;+ const pattern = platform === 'telegram' ? TELEGRAM_USER_ID : DISCORD_USER_ID;+ const owners = prefixed(platform, pattern);+ const allowFrom = platform === 'telegram' ? merged.allowFrom+ : [own.allowFrom, object(own.dm).allowFrom, channel.allowFrom, object(channel.dm).allowFrom].find(entry => entry !== undefined);+ const allowed = owners.length ? owners : userIds(listOf(allowFrom), platform === 'telegram' ? ['telegram:', 'tg:'] : ['discord:', 'user:'], pattern);+ bots.push({ platform, account, name, credential: { token }, enabled, enabledPath, shared: route.shared, ...inferOwner(allowed) });+ }+ }+ return bots;+}++/** WeCom / DingTalk on OpenClaw are external plugins with no published config shape; they are not guessed. */+async function sourceBots(source: ImportSource, values: Record<string, unknown>, env: Record<string, string>, deps: SourceReaderDeps, budget: ImportReadBudget, readText = optionalText, allAgents = false): Promise<SourceBot[]> {+ return source.kind === 'hermes' ? hermesBots(source, values, env) : openclawBots(source, values, env, deps, budget, readText, allAgents);+}++/** One entry per bot; an ambiguous owner offers up to five exclusive alternatives, none preselected. */+function pushBotItems(items: ImportItem[], bots: SourceBot[]) {+ for (const bot of bots) {+ const references = [...new Set(Object.values(bot.credential).flatMap(value => [...value.matchAll(REFERENCE)].map(match => match[1]!)))];+ const selected = bot.enabled && !bot.shared;+ const item = (id: string, owner: string | undefined, view: Partial<ImportItem['view']> = {}): ImportItem => ({+ view: { id, category: 'bots', platform: bot.platform, name: bot.name, selected, ...(bot.enabled ? {} : { enabled: false }),+ dependsOn: references.map(key => entryId('env', key)), ...(owner ? { owner } : {}), ...view },+ envDependencies: { names: references, entries: [] },+ credential: { format: bot.platform, value: { ...bot.credential, account: bot.account, ...(bot.service ? { service: bot.service } : {}), ...(owner ? { ownerUserId: owner } : {}) } },+ bot: { platform: bot.platform, account: bot.account, enabledPath: bot.enabledPath },+ });+ const id = entryId(bot.platform, bot.account);+ const candidates = bot.owner ? [] : bot.ownerCandidates ?? [];+ if (bot.owner || (bot.platform !== 'telegram' && bot.platform !== 'discord')) items.push(item(id, bot.owner));+ else if (candidates.length > 1 && candidates.length <= BOT_OWNER_ALTERNATIVES) {+ const ids = candidates.map(owner => entryId(bot.platform, `${bot.account}\0owner:${owner}`));+ candidates.forEach((owner, index) => items.push(item(ids[index]!, owner, { selected: false, exclusiveWith: ids.filter((_id, other) => other !== index) })));+ } else items.push(item(id, undefined, { issues: ['IMPORT_IM_BOT_OWNER_MISSING'] }));+ }+}++/** Current source switch for one imported bot, re-read from its native config. */+export async function readImportSourceBot(source: ImportSource, bot: NonNullable<ImportItem['bot']>): Promise<{ enabled: boolean; present: boolean; value?: unknown }> {+ const values = await config(path.dirname(source.configFile), source.configFile, createImportBudget());+ let parent: Record<string, unknown> = values;+ for (const key of bot.enabledPath.slice(0, -1)) parent = object(parent[key]);+ const key = bot.enabledPath.at(-1)!;+ const present = Object.hasOwn(parent, key);+ const channelOff = source.kind === 'openclaw' && sourceDisabled(object(object(values.channels)[bot.platform]).enabled);+ return { enabled: !channelOff && !(present && sourceDisabled(parent[key])), present, ...(present ? { value: parent[key] } : {}) };+}+function sourceConfiguration(items: ImportItem[], source: ImportSource, values: Record<string, unknown>) {const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;const tools = source.kind === 'openclaw' ? { ...(values.tools ? { global: values.tools } : {}), ...(row.tools ? { agent: row.tools } : {}) } : object(values.tools);@@ -310,6 +523,8 @@ export function createImportSourceReader(deps: SourceReaderDeps, budget = create? { credential: { format: 'source-tools', value: { apiKey: settings.apiKey } } } : {}) });}await connections(items, source, values, deps, budget, readText);+ // Mask every bot credential, including bots routed to other agents and platforms the legacy path skips.+ pushBotItems(items, await sourceBots(source, values, await sourceEnvironment(source, values, budget, readText), deps, budget, readText, true));sourceConfiguration(items, source, values);return previewImportRedactions(items);};@@ -317,7 +532,7 @@ export function createImportSourceReader(deps: SourceReaderDeps, budget = create}/** Snapshot immutable bytes once, then give the client only a safe selection projection. */-export async function inspectImportSource(source: ImportSource, deps: SourceReaderDeps, budget = createImportBudget()): Promise<ImportSnapshot> {+export async function inspectImportSource(source: ImportSource, deps: SourceReaderDeps, budget = createImportBudget(), options: { bots?: boolean } = {}): Promise<ImportSnapshot> {const values = await config(path.dirname(source.configFile), source.configFile, budget);const items: ImportItem[] = [];const workspace = source.workspace;@@ -385,7 +600,7 @@ export async function inspectImportSource(source: ImportSource, deps: SourceReaditem.envDependencies = { names: Object.keys(item.env), entries: [] };delete item.env;}- await connections(items, source, values, deps, budget);+ await connections(items, source, values, deps, budget, optionalText, options.bots === true);if (source.kind === 'hermes' && (await directories(source.root)).includes('scripts')) {for (const file of await readImportTree(path.join(source.root, 'scripts'), undefined, budget)) items.push({ view: { id: entryId('script', file.name), category: 'connections', name: `scripts/${file.name}`, selected: true }, asset: { name: `scripts/${file.name}`, bytes: file.bytes, executable: file.executable } });}diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.tsindex 17df032fc2..945cc5282d 100644--- a/apps/desktop/src/main/bot-import/transfer.ts+++ b/apps/desktop/src/main/bot-import/transfer.ts@@ -8,6 +8,7 @@ import { normalizeImportSkill, readImportSkillTree } from './skills.js';import { indexAutomationDependencies, normalizeAutomation } from './sourceAutomations.js';import { memoryFileContent } from './memoryFiles.js';import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';+import type { ImportBotRecord } from './botTakeover.js';export interface ImportReceipt {selectionHash: string;@@ -29,6 +30,8 @@ export interface ImportReceipt {/** Durable fence: a deleted companion's old preview/request must never recreate it. */cancelled?: boolean;routines: Record<string, { id: string; phase: 'created' | 'verified' | 'pausing-source' | 'source-paused' | 'complete'; sourceRestored?: boolean }>;+ /** `bots` entries: source stop / companion connect progress, by entry ID. */+ bots?: Record<string, ImportBotRecord>;}export interface TransferDeps {@@ -55,6 +58,11 @@ export interface TransferDeps {* Resolves to an advisory issue code when it could not; the credential stays saved for delivery.*/connectImBot?(botId: string, item: ImportItem): Promise<string | undefined>;+ /**+ * `bots` entries: stop the bot in the source agent, then connect it as the companion's own.+ * `save` persists the durable progress record; resolves to an advisory issue code.+ */+ takeOverImBot?(botId: string, item: ImportItem, record: ImportBotRecord | undefined, save: (record: ImportBotRecord | undefined) => Promise<void>): Promise<string | undefined>;}/** Advisory outcomes of connecting an imported bot. They never block automations that only deliver through it. */@@ -63,6 +71,7 @@ export const IMPORT_IM_BOT_ISSUES: ReadonlySet<string> = new Set(['IMPORT_IM_BOT_GATEWAY_RUNNING','IMPORT_IM_BOT_IN_USE','IMPORT_IM_BOT_CONNECT_FAILED',+ 'IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED',]);const IM_BOT_FORMATS = new Set(['telegram', 'discord']);@@ -96,6 +105,9 @@ export function validateImportSelection(value: CompanionImportSelection, snapshoconst items = snapshot.items.filter(item => ranges ? item.sourceIndex !== undefined && remaining.delete(item.sourceIndex) : selected.has(item.view.id));if (items.length !== count || remaining.size) throw new CompanionImportError('SELECTION_CHANGED');selectedImportEnvironment(items);+ // Owner alternatives of one bot are mutually exclusive, like conflicting env accounts.+ const chosen = new Set(items.map(item => item.view.id));+ if (items.some(item => item.view.category === 'bots' && item.view.exclusiveWith?.some(id => chosen.has(id)))) throw new CompanionImportError('INVALID_SELECTION');return resolveImportEnvironmentDependencies(items);}@@ -264,7 +276,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comreceipt.companionCreated = true;await save();// Retry only selected resources; saved batches skip completed idempotent copies.- for (const item of items.filter(item => item.view.category !== 'automations' && item.view.category !== 'connections')) {+ for (const item of items.filter(item => !['automations', 'connections', 'bots'].includes(item.view.category))) {if (copied.has(item.view.id)) continue;deps.assertOwner();try {@@ -286,16 +298,28 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comreceipt.environmentSaved = true;await save();}- for (const item of items.filter(item => item.view.category === 'connections')) {+ for (const item of items.filter(item => item.view.category === 'connections' || item.view.category === 'bots')) {let issue = item.view.dependsOn?.some(id => !selected.has(id)) ? 'AUTOMATION_DEPENDENCY_NOT_SELECTED' : item.view.issues?.[0];- if (!issue && deps.connectImBot && IM_BOT_FORMATS.has(item.credential?.format ?? '')) {- const index = checkIndexes.get(item.view.id);- const prior = index === undefined ? undefined : receipt.result.checks[index]?.message;+ const id = item.view.id;+ const index = checkIndexes.get(id);+ const prior = index === undefined ? undefined : receipt.result.checks[index]?.message;+ if (!issue && item.view.category === 'bots' && deps.takeOverImBot) {+ // Reconciliation resumes an interrupted takeover, but never retries a reported outcome on its own.+ issue = reconcileOnly && prior ? prior : await deps.takeOverImBot(botId, item, receipt.bots?.[id], async record => {+ receipt.bots ??= {};+ if (record) receipt.bots[id] = record; else delete receipt.bots[id];+ await save();+ });+ deps.assertOwner();+ check(id, issue ? 'needs-attention' : 'taken-over', issue);+ continue;+ }+ if (!issue && item.view.category === 'connections' && deps.connectImBot && IM_BOT_FORMATS.has(item.credential?.format ?? '')) {// Background reconciliation keeps an earlier advisory outcome instead of retrying the platform.issue = reconcileOnly && prior && IMPORT_IM_BOT_ISSUES.has(prior) ? prior : await deps.connectImBot(botId, item);deps.assertOwner();}- check(item.view.id, issue ? 'needs-attention' : 'copied', issue);+ check(id, issue ? 'needs-attention' : 'copied', issue);}receipt.result.canonicalSessionId = await deps.createConversation(botId);await save();@@ -386,7 +410,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com}}receipt.result.savedEntryIds = [...new Set([...receipt.copied,- ...items.filter(item => item.view.category === 'connections' && receipt.environmentSaved).map(item => item.view.id),+ ...items.filter(item => (item.view.category === 'connections' || item.view.category === 'bots') && receipt.environmentSaved).map(item => item.view.id),...Object.keys(receipt.routines),])];receipt.result.saved = true;diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.tsindex 83eacd9bb1..ae364e5430 100644--- a/apps/desktop/src/main/bot-import/types.ts+++ b/apps/desktop/src/main/bot-import/types.ts@@ -1,4 +1,5 @@import type {+ CompanionImportBotPlatform,CompanionImportEntry,CompanionImportSourceKind,} from '@cindy/maker-shared/companion-import';@@ -60,6 +61,8 @@ export interface ImportItem {envDependencies?: { names: string[]; entries: string[] };mcp?: ImportedMcpServer;credential?: { format: string; value: unknown };+ /** `bots` entries: where the source enables this bot, so the import can stop and restore it. */+ bot?: { platform: CompanionImportBotPlatform; account: string; enabledPath: string[] };asset?: { name: string; bytes: Buffer; executable?: boolean };automation?: {sourceId: string;diff --git a/apps/desktop/src/main/bot-import/verification.ts b/apps/desktop/src/main/bot-import/verification.tsindex 945baf827c..1c642d9f19 100644--- a/apps/desktop/src/main/bot-import/verification.ts+++ b/apps/desktop/src/main/bot-import/verification.ts@@ -155,7 +155,7 @@ export async function verifyImportedAutomation(root: string, botId: string, itemif (entry.env) return Object.keys(entry.env).every(name => !isDataVariable(name) || verifiedVariables.has(name));// Files/skills were copied before verification; unknown credentials// cannot be satisfied by a successful read from a different connection.- return !!entry.asset || entry.view.category !== 'connections';+ return !!entry.asset || entry.view.category !== 'connections' && entry.view.category !== 'bots';});const scriptNames = sourceRoot ? [string(item.automation.original.script), string(item.automation.original.monitor_script)].filter(Boolean).map(value => importedScriptName(sourceRoot, value)) : [];diff --git a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx b/apps/desktop/src/renderer/features/bots/BotImportForm.tsxindex 59bf2e8cdd..a91fafc684 100644--- a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx+++ b/apps/desktop/src/renderer/features/bots/BotImportForm.tsx@@ -1,7 +1,7 @@import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';-import { companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, type CompanionImportCategory, type CompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';+import { companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, type CompanionImportCategory, type CompanionImportEntry, type CompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';import { normalizeBotName } from '../../../shared/botCreation';import { BOT_PORTRAIT_COUNT, BotPortraitPicker, galleryPortrait } from './BotPortraitPicker';import { useBotProfiles } from './botStore';@@ -13,6 +13,8 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack}) {const { t } = useTranslation();const tr = (key: string) => t(`bots.import.${key}`);+ // Bots read as "platform · name"; their owner alternatives differ only by owner ID.+ const entryLabel = (entry: CompanionImportEntry) => entry.platform ? `${t(`bots.channels.platform.${entry.platform}`)} · ${entry.name}` : entry.name;const bots = useBotProfiles();const [sources, setSources] = useState<CompanionImportSource[]>();const [preview, setPreview] = useState<CompanionImportPreview>();@@ -91,8 +93,9 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBackopenedRequest.current = result.requestId;onCreated(result.botId);}, [enterChat, result, onCreated]);+ const entriesById = new Map(preview?.entries.map(entry => [entry.id, entry]));const categoryEntries = preview?.entries.filter(entry => entry.category === category) ?? [];- const filtered = categoryEntries.filter(entry => `${entry.name} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));+ const filtered = categoryEntries.filter(entry => `${entryLabel(entry)} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));const openCategory = (next: CompanionImportCategory) => { setCategory(next); setQuery(''); setPage(0); };const checkbox = (ids: string[], checked: boolean, label: string, partial = false) => <input type="checkbox" aria-label={label}disabled={locked} checked={checked} ref={node => { if (node) node.indeterminate = partial; }} onChange={event => toggle(ids, event.target.checked)}@@ -114,7 +117,7 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack<Button variant="secondary" onClick={() => { setDetails(!details); setDetailPage(0); }}>{tr('details')} · {outstanding.length}</Button>{details ? <div className="space-y-3">{outstanding.slice(detailPage * 20, (detailPage + 1) * 20).map(check => <div key={check.entryId} className="break-words text-13">- <p className="text-[var(--text-primary)]">{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('itemAttention')}</p>+ <p className="text-[var(--text-primary)]">{entriesById.has(check.entryId) ? entryLabel(entriesById.get(check.entryId)!) : tr('itemAttention')}</p><p className="text-[var(--text-secondary)]">{tr(check.progress?.saved ? 'partlySaved' : savedIds.has(check.entryId) ? 'savedNeedsSetup' : 'notSaved')} · {tr(companionImportReasonKey(check.message))}</p>{check.progress ? <p className="text-[var(--text-secondary)]">{check.progress.saved} / {check.progress.total}</p> : null}</div>)}@@ -131,13 +134,15 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack</div> : category ? <section className="space-y-3"><div className="flex items-center justify-between gap-3"><h3 className="text-16 font-medium">{tr(category)}</h3><label className="flex items-center gap-2 text-13">{checkbox(categoryEntries.map(entry => entry.id), areCompanionImportEntriesSelected(categoryEntries, selected), tr('selectAll'))}{tr('selectAll')}</label></div>- <input type="search" aria-label={tr('search')} placeholder={tr('search')} value={query} onChange={event => { setQuery(event.target.value); setPage(0); }}- className="h-9 w-full rounded-full border border-[var(--border-default)] bg-[var(--confirm-bg)] px-3 text-14 text-[var(--text-primary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]" />+ {category !== 'bots' || categoryEntries.length > 20 ? <input type="search" aria-label={tr('search')} placeholder={tr('search')} value={query} onChange={event => { setQuery(event.target.value); setPage(0); }}+ className="h-9 w-full rounded-full border border-[var(--border-default)] bg-[var(--confirm-bg)] px-3 text-14 text-[var(--text-primary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]" /> : null}<div className="divide-y divide-[var(--border-default)]">{filtered.slice(page * 20, (page + 1) * 20).map(entry => <label key={entry.id} className="flex min-h-11 cursor-pointer items-start gap-3 py-3">- <span className="flex h-5 shrink-0 items-center">{checkbox([entry.id], selectedSet.has(entry.id), entry.name)}</span>- <span className="min-w-0 flex-1 break-words text-14">{entry.name}{entry.description ? <span className="mt-1 line-clamp-2 block text-13 text-[var(--text-secondary)]">{entry.description}</span> : null}</span>- {entry.enabled === false ? <span className="shrink-0 text-12 text-[var(--text-secondary)]">{tr('paused')}</span> : null}+ <span className="flex h-5 shrink-0 items-center">{checkbox([entry.id], selectedSet.has(entry.id), entryLabel(entry))}</span>+ <span className="min-w-0 flex-1 break-words text-14">{entryLabel(entry)}+ {entry.owner && entry.exclusiveWith?.length ? <span className="mt-1 block text-13 text-[var(--text-secondary)]">{t('bots.import.botOwner', { id: entry.owner })}</span> : null}+ {entry.description ? <span className="mt-1 line-clamp-2 block text-13 text-[var(--text-secondary)]">{entry.description}</span> : null}</span>+ {entry.enabled === false ? <span className="shrink-0 text-12 text-[var(--text-secondary)]">{tr(entry.category === 'bots' ? 'sourceDisabled' : 'paused')}</span> : null}</label>)}</div>{filtered.length > 20 ? <div className="flex items-center justify-between gap-3"><Button variant="secondary" disabled={page === 0} onClick={() => setPage(page - 1)}>{tr('previous')}</Button><span className="text-13 text-[var(--text-secondary)]">{page + 1} / {Math.ceil(filtered.length / 20)}</span><Button variant="secondary" disabled={(page + 1) * 20 >= filtered.length} onClick={() => setPage(page + 1)}>{tr('next')}</Button></div> : null}@@ -157,7 +162,8 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBackreturn <div key={group} className="flex min-h-12 items-center gap-3 py-1">{checkbox(entries.map(item => item.id), allSelected, tr(group), count > 0 && !allSelected)}<button type="button" disabled={locked} className="flex min-h-11 min-w-0 flex-1 items-center justify-between gap-3 text-left text-14" onClick={() => openCategory(group)}>- <span>{tr(group)}</span><span className="shrink-0 text-[var(--text-secondary)]">{count} / {entries.length} <span aria-hidden="true">›</span></span>+ <span className="min-w-0">{tr(group)}{group === 'bots' ? <span className="mt-1 block text-13 text-[var(--text-secondary)]">{t('bots.import.botsNote', { source: preview.source.kind === 'hermes' ? 'Hermes' : 'OpenClaw' })}</span> : null}</span>+ <span className="shrink-0 text-[var(--text-secondary)]">{count} / {entries.length} <span aria-hidden="true">›</span></span></button></div>;})}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsxindex 67f358e499..b9f3f05733 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx@@ -6,7 +6,7 @@ import { BotImportForm } from '../BotImportForm';const portraits = vi.hoisted(() => ({ load: vi.fn(async (index: number) => `data:image/png;base64,portrait-${index}`) }));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, options?: Record<string, string>) => options ? `${key} ${Object.values(options).join(' ')}` : key }) }));vi.mock('../botStore', () => ({ useBotProfiles: () => [] }));vi.mock('../BotPortraitPicker', () => ({ BOT_PORTRAIT_COUNT: 17, galleryPortrait: portraits.load, BotPortraitPicker: ({ onChange, disabled }: { onChange(value: string): void; disabled: boolean }) => <button disabled={disabled} onClick={() => onChange('data:image/png;base64,chosen')}>existing-portrait-picker</button> }));beforeEach(() => portraits.load.mockClear());@@ -197,3 +197,29 @@ it('distinguishes partial saves, setup-only checks and failed automations whilefireEvent.click(screen.getByRole('button', { name: 'bots.import.open' }));expect(created).toHaveBeenCalledWith('bot');});++it('shows messaging bots as their own row with the source handover note, owner alternatives and source-disabled bots', async () => {+ const bot = { category: 'bots' as const, name: 'Ada', platform: 'telegram' as const };+ const api: CompanionImportApi = { sources: async () => [{ id: 'source', name: 'Ada', kind: 'hermes' }],+ preview: async () => ({ id: 'preview', name: 'Ada', source: { id: 'source', name: 'Ada', kind: 'hermes' }, entries: [+ { ...bot, id: 'owner-a', owner: '1111', selected: false, exclusiveWith: ['owner-b'] },+ { ...bot, id: 'owner-b', owner: '2222', selected: false, exclusiveWith: ['owner-a'] },+ { id: 'lark', category: 'bots', name: 'Ada Lark', platform: 'feishu', owner: 'ou_fixture', selected: false, enabled: false },+ ] }), status: async () => undefined,+ start: vi.fn(async input => ({ requestId: input.requestId, botId: 'bot', status: 'complete' as const, checks: [] })) };+ render(<BotImportForm api={api} onCreated={() => {}} onBack={() => {}} onBusy={() => {}} />);+ fireEvent.click(await screen.findByRole('button', { name: /Ada.*Hermes/ }));+ fireEvent.click(await screen.findByRole('button', { name: /bots\.import\.bots.*bots\.import\.botsNote Hermes/ }));+ // A short list needs no search box.+ expect(screen.queryByRole('searchbox')).toBeNull();+ expect(screen.getByText('bots.import.botOwner 1111')).toBeTruthy();+ expect(screen.queryByText('bots.import.botOwner ou_fixture')).toBeNull();+ expect(screen.getByText('bots.import.sourceDisabled')).toBeTruthy();+ fireEvent.click(screen.getByLabelText('bots.channels.platform.feishu · Ada Lark'));+ fireEvent.click(screen.getAllByLabelText('bots.channels.platform.telegram · Ada')[0]!);+ fireEvent.click(screen.getAllByLabelText('bots.channels.platform.telegram · Ada')[1]!);+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.back' }));+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));+ // Choosing the other owner replaces the first one.+ await waitFor(() => expect(api.start).toHaveBeenCalledWith(expect.objectContaining({ entryIds: ['lark', 'owner-b'] })));+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b46cf95510..3039738541 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9823,7 +9823,12 @@"imBotOwnerMissing": "No owner user ID was found. Finish connecting this bot on the teammate’s Messaging platforms page.","imBotGatewayRunning": "The original gateway is still using this bot. Stop it, then connect the bot on Messaging platforms.","imBotInUse": "This bot is already connected on this computer, in Settings → IM bots or on another teammate.",- "imBotConnectFailed": "Couldn’t connect this bot. Try again on the teammate’s Messaging platforms page."+ "imBotConnectFailed": "Couldn’t connect this bot. Try again on the teammate’s Messaging platforms page.",+ "imBotSourceStopUnconfirmed": "The original bot hasn’t stopped yet, so it wasn’t handed to the teammate. You can connect it later on the teammate’s Messaging platforms page.",+ "bots": "Messaging bots",+ "botsNote": "After import, these bots stop in {{source}} and the teammate takes them over.",+ "sourceDisabled": "Already off",+ "botOwner": "Owner ID {{id}}"},"learning": {"memory": "Remembered: {{title}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 368c9ed31a..e8d00703eb 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9777,7 +9777,12 @@"imBotOwnerMissing": "オーナーのユーザー ID が見つかりませんでした。仲間の「メッセージプラットフォーム」ページでこのボットを接続してください。","imBotGatewayRunning": "元のゲートウェイがまだこのボットを使っています。停止してから「メッセージプラットフォーム」で接続してください。","imBotInUse": "このボットはすでにこのコンピューターで使われています(設定 → IM ボット、または別の仲間)。",- "imBotConnectFailed": "このボットに接続できませんでした。仲間の「メッセージプラットフォーム」ページでやり直してください。"+ "imBotConnectFailed": "このボットに接続できませんでした。仲間の「メッセージプラットフォーム」ページでやり直してください。",+ "imBotSourceStopUnconfirmed": "元のボットがまだ停止していないため、仲間に引き継いでいません。あとで仲間の「メッセージプラットフォーム」ページで接続できます。",+ "bots": "メッセージボット",+ "botsNote": "インポート後、{{source}} のこれらのボットは停止し、仲間が引き継ぎます。",+ "sourceDisabled": "元から停止中",+ "botOwner": "オーナー ID {{id}}"},"learning": {"memory": "記憶しました:{{title}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 4d1ff050e6..8239666449 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9777,7 +9777,12 @@"imBotOwnerMissing": "소유자 사용자 ID를 찾지 못했습니다. 동료의 메시지 플랫폼 페이지에서 이 봇을 연결하세요.","imBotGatewayRunning": "기존 게이트웨이가 아직 이 봇을 사용 중입니다. 중지한 다음 메시지 플랫폼에서 연결하세요.","imBotInUse": "이 봇은 이미 이 컴퓨터에서 사용 중입니다 (설정 → IM 봇, 또는 다른 동료).",- "imBotConnectFailed": "이 봇에 연결하지 못했습니다. 동료의 메시지 플랫폼 페이지에서 다시 시도하세요."+ "imBotConnectFailed": "이 봇에 연결하지 못했습니다. 동료의 메시지 플랫폼 페이지에서 다시 시도하세요.",+ "imBotSourceStopUnconfirmed": "기존 봇이 아직 멈추지 않아 동료에게 넘기지 않았습니다. 나중에 동료의 메시지 플랫폼 페이지에서 연결할 수 있습니다.",+ "bots": "메시지 봇",+ "botsNote": "가져온 후 {{source}}의 이 봇들은 중지되고 동료가 이어받습니다.",+ "sourceDisabled": "원래 사용 중지됨",+ "botOwner": "소유자 ID {{id}}"},"learning": {"memory": "기억했어요: {{title}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 34eb5ad4fe..a15e8a7f17 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9777,7 +9777,12 @@"imBotOwnerMissing": "没找到主人的用户 ID,请到伙伴的「消息平台」页把这个机器人连上。","imBotGatewayRunning": "原来的网关还在用这个机器人。先停掉它,再到「消息平台」页连接。","imBotInUse": "这个机器人已经在这台电脑上用了:在 设置 → IM 机器人 里,或者在另一位伙伴那里。",- "imBotConnectFailed": "没能连上这个机器人,请到伙伴的「消息平台」页重试。"+ "imBotConnectFailed": "没能连上这个机器人,请到伙伴的「消息平台」页重试。",+ "imBotSourceStopUnconfirmed": "原来的机器人还没停下,暂时没有接给伙伴。可以稍后在伙伴的「消息平台」页连接。",+ "bots": "消息机器人",+ "botsNote": "导入后,{{source}} 里的这些机器人会停用,由伙伴接管。",+ "sourceDisabled": "原来已停用",+ "botOwner": "主人 ID {{id}}"},"learning": {"memory": "已记住:{{title}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0a56cc3ea6..83b57b4513 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9777,7 +9777,12 @@"imBotOwnerMissing": "沒找到主人的使用者 ID,請到夥伴的「訊息平台」頁把這個機器人連上。","imBotGatewayRunning": "原本的閘道還在使用這個機器人。先停掉它,再到「訊息平台」頁連線。","imBotInUse": "這個機器人已經在這台電腦上使用了:在 設定 → IM 機器人 裡,或是在另一位夥伴那裡。",- "imBotConnectFailed": "沒能連上這個機器人,請到夥伴的「訊息平台」頁重試。"+ "imBotConnectFailed": "沒能連上這個機器人,請到夥伴的「訊息平台」頁重試。",+ "imBotSourceStopUnconfirmed": "原本的機器人還沒停下,暫時沒有接給夥伴。可以稍後在夥伴的「訊息平台」頁連線。",+ "bots": "訊息機器人",+ "botsNote": "匯入後,{{source}} 裡的這些機器人會停用,由夥伴接管。",+ "sourceDisabled": "原本已停用",+ "botOwner": "主人 ID {{id}}"},"learning": {"memory": "已記住:{{title}}",diff --git a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsxindex 3e2b462536..b63988f3d6 100644--- a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx+++ b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx@@ -8,7 +8,7 @@ vi.mock('react-native', () => ({Pressable: ({ onPress, children }: any) => createElement('button', { onClick: onPress }, children),Switch: ({ accessibilityLabel, value, disabled, onValueChange }: any) => createElement('input', { type: 'checkbox', 'aria-label': accessibilityLabel, checked: value, disabled, onChange: (e: any) => onValueChange(e.target.checked) }),}));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, options?: Record<string, string>) => options ? `${key} ${Object.values(options).join(' ')}` : key, i18n: { language: 'en' } }) }));vi.mock('expo-crypto', () => ({ randomUUID: () => h.uuid() }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));vi.mock('@/device-link/remoteResources', () => ({ invokeRemoteResourceAction: (...args: unknown[]) => h.submit(...args) }));@@ -227,3 +227,27 @@ it('submits sparse 100,000-entry choices using bounded actions with the original}expect(JSON.parse(text)).toMatchObject({ entryIds: [], entryRanges: entries.filter(entry => entry.selected).map(entry => { const index = Number(entry.id.slice(6)); return [index, index]; }), deferSetup: true });});++it('advertises the bots category and shows bots with the handover note, owner alternatives and source-disabled bots', async () => {+ h.invoke.mockImplementation(async (_host: string, _channel: string, args: any[]) => {+ const id = args[0].ref.id;+ return { blocks: [{ primitive: 'companion-import', data: id === 'sources' ? { sources: [{ id: 'source', name: 'Ada', kind: 'openclaw' }] } : id.startsWith('preview:') ? { preview: { id: 'preview', name: 'Ada', source: { id: 'source', name: 'Ada', kind: 'openclaw' }, entries: [+ { id: 'owner-a', name: 'Ada', category: 'bots', platform: 'discord', owner: '111111111111111111', selected: false, exclusiveWith: ['owner-b'] },+ { id: 'owner-b', name: 'Ada', category: 'bots', platform: 'discord', owner: '222222222222222222', selected: false, exclusiveWith: ['owner-a'] },+ { id: 'lark', name: 'Work', category: 'bots', platform: 'feishu', owner: 'ou_fixture', selected: false, enabled: false },+ ] } } : { result: null } }] };+ });+ const container = document.createElement('div'); root = createRoot(container);+ await act(async () => root!.render(createElement(CompanionImportSheet, { visible: true, deviceId: 'host', deviceName: 'Mac', online: true, onClose() {}, onCreated: h.created })));+ expect(h.invoke.mock.calls[0]![2][0].client.primitives).toContain('companion-import-bots-v1');+ const click = async (text: string) => { await act(async () => { const button = [...container.querySelectorAll('button')].find(button => button.textContent?.startsWith(text)); expect(button).toBeDefined(); button!.click(); }); };+ await click('Ada · OpenClaw');+ expect(container.textContent).toContain('devices.companionImport.botsNote OpenClaw');+ await click('devices.companionImport.bots');+ // A short list needs no search field.+ expect(container.querySelector('input:not([type="checkbox"])')).toBeNull();+ expect(container.textContent).toContain('devices.companionImport.botOwner 222222222222222222');+ expect(container.textContent).not.toContain('devices.companionImport.botOwner ou_fixture');+ expect(container.textContent).toContain('devices.companionImport.sourceDisabled');+ expect(container.querySelector('[aria-label="message.renderer.imPlatform.feishu · Work"]')).not.toBeNull();+});diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex 915946014b..c8ebc1ebd4 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -823,7 +823,12 @@"imBotOwnerMissing": "No owner user ID was found. Finish connecting this bot on the teammate’s Messaging platforms page.","imBotGatewayRunning": "The original gateway is still using this bot. Stop it, then connect the bot on Messaging platforms.","imBotInUse": "This bot is already connected on this computer, in Settings → IM bots or on another teammate.",- "imBotConnectFailed": "Couldn’t connect this bot. Try again on the teammate’s Messaging platforms page."+ "imBotConnectFailed": "Couldn’t connect this bot. Try again on the teammate’s Messaging platforms page.",+ "imBotSourceStopUnconfirmed": "The original bot hasn’t stopped yet, so it wasn’t handed to the teammate. You can connect it later on the teammate’s Messaging platforms page.",+ "bots": "Messaging bots",+ "botsNote": "After import, these bots stop in {{source}} and the teammate takes them over.",+ "sourceDisabled": "Already off",+ "botOwner": "Owner ID {{id}}"},"teammateTodo": {"title": "Todos",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex b12f4fb2d9..5af3d6a55f 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -823,7 +823,12 @@"imBotOwnerMissing": "オーナーのユーザー ID が見つかりませんでした。仲間の「メッセージプラットフォーム」ページでこのボットを接続してください。","imBotGatewayRunning": "元のゲートウェイがまだこのボットを使っています。停止してから「メッセージプラットフォーム」で接続してください。","imBotInUse": "このボットはすでにこのコンピューターで使われています(設定 → IM ボット、または別の仲間)。",- "imBotConnectFailed": "このボットに接続できませんでした。仲間の「メッセージプラットフォーム」ページでやり直してください。"+ "imBotConnectFailed": "このボットに接続できませんでした。仲間の「メッセージプラットフォーム」ページでやり直してください。",+ "imBotSourceStopUnconfirmed": "元のボットがまだ停止していないため、仲間に引き継いでいません。あとで仲間の「メッセージプラットフォーム」ページで接続できます。",+ "bots": "メッセージボット",+ "botsNote": "インポート後、{{source}} のこれらのボットは停止し、仲間が引き継ぎます。",+ "sourceDisabled": "元から停止中",+ "botOwner": "オーナー ID {{id}}"},"teammateTodo": {"title": "Todo",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 715c1c08a2..1fd0d84afa 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -823,7 +823,12 @@"imBotOwnerMissing": "소유자 사용자 ID를 찾지 못했습니다. 동료의 메시지 플랫폼 페이지에서 이 봇을 연결하세요.","imBotGatewayRunning": "기존 게이트웨이가 아직 이 봇을 사용 중입니다. 중지한 다음 메시지 플랫폼에서 연결하세요.","imBotInUse": "이 봇은 이미 이 컴퓨터에서 사용 중입니다 (설정 → IM 봇, 또는 다른 동료).",- "imBotConnectFailed": "이 봇에 연결하지 못했습니다. 동료의 메시지 플랫폼 페이지에서 다시 시도하세요."+ "imBotConnectFailed": "이 봇에 연결하지 못했습니다. 동료의 메시지 플랫폼 페이지에서 다시 시도하세요.",+ "imBotSourceStopUnconfirmed": "기존 봇이 아직 멈추지 않아 동료에게 넘기지 않았습니다. 나중에 동료의 메시지 플랫폼 페이지에서 연결할 수 있습니다.",+ "bots": "메시지 봇",+ "botsNote": "가져온 후 {{source}}의 이 봇들은 중지되고 동료가 이어받습니다.",+ "sourceDisabled": "원래 사용 중지됨",+ "botOwner": "소유자 ID {{id}}"},"teammateTodo": {"title": "할 일",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex 6d432fefce..3e8da0b059 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -823,7 +823,12 @@"imBotOwnerMissing": "没找到主人的用户 ID,请到伙伴的「消息平台」页把这个机器人连上。","imBotGatewayRunning": "原来的网关还在用这个机器人。先停掉它,再到「消息平台」页连接。","imBotInUse": "这个机器人已经在这台电脑上用了:在 设置 → IM 机器人 里,或者在另一位伙伴那里。",- "imBotConnectFailed": "没能连上这个机器人,请到伙伴的「消息平台」页重试。"+ "imBotConnectFailed": "没能连上这个机器人,请到伙伴的「消息平台」页重试。",+ "imBotSourceStopUnconfirmed": "原来的机器人还没停下,暂时没有接给伙伴。可以稍后在伙伴的「消息平台」页连接。",+ "bots": "消息机器人",+ "botsNote": "导入后,{{source}} 里的这些机器人会停用,由伙伴接管。",+ "sourceDisabled": "原来已停用",+ "botOwner": "主人 ID {{id}}"},"teammateTodo": {"title": "待办",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 6fb26849bb..fd75039e33 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -823,7 +823,12 @@"imBotOwnerMissing": "沒找到主人的使用者 ID,請到夥伴的「訊息平台」頁把這個機器人連上。","imBotGatewayRunning": "原本的閘道還在使用這個機器人。先停掉它,再到「訊息平台」頁連線。","imBotInUse": "這個機器人已經在這台電腦上使用了:在 設定 → IM 機器人 裡,或是在另一位夥伴那裡。",- "imBotConnectFailed": "沒能連上這個機器人,請到夥伴的「訊息平台」頁重試。"+ "imBotConnectFailed": "沒能連上這個機器人,請到夥伴的「訊息平台」頁重試。",+ "imBotSourceStopUnconfirmed": "原本的機器人還沒停下,暫時沒有接給夥伴。可以稍後在夥伴的「訊息平台」頁連線。",+ "bots": "訊息機器人",+ "botsNote": "匯入後,{{source}} 裡的這些機器人會停用,由夥伴接管。",+ "sourceDisabled": "原本已停用",+ "botOwner": "主人 ID {{id}}"},"teammateTodo": {"title": "待辦",diff --git a/apps/mobile/src/session/CompanionImportSheet.tsx b/apps/mobile/src/session/CompanionImportSheet.tsxindex b1aa0f999f..2f96fb3bf6 100644--- a/apps/mobile/src/session/CompanionImportSheet.tsx+++ b/apps/mobile/src/session/CompanionImportSheet.tsx@@ -3,7 +3,7 @@ import { Pressable, ScrollView, StyleSheet, Switch, View } from 'react-native';import { randomUUID } from 'expo-crypto';import { useTranslation } from 'react-i18next';import { parseRemoteActionInvokeRequest, REMOTE_RESOURCE_GET_CHANNEL, REMOTE_RESOURCE_PROTOCOL_VERSION, type RemoteResourceRef } from '@cindy/device-link';-import { COMPANION_IMPORT_CHUNK_PRIMITIVE, companionImportSubmissions, companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, remoteCompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';+import { COMPANION_IMPORT_BOTS_PRIMITIVE, COMPANION_IMPORT_CHUNK_PRIMITIVE, companionImportSubmissions, companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, remoteCompanionImportApi, type CompanionImportEntry, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';import { Text, TextInput } from '@/components/AppText';import { MainWindowActionButton } from '@/components/MobilePrimitives';import { useDeviceLink } from '@/device-link/DeviceLinkContext';@@ -17,10 +17,12 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev}) {const { t, i18n } = useTranslation();const tr = (key: string) => t(`devices.companionImport.${key}`);+ // Bots read as "platform · name"; their owner alternatives differ only by owner ID.+ const entryLabel = (entry: CompanionImportEntry) => entry.platform ? `${t(`message.renderer.imPlatform.${entry.platform}`)} · ${entry.name}` : entry.name;const styles = useThemedStyles(makeStyles);const { invoke, openLink } = useDeviceLink();const api = useMemo(() => remoteCompanionImportApi(- async id => { await openLink(deviceId); return invoke(deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{ ref: { collectionId: 'companion-import', kind: 'import', id }, client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: ['companion-import', COMPANION_IMPORT_CHUNK_PRIMITIVE], locale: i18n.language } }]); },+ async id => { await openLink(deviceId); return invoke(deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{ ref: { collectionId: 'companion-import', kind: 'import', id }, client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: ['companion-import', COMPANION_IMPORT_CHUNK_PRIMITIVE, COMPANION_IMPORT_BOTS_PRIMITIVE], locale: i18n.language } }]); },(sourceId, selection) => invokeRemoteResourceAction(invoke, { deviceId, deviceName }, { collectionId: 'companion-import', resourceRef: { collectionId: 'companion-import', kind: 'import', id: `preview:${sourceId}` }, actionId: 'import', input: { ...selection } }, i18n.language),), [deviceId, deviceName, invoke, openLink, i18n.language]);const [sources, setSources] = useState<CompanionImportSource[]>();@@ -106,7 +108,8 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, devonCreated({ collectionId: 'teammates', kind: 'bot', id: result.botId }); onClose();}, [enterChat, result, onCreated, onClose]);const entries = preview?.entries.filter(entry => entry.category === expanded) ?? [];- const filtered = entries.filter(entry => `${entry.name} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));+ const entriesById = new Map(preview?.entries.map(entry => [entry.id, entry]));+ const filtered = entries.filter(entry => `${entryLabel(entry)} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));return <CompanionSheet visible={visible && !enterChat} title={tr('title')} contentScrolls onClose={() => { if (!busy || result) onClose(); }} onClosed={onClosed} preventDismiss={busy && !result}>{!enterChat ? <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content}>{!online || error ? <Text accessibilityRole="alert" style={styles.note}>{!online ? t('devices.companionProfile.offline', { deviceName }) : tr(companionImportReasonKey(error))}</Text> : null}@@ -121,7 +124,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev<MainWindowActionButton action={{ label: `${tr('details')} · ${outstanding.length}`, onPress: () => { setDetails(!details); setDetailPage(0); } }} />{details ? <>{outstanding.slice(detailPage * 20, (detailPage + 1) * 20).map(check => <View key={check.entryId}>- <Text style={styles.label}>{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('itemAttention')}</Text>+ <Text style={styles.label}>{entriesById.has(check.entryId) ? entryLabel(entriesById.get(check.entryId)!) : tr('itemAttention')}</Text><Text style={styles.note}>{tr(check.progress?.saved ? 'partlySaved' : savedIds.has(check.entryId) ? 'savedNeedsSetup' : 'notSaved')} · {tr(companionImportReasonKey(check.message))}</Text>{check.progress ? <Text style={styles.count}>{check.progress.saved} / {check.progress.total}</Text> : null}</View>)}@@ -135,8 +138,11 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev</> : expanded ? <><MainWindowActionButton action={{ label: tr('back'), onPress: () => setExpanded('') }} /><View style={styles.row}><Text style={[styles.label, styles.expand]}>{tr(expanded)}</Text><Switch accessibilityLabel={tr('selectAll')} disabled={locked} value={areCompanionImportEntriesSelected(entries, selected)} onValueChange={checked => toggle(entries.map(entry => entry.id), checked)} /></View>- <TextInput accessibilityLabel={tr('search')} placeholder={tr('search')} value={query} onChangeText={value => { setQuery(value); setPage(0); }} style={styles.input} />- {filtered.slice(page * 20, (page + 1) * 20).map(entry => <View key={entry.id} style={styles.row}><View style={styles.expand}><Text style={styles.label}>{entry.name}</Text>{entry.description ? <Text numberOfLines={2} style={styles.note}>{entry.description}</Text> : null}{entry.enabled === false ? <Text style={styles.note}>{tr('paused')}</Text> : null}</View><Switch accessibilityLabel={entry.name} value={selectedSet.has(entry.id)} disabled={locked} onValueChange={value => toggle([entry.id], value)} /></View>)}+ {expanded !== 'bots' || entries.length > 20 ? <TextInput accessibilityLabel={tr('search')} placeholder={tr('search')} value={query} onChangeText={value => { setQuery(value); setPage(0); }} style={styles.input} /> : null}+ {filtered.slice(page * 20, (page + 1) * 20).map(entry => <View key={entry.id} style={styles.row}><View style={styles.expand}><Text style={styles.label}>{entryLabel(entry)}</Text>+ {entry.owner && entry.exclusiveWith?.length ? <Text style={styles.note}>{t('devices.companionImport.botOwner', { id: entry.owner })}</Text> : null}+ {entry.description ? <Text numberOfLines={2} style={styles.note}>{entry.description}</Text> : null}{entry.enabled === false ? <Text style={styles.note}>{tr(entry.category === 'bots' ? 'sourceDisabled' : 'paused')}</Text> : null}</View>+ <Switch accessibilityLabel={entryLabel(entry)} value={selectedSet.has(entry.id)} disabled={locked} onValueChange={value => toggle([entry.id], value)} /></View>)}{filtered.length > 20 ? <View style={styles.row}><MainWindowActionButton action={{ label: tr('previous'), disabled: page === 0, onPress: () => setPage(page - 1) }} /><Text style={styles.count}>{page + 1} / {Math.ceil(filtered.length / 20)}</Text><MainWindowActionButton action={{ label: tr('next'), disabled: (page + 1) * 20 >= filtered.length, onPress: () => setPage(page + 1) }} /></View> : null}</> : <><Text style={styles.label}>{t('devices.companionProfile.name')}</Text>@@ -146,7 +152,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, devconst group = preview.entries.filter(entry => entry.category === category);if (!group.length) return null;const count = group.filter(entry => selectedSet.has(entry.id)).length;- return <View key={category} style={styles.row}><Pressable accessibilityRole="button" style={styles.expand} disabled={locked} onPress={() => { setExpanded(category); setQuery(''); setPage(0); }}><Text style={styles.label}>{tr(category)}</Text><Text style={styles.count}>{count} / {group.length}</Text></Pressable><Switch accessibilityLabel={tr(category)} value={areCompanionImportEntriesSelected(group, selected)} disabled={locked} onValueChange={value => toggle(group.map(entry => entry.id), value)} /></View>;+ return <View key={category} style={styles.row}><Pressable accessibilityRole="button" style={styles.expand} disabled={locked} onPress={() => { setExpanded(category); setQuery(''); setPage(0); }}><Text style={styles.label}>{tr(category)}</Text>{category === 'bots' ? <Text style={styles.note}>{t('devices.companionImport.botsNote', { source: preview.source.kind === 'hermes' ? 'Hermes' : 'OpenClaw' })}</Text> : null}<Text style={styles.count}>{count} / {group.length}</Text></Pressable><Switch accessibilityLabel={tr(category)} value={areCompanionImportEntriesSelected(group, selected)} disabled={locked} onValueChange={value => toggle(group.map(entry => entry.id), value)} /></View>;})}{preview.entries.some(entry => entry.category === 'automations' && selectedSet.has(entry.id)) ? <View style={styles.row}><Text style={[styles.note, styles.expand]}>{tr('takeover')}</Text><Switch accessibilityLabel={tr('takeover')} value={takeover} disabled={locked} onValueChange={setTakeover} /></View> : null}</>}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 697a030b3b..7477117eda 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2232,3 +2232,11 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca`:switch-home` / `:home-choices`,并新增 `:attachment`、`:cindy-copies`、`:merge-cindy` 与 `maker:companion-avatar:resolve`,只在同一个 Desktop 内的 preload 与 Main 之间使用。伙伴资料快照 `companion.profile.v1` 新增可选的 `templateId`;新增偏好键 `companion.todo.v1:<id>`、`companion.routine.v1:<id>`、`companion.workbench.v1`,旧客户端不认识这些键,接管时忽略。镜像上传的房间消息可带 `media` 块;旧客户端按文件名显示。手机端同样不改原生指纹。++## 伙伴导入的消息机器人分类++`companion-import` Remote Resource 的 client primitives 可追加 `companion-import-bots-v1`。只有声明它的控制端+(以及本机界面与 `import_agent`)的预览才会收到 `category: 'bots'` 条目及其可选 `platform` / `owner` 字段,导入时+会先在来源 Agent 里停用这些机器人再由伙伴连接;旧控制端的预览校验不认识新分类,所以照旧把 Telegram / Discord+放在 `connections`、不停来源,也不出现飞书 / 企业微信 / 钉钉条目。分类随预览快照与加密检查点保存,开始导入和恢复+都按当时的分类执行。不改 relay 帧、服务端 schema 或 Mobile 原生指纹。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 8e4af93ac6..648ebd0708 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -89,9 +89,10 @@ Discord 传输层只放行主人,钉钉群里被 @ 时成员也能触发(成「消息平台」页每条连接下有「隐藏任务」小节:列出这条连接名下的主人私聊(伙伴主任务)与各群 / 话题 / 外部用户私聊专线,每条可「重新开始」——复用伙伴已有的 `restartBotCanonicalRuntime` 交接(同一条任务、记录与记忆不删,下一条消息换干净的原生会话),不另写换会话逻辑,见 `im/shared/botImLaneRuntime.ts`。-本机 Hermes / OpenClaw 导入(见文末同名一节)读到 Telegram / Discord bot token 且能确定唯一主人 id 时,在伙伴建好后-直接用同一个 `addBotImConnection` 建成这位伙伴的连接;读不到主人或连不上时导入照常完成,该项标「需处理」并说明原因,-用户可之后在「消息平台」页补连。+本机 Hermes / OpenClaw 导入(见文末同名一节)把来源的消息机器人(Telegram / Discord / 飞书,Hermes 另有企业微信 / 钉钉)+列成单独一行「消息机器人」、默认勾选;导入时先用来源自己的命令把它在原 Agent 里停掉并确认停下,再用同一个+`addBotImConnection` 建成这位伙伴的连接,连不上就把原开关还原。主人不明、停不下或连不上时导入照常完成,该项标「需处理」,+用户可之后在「消息平台」页补连。没声明 `companion-import-bots-v1` 的旧控制端仍走原来的「环境与连接」路径,不停来源。实现见 `im/shared/botImConnectionStore.ts`(记录)、`im/shared/botImConnectionRuntime.ts`(实例生命周期)、`im/shared/imBotBindingRuntime.ts` 与 `im/shared/turnRunner.ts`(落点解析)、`localDb/ipc/bots.ts`(专线创建);官方 Cindy bot、其它个人渠道与「代主人收发」沿后续分期接入同一骨架。@@ -953,7 +954,7 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘- 导入页用分类汇总和可搜索、分页的单层列表;保存完成后直接进入伙伴聊天,不在完成页堆叠逐项待办。- 先保存资料、连接与停用状态的自动化定义,再在聊天中完成登录和验证;用户可以稍后处理,普通聊天始终可用。- 新导入的自动化结果统一进入 Cindy 伙伴聊天,不校验或沿用原发送渠道。存量已导入自动化不自动改渠道。-- Telegram / Discord bot token 在能确定唯一主人 id 时建成伙伴自己的连接(见 §2);主人不明、原网关仍在用或连不上只标「需处理」并说明原因,不让导入失败,凭证照常保存,也不阻塞依赖它的自动化。+- 消息机器人单独一行、默认勾选(来源里本已停用的不勾,并标「原来已停用」);导入即从原 Agent 停用后由伙伴接管(见 §2),只撤销本次导入做过的改动。主人不明时最多列出 5 个候选主人互斥选择,更多或没有则标「需处理」;停不下、原网关仍在用或连不上同样只标「需处理」并说明原因,不让导入失败,也不阻塞依赖它的自动化。- 全量保留来源资料、技能及自动化(包括原生 Heartbeat、未知触发条件、空标记文件),仅排除用户主动取消的项目。暂不能转换的自动化仍保存为可见的停用任务和加密原始定义,明确提示待适配项;不能因 Cindy 暂缺能力或原投放渠道不可用而过滤。验收对照来源总清单,不以过滤后的已选数量冒充完整。- 单项读取或写入失败保留重试记录,不中止其它内容;导入成功数量与自动化启用状态分别计算。文件字节保护仍适用,不截断文件冒充完整导入。- 原任务在验证及接管完成前保持原状。明确选用 Cindy 模型和工具设置后可解除相应兼容性待办,仍须验证数据并确认原任务已暂停,才能启用 Cindy 任务。diff --git a/packages/maker-shared/src/companionImport.ts b/packages/maker-shared/src/companionImport.tsindex cc908c472a..8c61751780 100644--- a/packages/maker-shared/src/companionImport.ts+++ b/packages/maker-shared/src/companionImport.ts@@ -1,6 +1,7 @@/** Public import projection. Source paths, credentials and configuration stay on the owning host. */export type CompanionImportSourceKind = 'hermes' | 'openclaw';-export type CompanionImportCategory = 'personality' | 'memory' | 'skills' | 'connections' | 'automations';+export type CompanionImportCategory = 'personality' | 'memory' | 'skills' | 'bots' | 'connections' | 'automations';+export type CompanionImportBotPlatform = 'telegram' | 'discord' | 'feishu' | 'wecom' | 'dingtalk';export interface CompanionImportSource {id: string;@@ -21,6 +22,10 @@ export interface CompanionImportEntry {exclusiveWith?: string[];/** An explicit compatibility problem, never silently discarded configuration. */issues?: string[];+ /** `bots` only: messaging platform of the source bot. */+ platform?: CompanionImportBotPlatform;+ /** `bots` only: inferred owner id on that platform; alternatives differ only by owner. */+ owner?: string;}export interface CompanionImportPreview {@@ -90,7 +95,7 @@ export interface CompanionImportApi {status(requestId: string): Promise<CompanionImportResult | undefined>;}-export const companionImportCategories: CompanionImportCategory[] = ['personality', 'memory', 'skills', 'connections', 'automations'];+export const companionImportCategories: CompanionImportCategory[] = ['personality', 'memory', 'skills', 'bots', 'connections', 'automations'];/** Preserve exact choices while keeping large selections below the existing action budget. */export function compactCompanionImportSelection(preview: CompanionImportPreview, selected: string[]): Pick<CompanionImportSelection, 'entryIds' | 'entryRanges'> {@@ -149,6 +154,12 @@ export function companionImportIssueKey(code?: string): string {export const COMPANION_IMPORT_CHUNK_PRIMITIVE = 'companion-import-chunks-v1';export const COMPANION_IMPORT_CHUNK_LENGTH = 256 * 1024;export const COMPANION_IMPORT_READ_MAX_LENGTH = 128 * 1024 * 1024;+/**+ * Additive preview capability: the controller renders the `bots` category, and importing a+ * bot stops it in the source agent before the teammate connects it. Controllers without it+ * keep receiving those bots under `connections`, with no source stop.+ */+export const COMPANION_IMPORT_BOTS_PRIMITIVE = 'companion-import-bots-v1';/** Transport-neutral client: Desktop and Mobile use their existing Remote Resource adapters. */export function remoteCompanionImportApi(@@ -239,9 +250,12 @@ export function companionImportReasonKey(code?: string): string {SOURCE_AUTOMATION_INVALID: 'automationInvalid', AUTOMATION_TRIGGER_NEEDS_ADAPTER: 'automationInvalid',AUTOMATION_DATA_READ_FAILED: 'readFailed', AUTOMATION_READ_NOT_VERIFIED: 'readFailed',NATIVE_AUTH_REFRESH_REQUIRED: 'authRefresh', AUTOMATION_DEPENDENCY_NOT_SELECTED: 'missingSelection',+ SOURCE_COMMAND_UNAVAILABLE: 'sourceCommand',// 导入的 Telegram / Discord 机器人没能直接变成伙伴的消息平台连接(凭证仍保留给自动化投递)。IMPORT_IM_BOT_OWNER_MISSING: 'imBotOwnerMissing', IMPORT_IM_BOT_GATEWAY_RUNNING: 'imBotGatewayRunning',IMPORT_IM_BOT_IN_USE: 'imBotInUse', IMPORT_IM_BOT_CONNECT_FAILED: 'imBotConnectFailed',+ // 原 Agent 里的机器人没能确认停下,没有接给伙伴。+ IMPORT_IM_BOT_SOURCE_STOP_UNCONFIRMED: 'imBotSourceStopUnconfirmed',};return code && keys[code] || 'itemFailed';}