Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(companion-cloud): carry capability setup and reply artifacts when a companion changes computer
nana38d8b9a44a09
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/capabilities.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/capabilities.test.tsnew file mode 100644index 0000000000..b4aaa629a0--- /dev/null+++ b/apps/desktop/src/main/companion-cloud/__tests__/capabilities.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';+import { companionCapabilitiesPatch, parseCompanionCapabilities, portableCompanionCapabilities } from '../capabilities.js';++const route = (model: string, extra: Record<string, unknown> = {}) =>+ ({ harness: 'claude' as const, model, providerId: 'p1', effort: 'high', fastMode: false, ...extra });++describe('portable companion capabilities', () => {+ it('carries references and switches, never the permission level, credentials or the invitation state', () => {+ const value = portableCompanionCapabilities({+ permissions: 'trusted', invitation: { id: 'x' }, userContextSource: 'private', apiKey: 'sk-1',+ skills: ['a', 'a', 'b'], skillMode: 'allowlist', skillsExcluded: ['old'],+ toolsets: ['plugin-x'], toolsetMode: 'inherit', mcpServers: ['mcp-1'], mcpMode: 'allowlist',+ memory: false, inputHandoff: true, allowSchedulerFollow: true, gender: 'female',+ }, null);+ expect(value).toEqual({ skills: ['a', 'b'], skillMode: 'allowlist', skillsExcluded: ['old'], toolsets: ['plugin-x'],+ toolsetMode: 'inherit', mcpServers: ['mcp-1'], mcpMode: 'allowlist', memory: false, inputHandoff: true, allowSchedulerFollow: true, gender: 'female' });+ });++ it('carries only the model chain the owner chose, without routes that run on another computer', () => {+ const chosen = [route('m1'), route('m2', { agentDeviceId: 'phone-1' })];+ expect(portableCompanionCapabilities({}, chosen).modelChain).toEqual([route('m1')]);+ // Following the default is not a choice to carry: the new computer follows its own default.+ expect(portableCompanionCapabilities({}, null)).toEqual({});+ expect(portableCompanionCapabilities({ taskModelOverride: route('t1') }, null).taskModel).toEqual(route('t1'));+ expect(portableCompanionCapabilities({ taskModelOverride: route('t1', { agentDeviceId: 'x' }) }, null).taskModel).toBeUndefined();+ expect(portableCompanionCapabilities({ taskModelOverride: 'garbage' }, null).taskModel).toBeUndefined();+ });++ it('reads a cloud value defensively', () => {+ expect(parseCompanionCapabilities(null)).toBeNull();+ expect(parseCompanionCapabilities([])).toBeNull();+ expect(parseCompanionCapabilities({ skills: ['a', 3, ''], skillMode: 'bogus', memory: 'yes', permissions: 'trusted',+ modelChain: [route('m1'), { nope: true }, route('m2', { agentDeviceId: 'x' })], taskModel: { model: '' } }))+ .toEqual({ skills: ['a'], modelChain: [route('m1')] });+ });+});++describe('companionCapabilitiesPatch', () => {+ it('keeps references this computer lacks, and carries the usable model chain as the explicit choice', () => {+ const patch = companionCapabilitiesPatch({ skills: ['missing-here'], mcpServers: ['mcp-1'], mcpMode: 'allowlist', memory: false,+ modelChain: [route('m1'), route('m2')] }, { chain: [route('m2')], task: null });+ expect(patch).toMatchObject({ skills: ['missing-here'], mcpServers: ['mcp-1'], mcpMode: 'allowlist', memory: false,+ model: 'm2', modelChain: [route('m2')], modelChainOverride: [route('m2')] });+ expect(patch).not.toHaveProperty('permissions');+ });++ it('follows this computer\'s default model when none of the saved routes is usable, and leaves the model alone when none was chosen', () => {+ expect(companionCapabilitiesPatch({ modelChain: [route('m1')] }, { chain: [], task: null }))+ .toEqual({ modelOverride: null, modelChainOverride: null });+ expect(companionCapabilitiesPatch({ memory: true }, { chain: [], task: null })).toEqual({ memory: true });+ expect(companionCapabilitiesPatch({ taskModel: route('t1') }, { chain: [], task: null })).toEqual({ taskModelOverride: null });+ });+});diff --git a/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.tsindex 45248330eb..1e390768ff 100644--- a/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts+++ b/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts@@ -36,7 +36,7 @@ describe('materializeCompanion', () => {expect(local.host.writeSystemPrompt).toHaveBeenCalledWith('bot_mia', 'custom', expect.anything());expect(local.memories.get('user_tea.md')).toContain('likes tea');expect(local.skills.get('brew')).toContain('steps');- expect(result).toEqual({ created: true, inserted: 0, rebuild: 'skipped' });+ expect(result).toEqual({ created: true, inserted: 0, rebuild: 'skipped', notices: ['permissions'] });expect(state.bot('bot_mia')?.demoted).toBeUndefined();expect(local.host.rebuildContext).not.toHaveBeenCalled();});@@ -378,5 +378,72 @@ describe('materializeCompanion', () => {await expect(materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM })).rejects.toThrow('RESTORE_INCOMPLETE');expect(state.bot('bot_mia')?.demoted).toBe(true);});++ describe('capability setup', () => {+ const capabilitiesPref = (value: unknown) => ({ key: 'companion.capabilities.v1', value });+ const setup = (overrides: Parameters<typeof fakeLocal>[0] = {}) => {+ const local = fakeLocal({ applyCapabilities: vi.fn(async () => []), ...overrides });+ return { local, state: memoryState().state };+ };++ it('applies the cloud setup to a new copy, which gets the default permission level and says so', async () => {+ const { api } = cloud([{ ...profilePref, value: { ...profilePref.value, templateId: 'cindy' } },+ capabilitiesPref({ skills: ['a'], skillMode: 'allowlist', mcpServers: ['gone-here'], mcpMode: 'allowlist', memory: false, permissions: 'trusted' })]);+ const { local, state } = setup();+ const result = await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });+ expect(local.host.createProfile).toHaveBeenCalledWith(expect.objectContaining({ templateId: 'cindy' }), expect.anything());+ // Whatever the cloud holds is handed over as read; the permission level is not part of it.+ expect(local.host.applyCapabilities).toHaveBeenCalledWith('bot_mia',+ { skills: ['a'], skillMode: 'allowlist', mcpServers: ['gone-here'], mcpMode: 'allowlist', memory: false }, expect.anything());+ expect(result.notices).toEqual(['permissions']);+ expect(state.bot('bot_mia')?.arrivalNotices).toEqual(['permissions']);+ expect(state.bot('bot_mia')?.prefs['companion.capabilities.v1']).toMatchObject({ local: true });+ });++ it('also tells when a saved model could not be kept, but not about permissions of a copy that already existed', async () => {+ const { api } = cloud([profilePref, capabilitiesPref({ modelChain: [{ harness: 'codex', model: 'gpt-x', providerId: 'p', effort: '', fastMode: false }] })]);+ const { local, state } = setup({ applyCapabilities: vi.fn(async () => ['model' as const]) });+ local.setProfile({ status: 'active', displayName: 'Mia', description: '' });+ const result = await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });+ expect(result.notices).toEqual(['model']);+ expect(state.bot('bot_mia')?.arrivalNotices).toEqual(['model']);+ });++ it('keeps the copy as it is when the home predates the setup (no key), or the value is not an object', async () => {+ for (const prefs of [[profilePref], [profilePref, capabilitiesPref('nope')], [profilePref, capabilitiesPref(null)]]) {+ const { api } = cloud(prefs);+ const { local, state } = setup();+ local.setProfile({ status: 'active', displayName: 'Mia', description: '' });+ const result = await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });+ expect(local.host.applyCapabilities).not.toHaveBeenCalled();+ expect(result.notices).toEqual([]);+ expect(state.bot('bot_mia')?.arrivalNotices).toBeUndefined();+ }+ });++ it('stays demoted when the setup cannot be applied, and still remembers the permission reset on the retry', async () => {+ const { api } = cloud([profilePref, capabilitiesPref({ memory: true })]);+ let fail = true;+ const { local, state } = setup({ applyCapabilities: vi.fn(async () => { if (fail) throw new Error('DB_BUSY'); return []; }) });+ await expect(materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM })).rejects.toThrow('RESTORE_INCOMPLETE');+ expect(state.bot('bot_mia')?.demoted).toBe(true);+ // The copy exists now, so the retry no longer sees it as new.+ fail = false;+ const result = await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });+ expect(result.notices).toEqual(['permissions']);+ expect(state.bot('bot_mia')?.demoted).toBeUndefined();+ });+ });++ it('brings the files a companion reply refers to, written into the reply on this computer', async () => {+ const answer = { ...roomMessage('m2', 2, 'actor-1', '做好了 documents/report.docx', 2_000), content: [{ type: 'text', text: '做好了 documents/report.docx' },+ { type: 'media', mediaId: 'media-9', caption: 'report.docx' }] };+ const { api } = cloud([profilePref], [answer]);+ const local = fakeLocal();+ const download = vi.fn(async () => ({ name: 'report.docx', category: 'file', mimeType: 'application/octet-stream', size: 3, url: null, path: '/attachments/media-9/report.docx' }));+ await materializeCompanion({ api, state: memoryState().state, host: local.host, actor, roomId: async () => ROOM, download });+ expect(local.host.insertHistory).toHaveBeenCalledWith('session-1', expect.objectContaining({+ role: 'assistant', attachments: [expect.objectContaining({ path: '/attachments/media-9/report.docx' })] }), expect.anything());+ });});diff --git a/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.tsindex fdacf3c5f9..5ac9953f71 100644--- a/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts+++ b/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts@@ -83,7 +83,8 @@ describe('splitMirrorText', () => {});});-function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolean, uploadMedia?: Parameters<typeof createCompanionMirror>[0]['uploadMedia']) {+function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolean, uploadMedia?: Parameters<typeof createCompanionMirror>[0]['uploadMedia'],+ replyAttachments?: Parameters<typeof createCompanionMirror>[0]['replyAttachments']) {let imports = 0;const { api, calls } = fakeApi((route, method) => {if (route === '/conversations' && method === 'POST') return { id: ROOM };@@ -104,6 +105,7 @@ function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolea.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id)).slice(0, limit),latestRows: async (_sessionId, limit) => [...rows].reverse().slice(0, limit),...(uploadMedia ? { uploadMedia } : {}),+ ...(replyAttachments ? { replyAttachments } : {}),});const imported = () => calls.filter(call => call.route.endsWith('/import')).map(call => (call.data as { messages: Array<{ sourceId: string; authorId: string; content: Array<{ type?: string; text: string; mediaId?: string }> }> }).messages);@@ -183,6 +185,56 @@ describe('companion conversation mirror', () => {expect(t.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'look' }, { type: 'media', mediaId: 'm-2', caption: 'a.pdf' }]);});+ describe('files a reply refers to', () => {+ const report = { id: '', name: 'report.docx', category: 'file' as const, mimeType: 'application/octet-stream', size: 10, url: null, path: '/work/documents/report.docx' };+ const upload = () => vi.fn(async (_room: string, _source: string, files: Array<{ name: string }>) =>+ [{ type: 'media', mediaId: 'm-r', caption: files[0]!.name }]);++ it('sends them with the reply: the text stays, the files ride as media blocks', async () => {+ const answer = reply('做好了 documents/report.docx');+ const find = vi.fn(async (_bot: string, _session: string, found: CompanionMirrorRow, text: string) => {+ expect(text).toBe('做好了 documents/report.docx');+ return [{ ...report, id: `${found.id}:reply:0` }];+ });+ const send = upload();+ const t = setup([user('做个报告'), answer], undefined, send, find);+ await t.mirror.syncBot('bot', 'actor', 'Mia');+ expect(find).toHaveBeenCalledTimes(1);+ expect(send).toHaveBeenCalledWith(ROOM, expect.stringContaining(answer.id), [expect.objectContaining({ path: '/work/documents/report.docx' })], 'actor');+ expect(t.imported()[0]![1]!.content).toEqual([{ type: 'text', text: '做好了 documents/report.docx' }, { type: 'media', mediaId: 'm-r', caption: 'report.docx' }]);+ });++ it('does not look at replies that are not visible, or when files cannot be uploaded', async () => {+ const find = vi.fn(async () => [report]);+ const hidden = reply('internal documents/report.docx', { agentMeta: JSON.stringify({ botPrivateReply: true }) });+ const t = setup([user('hi'), hidden], undefined, upload(), find);+ await t.mirror.syncBot('bot', 'actor', 'Mia');+ expect(find).not.toHaveBeenCalled();+ const noUpload = setup([reply('documents/report.docx')], undefined, undefined, find);+ await noUpload.mirror.syncBot('bot', 'actor', 'Mia');+ expect(find).not.toHaveBeenCalled();+ expect(noUpload.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'documents/report.docx' }]);+ });++ it('keeps the reply text only for a file that never uploads, and retries one that may still go up', async () => {+ const answer = reply('see documents/report.docx');+ const find = async () => [{ ...report, id: `${answer.id}:reply:0` }];+ const gone = setup([answer], undefined, vi.fn(async () => { throw new Error('ATTACHMENT_UNAVAILABLE'); }), find);+ await gone.mirror.syncBot('bot', 'actor', 'Mia');+ // No placeholder is invented for a reply: the text is exactly what the companion said.+ expect(gone.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'see documents/report.docx' }]);+ const offline = setup([answer], undefined, vi.fn(async () => { throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 }); }), find);+ await expect(offline.mirror.syncBot('bot', 'actor', 'Mia')).rejects.toThrow('MEDIA_UPLOAD_FAILED');+ expect(offline.imported()).toEqual([]);+ });++ it('does not stop mirroring when the files cannot be listed', async () => {+ const t = setup([reply('hello')], undefined, upload(), vi.fn(async () => { throw new Error('EACCES'); }));+ await t.mirror.syncBot('bot', 'actor', 'Mia');+ expect(t.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'hello' }]);+ });+ });+it('uploads the older history on later passes, oldest first, without re-sending', async () => {const rows = Array.from({ length: 260 }, (_, i) => (i % 2 ? reply(`r${i}`) : user(`u${i}`)));const t = setup(rows);diff --git a/apps/desktop/src/main/companion-cloud/__tests__/replyArtifacts.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/replyArtifacts.test.tsnew file mode 100644index 0000000000..21d87243c5--- /dev/null+++ b/apps/desktop/src/main/companion-cloud/__tests__/replyArtifacts.test.ts@@ -0,0 +1,88 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { collectReplyReferences, replyArtifactAttachments, replyTextWithFiles, REPLY_ARTIFACTS_MAX } from '../replyArtifacts.js';++const HASH = 'a'.repeat(64);++describe('collectReplyReferences', () => {+ it('finds media addresses and the files a reply names, in prose, inline code and links', () => {+ const text = [+ ``,+ '做好了 documents/报告.docx,另见 `notes/todo.txt`。',+ '[表格](documents/q3.xlsx) 和 [导出](xdt-file:///work/out/data.csv)',+ '放在了summary.pdf里,见documents/a.pdf。',+ '```\ndocuments/example-only.docx\n```',+ '网页 https://example.com/a/b.pdf 与 [站](https://x.dev/y.zip) 不算',+ ].join('\n');+ const found = collectReplyReferences(text);+ expect(found.blobs).toEqual([`cindy-media://blobs/${HASH}.png`]);+ expect(found.paths).toEqual(expect.arrayContaining(['documents/报告.docx', 'notes/todo.txt', 'documents/q3.xlsx', '/work/out/data.csv', 'summary.pdf', 'documents/a.pdf']));+ expect(found.paths).not.toContain('documents/example-only.docx');+ expect(found.paths.some(item => item.includes('example.com') || item.includes('x.dev'))).toBe(false);+ });++ it('does not take a bare word with a dot, or a name without a deliverable extension, as a file', () => {+ expect(collectReplyReferences('版本是 v1.2,见 README.md 和 config.json').paths).toEqual([]);+ });+});++describe('replyArtifactAttachments', () => {+ let root: string;+ let outside: string;+ const deps = (extra: Partial<Parameters<typeof replyArtifactAttachments>[3]> = {}) => ({+ roots: async () => [root], blob: async () => null, maxBytes: 1000, ...extra,+ });+ beforeEach(async () => {+ root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'reply-')));+ outside = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'outside-')));+ await fs.mkdir(path.join(root, 'documents'));+ await fs.writeFile(path.join(root, 'documents', 'report.docx'), 'docx-bytes');+ });+ afterEach(async () => {+ await fs.rm(root, { recursive: true, force: true });+ await fs.rm(outside, { recursive: true, force: true });+ });++ it('lists the existing files inside the work folder that the reply names, by relative or absolute path', async () => {+ const files = await replyArtifactAttachments({ id: 'm1' }, `做好了 documents/report.docx,也见 ${path.join(root, 'documents', 'report.docx')} 和 documents/missing.docx`, 's1', deps());+ expect(files).toHaveLength(1);+ expect(files[0]).toMatchObject({ name: 'report.docx', category: 'file', path: path.join(root, 'documents', 'report.docx'), url: null, size: 10 });+ });++ it('never reads outside the work folder, through a link out of it, a hidden file, or an oversized one', async () => {+ await fs.writeFile(path.join(outside, 'secret.docx'), 'secret');+ await fs.symlink(path.join(outside, 'secret.docx'), path.join(root, 'documents', 'link.docx'));+ await fs.writeFile(path.join(root, '.env.docx'), 'hidden');+ await fs.mkdir(path.join(root, '.git'));+ await fs.writeFile(path.join(root, '.git', 'config.txt'), 'hidden');+ await fs.writeFile(path.join(root, 'documents', 'big.docx'), 'x'.repeat(2000));+ const text = `${path.join(outside, 'secret.docx')} documents/link.docx .env.docx .git/config.txt documents/big.docx ../${path.basename(outside)}/secret.docx`;+ expect(await replyArtifactAttachments({ id: 'm1' }, text, 's1', deps())).toEqual([]);+ expect(await replyArtifactAttachments({ id: 'm1' }, 'documents/report.docx', 's1', deps({ roots: async () => [] }))).toEqual([]);+ });++ it('adds stored media the task may read as image or file, skips missing or oversized ones, and stops at the limit', async () => {+ const urls = Array.from({ length: REPLY_ARTIFACTS_MAX + 3 }, (_, index) => `cindy-media://blobs/${String(index).padStart(64, '0')}.png`);+ const blob = async (url: string) => (url === urls[0] ? null : url === urls[1] ? { mimeType: 'image/png', size: 5000 }+ : url === urls[2] ? { mimeType: 'video/mp4', size: 10 } : { mimeType: 'image/png', size: 10 });+ const files = await replyArtifactAttachments({ id: 'm1' }, urls.join(' '), 's1', deps({ blob }));+ expect(files).toHaveLength(REPLY_ARTIFACTS_MAX);+ expect(files[0]).toMatchObject({ url: urls[2], category: 'file', mimeType: 'video/mp4' });+ expect(files[1]).toMatchObject({ url: urls[3], category: 'image' });+ expect(new Set(files.map(file => file.id)).size).toBe(files.length);+ });+});++describe('replyTextWithFiles', () => {+ it('shows media the text already names as before, and links everything else below the reply', () => {+ const named = `cindy-media://blobs/${HASH}.png`;+ expect(replyTextWithFiles(`图 `, [{ name: 'x.png', url: named, path: null }])).toBe(`图 `);+ expect(replyTextWithFiles('看这个', [+ { name: 'chart.png', url: `cindy-media://blobs/${'b'.repeat(64)}.png`, path: null },+ { name: 'a (1).docx', path: '/att/a (1).docx', url: null },+ { name: 'gone.pdf', path: null, url: null },+ ])).toBe(`看这个\n\n}.png)\n\n[a (1).docx](xdt-file://local/?path=%2Fatt%2Fa%20%281%29.docx)\n\n[附件: gone.pdf]`);+ });+});diff --git a/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.tsindex c1813c1657..058d6c7fa4 100644--- a/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts+++ b/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts@@ -154,6 +154,23 @@ describe('companion profile uploader', () => {expect(log.warn).toHaveBeenCalledWith('Companion upload will retry', { actorId: 'actor', code: 'UNAVAILABLE' });});+ it('uploads the capability setup like any value: once, on change, with a hand-over waiting for it too', async () => {+ const t = setup();+ const caps = (memory: boolean): CompanionPreferenceValue => ({ key: 'companion.capabilities.v1', value: { skills: ['a'], memory } });+ t.setValues([profile('soul'), caps(true)]);+ await t.uploader.syncBot('bot', 'actor', undefined, { requireAll: true });+ await t.uploader.syncBot('bot', 'actor');+ expect(t.writes().filter(w => w.key === 'companion.capabilities.v1').map(w => w.value)).toEqual([{ skills: ['a'], memory: true }]);+ t.setValues([profile('soul'), caps(false)]);+ await t.uploader.syncBot('bot', 'actor');+ expect(t.writes().filter(w => w.key === 'companion.capabilities.v1')).toHaveLength(2);+ // A record that could not be read keeps the cloud value; a hand-over refuses to go without it.+ t.setValues([profile('soul'), { key: 'companion.capabilities.v1', value: null, unread: true }]);+ await t.uploader.syncBot('bot', 'actor');+ expect(t.writes().filter(w => w.key === 'companion.capabilities.v1')).toHaveLength(2);+ await expect(t.uploader.syncBot('bot', 'actor', undefined, { requireAll: true })).rejects.toThrow('COMPANION_READ_INCOMPLETE');+ });+it('serialises JSON with sorted keys', () => {expect(canonicalJson({ b: 1, a: [{ d: null, c: 'x' }], e: undefined })).toBe('{"a":[{"c":"x","d":null}],"b":1}');});diff --git a/apps/desktop/src/main/companion-cloud/capabilities.ts b/apps/desktop/src/main/companion-cloud/capabilities.tsnew file mode 100644index 0000000000..7dc104ec19--- /dev/null+++ b/apps/desktop/src/main/companion-cloud/capabilities.ts@@ -0,0 +1,111 @@+/**+ * What of a companion's capability setup moves with it to another computer+ * (`companion.capabilities.v1`; cloud-companions.md §2, 2026-10-22 ruling). Only choices that mean+ * the same on any computer: references to skills, MCP servers and toolsets (ids, never their+ * configuration or credentials), the memory switch, hand-over and follow-up switches, and the+ * model *preference*. The permission level never travels; the new computer uses its default.+ */+import { BOT_MODEL_CHAIN_MAX, normalizeBotModelChain, readBotTaskModelOverride, type BotModelRoute } from '../../shared/botModelChain.js';++const MAX_REFS = 100;+const MAX_REF_LENGTH = 200;++type SelectionMode = 'inherit' | 'allowlist';++export interface CompanionCapabilitiesValue {+ skills?: string[];+ skillMode?: SelectionMode;+ skillsExcluded?: string[];+ toolsets?: string[];+ toolsetMode?: SelectionMode;+ mcpServers?: string[];+ mcpMode?: SelectionMode;+ memory?: boolean;+ inputHandoff?: boolean;+ allowSchedulerFollow?: boolean;+ gender?: string;+ /** The routes the owner chose for this companion; absent when it follows the default model. */+ modelChain?: BotModelRoute[];+ taskModel?: BotModelRoute;+}++const refs = (value: unknown): string[] | undefined => Array.isArray(value)+ ? [...new Set(value.filter((id): id is string => typeof id === 'string' && !!id.trim() && id.length <= MAX_REF_LENGTH))].slice(0, MAX_REFS)+ : undefined;+const mode = (value: unknown): SelectionMode | undefined => (value === 'inherit' || value === 'allowlist' ? value : undefined);+/** A route that names another computer to run on has no meaning on the new home. */+const portableRoute = (route: BotModelRoute) => !route.agentDeviceId;++/**+ * The portable part of a capabilities record. `explicitChain` is the companion's own chosen model+ * chain (null: it follows the default, which the new computer then also follows).+ */+export function portableCompanionCapabilities(config: Record<string, unknown>, explicitChain: BotModelRoute[] | null): CompanionCapabilitiesValue {+ const value: CompanionCapabilitiesValue = {};+ for (const [field, selection] of [['skills', 'skillMode'], ['toolsets', 'toolsetMode'], ['mcpServers', 'mcpMode']] as const) {+ const list = refs(config[field]);+ if (list) value[field] = list;+ const selected = mode(config[selection]);+ if (selected) value[selection] = selected;+ }+ const excluded = refs(config.skillsExcluded);+ if (excluded) value.skillsExcluded = excluded;+ for (const field of ['memory', 'inputHandoff', 'allowSchedulerFollow'] as const) {+ if (typeof config[field] === 'boolean') value[field] = config[field];+ }+ if (typeof config.gender === 'string' && config.gender.length <= 16) value.gender = config.gender;+ const chain = (explicitChain ?? []).filter(portableRoute);+ if (chain.length) value.modelChain = chain;+ try {+ const task = readBotTaskModelOverride(config.taskModelOverride);+ if (task && portableRoute(task)) value.taskModel = task;+ } catch { /* an unreadable task model is not carried */ }+ return value;+}++/** A value from the cloud, read defensively (it is untrusted); null when it is not an object. */+export function parseCompanionCapabilities(raw: unknown): CompanionCapabilitiesValue | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const input = raw as Record<string, unknown>;+ const value: CompanionCapabilitiesValue = {};+ for (const [field, selection] of [['skills', 'skillMode'], ['toolsets', 'toolsetMode'], ['mcpServers', 'mcpMode']] as const) {+ const list = refs(input[field]);+ if (list) value[field] = list;+ const selected = mode(input[selection]);+ if (selected) value[selection] = selected;+ }+ const excluded = refs(input.skillsExcluded);+ if (excluded) value.skillsExcluded = excluded;+ for (const field of ['memory', 'inputHandoff', 'allowSchedulerFollow'] as const) {+ if (typeof input[field] === 'boolean') value[field] = input[field];+ }+ if (typeof input.gender === 'string' && input.gender.length <= 16) value.gender = input.gender;+ const chain = normalizeBotModelChain(input.modelChain).filter(portableRoute).slice(0, BOT_MODEL_CHAIN_MAX);+ if (chain.length) value.modelChain = chain;+ try {+ const task = readBotTaskModelOverride(input.taskModel);+ if (task && portableRoute(task)) value.taskModel = task;+ } catch { /* ignored: follows the primary model */ }+ return value;+}++/** What the new home could not keep of the old setup; shown once as a line after the move. */+export type CompanionArrivalNotice = 'permissions' | 'model';++/** The settings patch for `updateBotProfile` from a cloud value and the routes usable here. */+export function companionCapabilitiesPatch(value: CompanionCapabilitiesValue, models: {+ chain: BotModelRoute[]; task: BotModelRoute | null;+}): Record<string, unknown> {+ const patch: Record<string, unknown> = {};+ for (const field of ['skills', 'skillMode', 'skillsExcluded', 'toolsets', 'toolsetMode', 'mcpServers', 'mcpMode', 'memory', 'inputHandoff', 'allowSchedulerFollow'] as const) {+ if (value[field] !== undefined) patch[field] = value[field];+ }+ if (value.modelChain) {+ const [primary] = models.chain;+ if (primary) Object.assign(patch, primary, { modelChain: models.chain, modelChainOverride: models.chain });+ // None of the saved routes exists here: follow this computer's default.+ else Object.assign(patch, { modelOverride: null, modelChainOverride: null });+ }+ if (value.taskModel) patch.taskModelOverride = models.task;+ return patch;+}diff --git a/apps/desktop/src/main/companion-cloud/host.ts b/apps/desktop/src/main/companion-cloud/host.tsindex 02e0d71560..c3a79a9880 100644--- a/apps/desktop/src/main/companion-cloud/host.ts+++ b/apps/desktop/src/main/companion-cloud/host.ts@@ -14,9 +14,15 @@ import { createBotProfile, getBotMemoryService, setBotProfileAvatar, updateBotPrimport { decodeBotAvatarImage } from '../localDb/ipc/botAvatarSelection.js';import { createMessage } from '../localDb/ipc/messages.js';import { commitChatImageUrls } from '../cindy-media/chatAttachments.js';-import { botProfileVersions, botProfiles, botSessionLinks, messages } from '../localDb/schema.js';+import { botProfileVersions, botProfiles, botSessionLinks, messages, sessions } from '../localDb/schema.js';+import { parseBlobUrl, resolveSafe } from '../cindy-media/blobStore.js';+import { sessionCanRead } from '../cindy-media/ledger.js';+import { taskImageRoots } from '../cindy-media/taskImageDelivery.js';+import type { BotModelRoute } from '../../shared/botModelChain.js';import { inferBotTemplatePresetId } from '../../shared/botTemplatePreset.js';import { resolveBotCanonicalSession } from '../maker-ipc/botCanonicalSessionRegistry.js';+import { readExplicitBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';+import { resolveAvailableTaskModels } from '../maker-ipc/appDefaultModelControl.js';import { botProfileDir, botProfileMemoryDir, readBotProfileFolder, writeBotProfileFolder } from '../maker-ipc/botProfileFolder.js';import { onBotRemoteResourceChanged } from '../maker-ipc/botRemoteResourceInvalidation.js';import { deleteBotSkillForBot, listBotSkillSourcesForBot, readBotSkillSourceForBot, saveBotSkillSourceForBot } from '../maker-ipc/botSkillService.js';@@ -27,11 +33,14 @@ import type { TeammateTodo } from '@cindy/maker-shared/teammate-todo';import { portableTodo, travellingTodos } from './travel.js';import type { CompanionMaterializeHost } from './materialize.js';import { companionHomes } from './homes.js';-import type { CompanionMirrorCursor, CompanionMirrorRow } from './mirror.js';+import { companionCapabilitiesPatch, portableCompanionCapabilities, type CompanionArrivalNotice } from './capabilities.js';+import { MIRROR_ATTACHMENT_MAX_BYTES, type CompanionMirrorCursor, type CompanionMirrorRow } from './mirror.js';+import { replyArtifactAttachments, replyTextWithFiles } from './replyArtifacts.js';import type { CompanionCloudHost } from './runtime.js';import { createCompanionCloudState } from './state.js';import type { CompanionLog } from './types.js';import {+ COMPANION_CAPABILITIES_KEY,COMPANION_MEMORY_PREFIX,COMPANION_PROFILE_KEY,COMPANION_ROUTINE_PREFIX,@@ -69,6 +78,14 @@ export async function readCompanionValues(botId: string, selfDeviceId: string |name: row.displayName, description: row.description, soul: folder.identitySource,systemPrompt: folder.systemPromptOverride, user: folder.userContextSource, ...(templateId ? { templateId } : {}),} }];+ // The setup that means the same on any computer. A record that cannot be read keeps its cloud+ // value (the uploader never tombstones what was merely unreadable).+ try {+ const config = JSON.parse(row.capabilities ?? '{}') as unknown;+ if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('CAPABILITIES_UNREADABLE');+ values.push({ key: COMPANION_CAPABILITIES_KEY, value: portableCompanionCapabilities(+ config as Record<string, unknown>, readExplicitBotModelChain(config as Record<string, unknown>)) });+ } catch { values.push({ key: COMPANION_CAPABILITIES_KEY, value: null, unread: true }); }const memoryDir = botProfileMemoryDir(userDataDir, botId);// Only a missing folder means "no memories"; any other read error aborts this cycle so the// uploader never tombstones memories it merely failed to read.@@ -173,26 +190,43 @@ function createMaterializer(input: {return row ?? null;},// Normal creation path: no invitation, no generated persona, the new home's default model.- createProfile: async ({ id, name, description, identitySource, userContextSource, avatar }, fence) => {+ createProfile: async ({ id, name, description, identitySource, userContextSource, avatar, templateId }, fence) => {const restored = await cloudAvatar(avatar, fence.signal);fence.assertCurrent();await createBotProfile({ id, name: name.slice(0, 200), description, identitySource, userContextSource,- ...('portable' in restored ? { avatar: restored.portable } : { avatarImageBase64: restored.imageBase64 }) });+ ...('portable' in restored ? { avatar: restored.portable } : { avatarImageBase64: restored.imageBase64 }) },+ { templateId });},- updateProfile: async ({ id, name, description, identitySource, userContextSource, avatar }, fence) => {+ updateProfile: async ({ id, name, description, identitySource, userContextSource, avatar, templateId }, fence) => {const restored = await cloudAvatar(avatar, fence.signal);fence.assertCurrent();await updateBotProfile({ id, name: name.slice(0, 200), enabled: true,...(description !== undefined ? { description } : {}),...(identitySource !== undefined ? { identitySource } : {}),...(userContextSource !== undefined ? { userContextSource } : {}),- ...('portable' in restored ? { avatar: restored.portable } : {}) });+ ...('portable' in restored ? { avatar: restored.portable } : {}) }, undefined, undefined, { templateId });if ('imageBase64' in restored) {const image = decodeBotAvatarImage(restored.imageBase64);fence.assertCurrent();if (image) await setBotProfileAvatar(id, image);}},+ applyCapabilities: async (botId, value, fence) => {+ // Only the same provider + model that this computer can use is kept (no credential travels);+ // otherwise the companion follows this computer's default model.+ const usable = async (routes: BotModelRoute[]) => (await resolveAvailableTaskModels(routes))+ .filter((route): route is BotModelRoute => route !== null);+ const chain = value.modelChain ? await usable(value.modelChain) : [];+ const task = value.taskModel ? (await usable([value.taskModel]))[0] ?? null : null;+ fence.assertCurrent();+ const patch = companionCapabilitiesPatch(value, { chain, task });+ if (Object.keys(patch).length || value.gender) {+ await updateBotProfile({ id: botId, capabilities: patch, ...(value.gender ? { gender: value.gender } : {}) });+ }+ const notices: CompanionArrivalNotice[] = [];+ if ((value.modelChain && chain.length < value.modelChain.length) || (value.taskModel && !task)) notices.push('model');+ return notices;+ },writeSystemPrompt: async (botId, text, fence) => {const root = ownerScopedUserDataPath();fence.assertCurrent();@@ -237,7 +271,6 @@ function createMaterializer(input: {const files = row.attachments ?? [];const images = files.flatMap(file => file.url ? [{ url: file.url, mimeType: file.mimeType, originalName: file.name, size: file.size }] : []);const others = files.flatMap(file => !file.url && file.path ? [{ name: file.name, path: file.path }] : []);- const names = row.role === 'assistant' ? files.map(file => `[附件: ${file.name}]`) : [];// The room's image copies were cached only: they belong to this task before the message is// written. A failed commit fails the import while the message is still absent, so the retry// downloads and commits again instead of treating it as imported with recyclable images.@@ -248,12 +281,30 @@ function createMaterializer(input: {}await createMessage(sessionId, { clientId: row.clientId, role: row.role, createdAt: row.createdAt,content: row.role === 'user' ? { text: row.text, images, files: others }- : [{ type: 'text', text: [row.text, ...names].filter(Boolean).join('\n') }] });+ : [{ type: 'text', text: replyTextWithFiles(row.text, files) }] });},rebuildContext: sessionId => input.rebuildContext(sessionId),};}+/** The folders a task's own files live in (its work folder); none for a deleted or remote task. */+async function readTaskFileRoots(sessionId: string): Promise<string[]> {+ const [session] = await getDbClient().drizzle+ .select({ id: sessions.id, workingDir: sessions.workingDir, sdkSessionId: sessions.sdkSessionId, agentKind: sessions.agentKind,+ remoteHostId: sessions.remoteHostId, status: sessions.status, clearedAt: sessions.clearedAt })+ .from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ return session ? taskImageRoots(session) : [];+}++/** A media blob this task may read and this computer still has (the reply only names its address). */+async function readReplyBlob(url: string, sessionId: string): Promise<{ mimeType: string; size: number } | null> {+ const blob = parseBlobUrl(url);+ if (!blob || !await sessionCanRead(blob.hash, sessionId, getDbClient().drizzle)) return null;+ const { absPath, mimeType } = resolveSafe(url);+ const stat = await fs.stat(absPath);+ return stat.isFile() ? { mimeType, size: stat.size } : null;+}+const mirrorColumns = {id: messages.id, clientId: messages.clientId, role: messages.role, content: messages.content,agentMeta: messages.agentMeta, createdAt: messages.createdAt,@@ -344,6 +395,12 @@ export function createCompanionCloudHost(input: {},rowsAfter: readMirrorRowsAfter,latestRows: readLatestMirrorRows,+ replyAttachments: (_botId, sessionId, row, text) => replyArtifactAttachments(row, text, sessionId, {+ roots: readTaskFileRoots,+ blob: readReplyBlob,+ maxBytes: MIRROR_ATTACHMENT_MAX_BYTES,+ ...(input.log ? { log: input.log } : {}),+ }),deliverToCanonical: input.deliverToCanonical,onLocalChange: onBotRemoteResourceChanged,materializer: createMaterializer(input),diff --git a/apps/desktop/src/main/companion-cloud/materialize.ts b/apps/desktop/src/main/companion-cloud/materialize.tsindex 17af8c0cf5..464ae84b47 100644--- a/apps/desktop/src/main/companion-cloud/materialize.ts+++ b/apps/desktop/src/main/companion-cloud/materialize.ts@@ -8,12 +8,13 @@*/import type { CompanionMirrorCursor, CompanionMirrorRow } from './mirror.js';import { COMPANION_HISTORY_CLIENT_PREFIX } from './mirror.js';+import { parseCompanionCapabilities, type CompanionArrivalNotice, type CompanionCapabilitiesValue } from './capabilities.js';import { directRoomSourceId } from './directRoom.js';import { readAllRoomMessages } from './room.js';import type { CompanionCloudState } from './state.js';import { errorCode, isTransientAttachmentFailure, type CompanionApi, type CompanionLog } from './types.js';import {- COMPANION_MEMORY_PREFIX, COMPANION_PROFILE_KEY, COMPANION_ROUTINE_PREFIX, COMPANION_SKILL_PREFIX, COMPANION_TODO_PREFIX,+ COMPANION_CAPABILITIES_KEY, COMPANION_MEMORY_PREFIX, COMPANION_PROFILE_KEY, COMPANION_ROUTINE_PREFIX, COMPANION_SKILL_PREFIX, COMPANION_TODO_PREFIX,COMPANION_WORKBENCH_KEY, TOMBSTONE_HASH, isCompanionProfileSnapshot, valueHash,} from './uploader.js';@@ -31,6 +32,8 @@ export interface CompanionMaterializeHost {/** The cloud avatar must be restored (an image that cannot be downloaded fails the call). */createProfile: (input: {id: string; name: string; description: string; identitySource: string; userContextSource: string; avatar: string | null;+ /** The preset the companion was made from (the cloud profile's `templateId`). */+ templateId?: string;}, fence: CompanionWriteFence) => Promise<void>;/*** Also makes the profile active again. Undefined fields stay unchanged; a cloud avatar replaces@@ -38,7 +41,14 @@ export interface CompanionMaterializeHost {*/updateProfile: (input: {id: string; name: string; description?: string; identitySource?: string; userContextSource?: string; avatar: string | null;+ templateId?: string;}, fence: CompanionWriteFence) => Promise<void>;+ /**+ * Apply the companion's portable capability setup (capabilities.ts): references stay even when+ * this computer lacks them, a model chain that is not usable here falls back to the default.+ * Returns what could not be kept, for the one-line notice.+ */+ applyCapabilities?: (botId: string, value: CompanionCapabilitiesValue, fence: CompanionWriteFence) => Promise<CompanionArrivalNotice[]>;writeSystemPrompt: (botId: string, text: string, fence: CompanionWriteFence) => Promise<void>;/** Copy the companion's Home (identity, prompt, user file, memories, skills) aside; returns where. */backupHome?: (botId: string, fence: CompanionWriteFence) => Promise<string | null>;@@ -90,6 +100,8 @@ export interface CompanionMaterializeResult {rebuild: 'rebuilt' | 'skipped';/** Where an existing, never-synced local copy was saved before being overwritten. */backup?: string | null;+ /** What of the old setup this computer could not keep (the permission level never travels). */+ notices: CompanionArrivalNotice[];}const text = (value: unknown) => typeof value === 'string' ? value : undefined;@@ -145,12 +157,17 @@ export async function materializeCompanion(input: {state.update(botId, actor.id, entry => { entry.backedUp = true; });}const name = text(profile?.name)?.trim() || actor.name || local?.displayName || '伙伴';+ const templateId = text(record(profile)?.templateId);if (!local) {await step(() => host.createProfile({ id: botId, name, description: text(profile?.description) ?? '',- identitySource: text(profile?.soul) ?? '', userContextSource: text(profile?.user) ?? '', avatar: actor.avatar }, fence));+ identitySource: text(profile?.soul) ?? '', userContextSource: text(profile?.user) ?? '', avatar: actor.avatar,+ ...(templateId ? { templateId } : {}) }, fence));+ // From here the copy exists, so a retry no longer sees it as new: remember the permission reset now.+ state.update(botId, actor.id, entry => { entry.arrivalNotices = [...new Set([...(entry.arrivalNotices ?? []), 'permissions' as const])]; });} else {await step(() => host.updateProfile({ id: botId, name, description: text(profile?.description),- identitySource: text(profile?.soul), userContextSource: text(profile?.user), avatar: actor.avatar }, fence));+ identitySource: text(profile?.soul), userContextSource: text(profile?.user), avatar: actor.avatar,+ ...(templateId ? { templateId } : {}) }, fence));}const systemPrompt = text(profile?.systemPrompt);if (systemPrompt !== undefined) await step(() => host.writeSystemPrompt(botId, systemPrompt, fence));@@ -203,6 +220,23 @@ export async function materializeCompanion(input: {}}+ // Capability setup (references, memory switch, model preference). A new copy gets this computer's+ // default permission level; an existing copy keeps its own. A cloud value from an older home is+ // simply absent: the copy keeps what it has.+ // (Notices a failed earlier try of this take-over already recorded stay until the owner clears them.)+ const notices: CompanionArrivalNotice[] = known?.actorId === actor.id ? [...(known.arrivalNotices ?? [])] : [];+ if (!local && !notices.includes('permissions')) notices.push('permissions');+ const capabilitiesRow = prefs.get(COMPANION_CAPABILITIES_KEY);+ const capabilities = capabilitiesRow ? parseCompanionCapabilities(capabilitiesRow.value) : null;+ if (capabilitiesRow && capabilities && host.applyCapabilities) {+ await apply('capabilities', async () => {+ for (const notice of await step(() => host.applyCapabilities!(botId, capabilities, fence))) {+ if (!notices.includes(notice)) notices.push(notice);+ }+ applied.set(COMPANION_CAPABILITIES_KEY, { hash: valueHash(capabilitiesRow.value), revision: capabilitiesRow.revision });+ });+ }+// Todos, routines and the workbench move with the companion: applied in one batch each (the// cloud wins; a routine tombstone removes it here). A todo is deleted by marking it (the mark// travels as a value); its tombstone only means it left the travelling window (closed long ago),@@ -235,7 +269,11 @@ export async function materializeCompanion(input: {if (failures > 0) {// Keep what was restored (so the retry does not back the copy up again) and stay demoted.- state.update(botId, actor.id, entry => { for (const [key, value] of applied) entry.prefs[key] = { ...value, local: true }; });+ state.update(botId, actor.id, entry => {+ for (const [key, value] of applied) entry.prefs[key] = { ...value, local: true };+ // The copy now exists: the retry no longer sees it as new, so remember what it could not keep.+ if (notices.length) entry.arrivalNotices = notices;+ });throw new Error('RESTORE_INCOMPLETE');}@@ -257,6 +295,7 @@ export async function materializeCompanion(input: {for (const [key, value] of applied) entry.prefs[key] = { ...value, local: true };if (!keepCursor) entry.mirror = { sessionId, ...cursor };if (needsRebuild) entry.pendingRebuild = true;+ if (notices.length) entry.arrivalNotices = notices; else delete entry.arrivalNotices;});// Rebuild while still demoted: a failure, or a turn still running (`busy`), leaves the copy// demoted and the automatic take-over retries until the rebuild completes.@@ -268,7 +307,7 @@ export async function materializeCompanion(input: {// The next take-over (after this copy hands the companion away again) backs it up anew.delete entry.backedUp;});- return { created: !local, inserted, rebuild, ...(backup !== undefined ? { backup } : {}) };+ return { created: !local, inserted, rebuild, notices, ...(backup !== undefined ? { backup } : {}) };}/** Insert the room's whole conversation that is not already local, in message-time order. */diff --git a/apps/desktop/src/main/companion-cloud/mirror.ts b/apps/desktop/src/main/companion-cloud/mirror.tsindex 664d52ee90..e4a33aaff9 100644--- a/apps/desktop/src/main/companion-cloud/mirror.ts+++ b/apps/desktop/src/main/companion-cloud/mirror.ts@@ -179,6 +179,11 @@ export function createCompanionMirror(deps: {latestRows: (sessionId: string, limit: number) => Promise<CompanionMirrorRow[]>;/** Uploads the owner's attachments so other devices can open them; absent keeps name placeholders. */uploadMedia?: CompanionMediaUpload;+ /**+ * The files a companion reply refers to (generated media, files in its work folder) that go to+ * the room with it; given the reply's visible text. Absent keeps replies text only.+ */+ replyAttachments?: (botId: string, sessionId: string, row: CompanionMirrorRow, text: string) => Promise<CompanionMirrorAttachment[]>;log?: CompanionLog;}) {async function ensureRoom(botId: string, actorId: string, name: string): Promise<string> {@@ -213,7 +218,13 @@ export function createCompanionMirror(deps: {// address form) keeps its name in the text, as before.const media: Array<{ type: string; mediaId?: string; caption?: string }> = [];const uploaded: string[] = [];- for (const file of deps.uploadMedia ? mirrorAttachments(row) : []) {+ // A reply's files are found from what it says; a failure to look is not a reason to stop mirroring.+ const replyFiles = row.role === 'assistant' && deps.uploadMedia && deps.replyAttachments+ ? await deps.replyAttachments(botId, sessionId, row, mirrorMessageText(row, { placeholders: false }) ?? '').catch((error: unknown) => {+ deps.log?.warn('Companion reply files could not be listed', { code: errorCode(error) });+ return [];+ }) : [];+ for (const file of deps.uploadMedia ? [...mirrorAttachments(row), ...replyFiles] : []) {if (file.size > MIRROR_ATTACHMENT_MAX_BYTES) continue;try { media.push(...await deps.uploadMedia!(roomId, sourceId, [file], authorId)); uploaded.push(file.name); }catch (error) {diff --git a/apps/desktop/src/main/companion-cloud/replyArtifacts.ts b/apps/desktop/src/main/companion-cloud/replyArtifacts.tsnew file mode 100644index 0000000000..620ee01999--- /dev/null+++ b/apps/desktop/src/main/companion-cloud/replyArtifacts.ts@@ -0,0 +1,151 @@+/**+ * The files a companion's reply refers to (cloud-companions.md §4): generated media by their+ * `cindy-media://` address, and files the reply names inside the companion's own work folder+ * (`documents/report.docx`, a Markdown link, an `xdt-file://` link). They go to the room with the+ * reply so a computer that takes the companion over can open them. Only what the reply names and+ * what exists inside the task's own folder is sent; nothing else on the disk is ever read.+ */+import fs from 'node:fs/promises';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { buildLooseUrl, extractLoosePath } from '../session-share/mediaUrlRewrite.pure.js';+import type { CompanionMirrorAttachment } from './mirror.js';++/** A reply sends at most this many files to the room. */+export const REPLY_ARTIFACTS_MAX = 8;++const BLOB_URL = /\bcindy-media:\/\/blobs\/[0-9a-f]{64}\.[a-z0-9]+/g;+/** A bare file name (no folder) counts only for the formats people are handed as deliverables. */+const DELIVERABLE_EXT = new Set(['docx', 'doc', 'xlsx', 'xls', 'pptx', 'ppt', 'pdf', 'csv', 'tsv', 'zip', 'key', 'pages', 'numbers']);+const MIME_BY_EXT: Record<string, string> = {+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp',+ pdf: 'application/pdf', zip: 'application/zip', csv: 'text/csv', tsv: 'text/tab-separated-values',+ txt: 'text/plain', md: 'text/markdown', json: 'application/json', html: 'text/html',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+};+/** UNC / WebDAV / device paths are never opened (realpath could contact a remote server). */+const NETWORK_PATH = /^[\\/]{2}|^[\\/]\?\?[\\/]/;++export interface ReplyReferences { blobs: string[]; paths: string[] }++/** What the reply text refers to, in reading order and without duplicates. Code fences are examples, not deliveries. */+export function collectReplyReferences(text: string): ReplyReferences {+ const prose = text.replace(/```[\s\S]*?(?:```|$)/g, ' ');+ const blobs = [...new Set(prose.match(BLOB_URL) ?? [])];+ const paths: string[] = [];+ const add = (candidate: string | null) => {+ if (candidate && !candidate.includes('\0') && !paths.includes(candidate)) paths.push(candidate);+ };+ // Markdown link / image targets (a local path, or an xdt-file link).+ for (const match of prose.matchAll(/\]\(\s*<?([^)>\n]+?)>?(?:\s+"[^"]*")?\s*\)/g)) {+ const target = match[1]!.trim();+ if (target.startsWith('xdt-file://')) {+ add(extractLoosePath(target) ?? hostlessFilePath(target));+ } else if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(target) && !target.startsWith('#') && !target.startsWith('mailto:')) {+ add(safeDecode(target.split(/[?#]/, 1)[0]!));+ }+ }+ // Paths written in the text (inline code or plain).+ for (const raw of prose.split(/[\s"'`<>()[\]{}|,。;:!?、]+/)) {+ const token = raw.replace(/[.,;:]+$/, '');+ if (!token || token.includes('://')) continue;+ // Chinese text is written without spaces: try the token as is and without the words stuck to its ends.+ const bare = token.replace(/^[\u3400-\u9fff\uff00-\uffef]+/, '');+ for (const candidate of new Set([token, bare, token.replace(/[\u3400-\u9fff\uff00-\uffef]+$/, ''), bare.replace(/[\u3400-\u9fff\uff00-\uffef]+$/, '')])) {+ const ext = /\.([A-Za-z0-9]{1,8})$/.exec(candidate)?.[1]?.toLowerCase();+ if (!ext) continue;+ if (candidate.includes('/') ? candidate.length > 1 : DELIVERABLE_EXT.has(ext) && /^[\p{L}\p{N}_.@ -]+$/u.test(candidate)) add(candidate);+ }+ }+ return { blobs, paths };+}++function safeDecode(value: string): string {+ try { return decodeURIComponent(value); } catch { return value; }+}++/** The hostless `xdt-file:///abs/path` form the agent is told to write. */+function hostlessFilePath(url: string): string | null {+ if (!url.startsWith('xdt-file:///')) return null;+ const decoded = safeDecode(url.slice('xdt-file://'.length).split(/[?#]/, 1)[0]!);+ return /^\/[A-Za-z]:[\\/]/.test(decoded) ? decoded.slice(1) : decoded;+}++function within(root: string, target: string): boolean {+ const relative = path.relative(root, target);+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));+}++export interface ReplyArtifactDeps {+ /** The real folders this companion's task may read from (its work folder); empty when none. */+ roots: (sessionId: string) => Promise<string[]>;+ /** A stored media blob: its type and size, or null when this computer does not have it. */+ blob: (url: string, sessionId: string) => Promise<{ mimeType: string; size: number } | null>;+ maxBytes: number;+ log?: { warn: (message: string, meta?: Record<string, unknown>) => void };+}++/** Files the reply names that can go to the room with it (see the file comment). */+export async function replyArtifactAttachments(+ row: { id: string }, text: string, sessionId: string, deps: ReplyArtifactDeps,+): Promise<CompanionMirrorAttachment[]> {+ const refs = collectReplyReferences(text);+ if (!refs.blobs.length && !refs.paths.length) return [];+ const out: CompanionMirrorAttachment[] = [];+ const full = () => out.length >= REPLY_ARTIFACTS_MAX;+ for (const url of refs.blobs) {+ if (full()) break;+ try {+ const blob = await deps.blob(url, sessionId);+ if (!blob || blob.size <= 0 || blob.size > deps.maxBytes) continue;+ out.push({ id: `${row.id}:reply:${out.length}`, name: url.slice(url.lastIndexOf('/') + 1), category: blob.mimeType.startsWith('image/') ? 'image' : 'file',+ mimeType: blob.mimeType, size: blob.size, url, path: null });+ } catch (error) { deps.log?.warn('Reply media not sent to the room', { code: (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN' }); }+ }+ if (!refs.paths.length || full()) return out;+ const roots = await deps.roots(sessionId);+ if (!roots.length) return out;+ const seen = new Set<string>();+ for (const candidate of refs.paths) {+ if (full()) break;+ if (NETWORK_PATH.test(candidate)) continue;+ try {+ // Relative names are the work folder's; an absolute one must still end up inside it.+ const real = await fs.realpath(path.isAbsolute(candidate) ? candidate : path.join(roots[0]!, candidate));+ const root = roots.find(item => within(item, real));+ if (!root || seen.has(real)) continue;+ // Hidden files and folders (.env, .git, …) are never part of a delivery.+ if (path.relative(root, real).split(path.sep).some(part => part.startsWith('.'))) continue;+ const stat = await fs.stat(real);+ if (!stat.isFile() || stat.size <= 0 || stat.size > deps.maxBytes) continue;+ seen.add(real);+ const ext = path.extname(real).slice(1).toLowerCase();+ const mimeType = MIME_BY_EXT[ext] ?? 'application/octet-stream';+ out.push({ id: `${row.id}:reply:${createHash('sha256').update(real).digest('hex').slice(0, 12)}`, name: path.basename(real).slice(0, 200),+ category: mimeType.startsWith('image/') ? 'image' : 'file', mimeType, size: stat.size, url: null, path: real });+ } catch { /* not a file here: the text only mentioned it */ }+ }+ return out;+}++/** A name safe inside Markdown link text. */+const markdownLabel = (name: string) => name.replace(/[\\`*_{}[\]<>#!|]/g, '\\$&').replace(/[\r\n]+/g, ' ');++/**+ * A reply as it reads on the computer that takes the companion over. A reply has no attachment+ * slots, so its files are reachable from the text itself: media the text already names (the same+ * content address) shows as before, anything else is linked below it, and a file that could not+ * come keeps its name.+ */+export function replyTextWithFiles(+ text: string, files: ReadonlyArray<{ name: string; url: string | null; path: string | null }>,+): string {+ const links = files.map(file => {+ if (file.url) return text.includes(file.url) ? '' : ``;+ if (file.path) return `[${markdownLabel(file.name)}](${buildLooseUrl('xdt-file', file.path)})`;+ return `[附件: ${file.name}]`;+ }).filter(Boolean);+ return [text, ...links].filter(Boolean).join('\n\n');+}diff --git a/apps/desktop/src/main/companion-cloud/runtime.ts b/apps/desktop/src/main/companion-cloud/runtime.tsindex f6f73d341c..a47813c567 100644--- a/apps/desktop/src/main/companion-cloud/runtime.ts+++ b/apps/desktop/src/main/companion-cloud/runtime.ts@@ -16,8 +16,9 @@ import type {import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';import { isMobilePlatform } from '@cindy/maker-shared/device-list';import type { CompanionHomeRegistry } from './homes.js';+import type { CompanionArrivalNotice } from './capabilities.js';import { materializeCompanion, rebuildPending, type CompanionHistoryAttachment, type CompanionMaterializeHost, type CompanionMaterializeResult, type CompanionRoomDownload } from './materialize.js';-import { createCompanionMirror, type CompanionMediaUpload, type CompanionMirrorCursor, type CompanionMirrorRow } from './mirror.js';+import { createCompanionMirror, type CompanionMediaUpload, type CompanionMirrorAttachment, type CompanionMirrorCursor, type CompanionMirrorRow } from './mirror.js';import { readAllRoomMessages, transcriptPageOf } from './room.js';import { isCindyCompanion, mergeCompanionsInto, readProfileSnapshot } from './merge.js';import { importCloudHistory } from './materialize.js';@@ -30,6 +31,8 @@ export interface CompanionCloudHost {homes: CompanionHomeRegistry;openState: (endpoint: string, humanActorId: string, current: () => boolean) => CompanionCloudState;readValues: (botId: string) => Promise<CompanionPreferenceValue[]>;+ /** The files a companion reply refers to that go to the room with it (replyArtifacts.ts). */+ replyAttachments?: (botId: string, sessionId: string, row: CompanionMirrorRow, text: string) => Promise<CompanionMirrorAttachment[]>;/** The companion's main task; null when it has none yet. Throws when it cannot be told (conflicting links). */canonicalSession: (botId: string) => Promise<string | null>;rowsAfter: (sessionId: string, cursor: CompanionMirrorCursor, limit: number) => Promise<CompanionMirrorRow[]>;@@ -101,6 +104,9 @@ export interface CompanionCloudRuntime {mergeCindyHere: (keepBotId: string, fromBotIds: string[]) => Promise<CompanionMergeResult>;/** Before a merge on another computer: send everything of a companion homed here to the server. */flushHere: (botId: string) => Promise<CompanionCloudActionResult>;+ /** What the last move to this computer could not keep of the companion's setup, until dismissed. */+ arrivalNotices: (botId: string) => CompanionArrivalNotice[];+ dismissArrivalNotices: (botId: string) => void;/** One of the files in the companion's room, brought to this computer. */attachment: (botId: string, mediaId: string) => Promise<CompanionHistoryAttachment>;/** The companion was deleted on its home (this computer): retire its cloud actor (retried until it succeeds). */@@ -200,7 +206,8 @@ export function startCompanionCloud(input: {});const mirror = createCompanionMirror({ api: input.api, state, humanActorId: () => input.humanActorId,canonicalSession: input.host.canonicalSession, rowsAfter: input.host.rowsAfter, latestRows: input.host.latestRows,- ...(input.media ? { uploadMedia: input.media.upload } : {}), ...(input.log ? { log: input.log } : {}) });+ ...(input.media ? { uploadMedia: input.media.upload } : {}),+ ...(input.host.replyAttachments ? { replyAttachments: input.host.replyAttachments } : {}), ...(input.log ? { log: input.log } : {}) });let disposed = false;const live = () => !disposed && input.current();const aborts = new AbortController();@@ -799,6 +806,13 @@ export function startCompanionCloud(input: {return flushOwn(botId);},+ arrivalNotices: botId => state.bot(botId)?.arrivalNotices ?? [],+ dismissArrivalNotices(botId) {+ const entry = state.bot(botId);+ if (!entry?.arrivalNotices) return;+ state.update(botId, entry.actorId, next => { delete next.arrivalNotices; });+ },+async attachment(botId, mediaId) {const actor = actorOf(botId);if (!actor || !input.media) throw new Error('COMPANION_NOT_FOUND');diff --git a/apps/desktop/src/main/companion-cloud/state.ts b/apps/desktop/src/main/companion-cloud/state.tsindex 6a33287e4b..b28c7c1d26 100644--- a/apps/desktop/src/main/companion-cloud/state.ts+++ b/apps/desktop/src/main/companion-cloud/state.ts@@ -41,6 +41,11 @@ const bot = z.object({pendingRebuild: z.boolean().optional(),/** The never-synced local copy was backed up before a take-over; retries do not back it up again. */backedUp: z.boolean().optional(),+ /**+ * What the last take-over could not keep of the old setup (cloud-companions.md §2): shown once+ * after the move, then cleared by the owner.+ */+ arrivalNotices: z.array(z.enum(['permissions', 'model'])).optional(),/** Deleted here while this computer was the home; disable the cloud actor until it succeeds. */retirePending: z.boolean().optional(),});diff --git a/apps/desktop/src/main/companion-cloud/uploader.ts b/apps/desktop/src/main/companion-cloud/uploader.tsindex 63dfad7274..bd4d9a379e 100644--- a/apps/desktop/src/main/companion-cloud/uploader.ts+++ b/apps/desktop/src/main/companion-cloud/uploader.ts@@ -16,8 +16,10 @@ export const COMPANION_TODO_PREFIX = 'companion.todo.v1:';export const COMPANION_ROUTINE_PREFIX = 'companion.routine.v1:';/** Workbench folders (with the computer each is on) and portable judgments. */export const COMPANION_WORKBENCH_KEY = 'companion.workbench.v1';+/** Capability setup that means the same on any computer (capabilities.ts); never the permission level. */+export const COMPANION_CAPABILITIES_KEY = 'companion.capabilities.v1';const OWNED_PREFIXES = [COMPANION_PROFILE_KEY, COMPANION_MEMORY_PREFIX, COMPANION_SKILL_PREFIX,- COMPANION_TODO_PREFIX, COMPANION_ROUTINE_PREFIX, COMPANION_WORKBENCH_KEY];+ COMPANION_TODO_PREFIX, COMPANION_ROUTINE_PREFIX, COMPANION_WORKBENCH_KEY, COMPANION_CAPABILITIES_KEY];const MAX_KEY_LENGTH = 160;export const COMPANION_VALUE_MAX_BYTES = 60 * 1024;/** A value over the size limit was not uploaded (thrown only when every value is required). */diff --git a/apps/desktop/src/main/companion-cloud/view.ts b/apps/desktop/src/main/companion-cloud/view.tsindex 9f9273ee51..9e4e90a153 100644--- a/apps/desktop/src/main/companion-cloud/view.ts+++ b/apps/desktop/src/main/companion-cloud/view.ts@@ -1,10 +1,11 @@/** Renderer view of companion homes: the registry plus device-link names and presence. */-import type { CompanionCloudSnapshot } from '../../shared/companionCloud.js';+import type { CompanionArrivalNoticeKind, CompanionCloudSnapshot } from '../../shared/companionCloud.js';import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';export async function companionCloudView(snapshot: CompanionCloudSnapshot,listDevices: () => Promise<DeviceLinkDeviceView[]>,+ arrivalNotices: (botId: string) => CompanionArrivalNoticeKind[] = () => [],): Promise<CompanionCloudSnapshot> {if (!snapshot.enabled) return snapshot;// Presence is advisory; without the list the homes still show, just not their names.@@ -12,6 +13,8 @@ export async function companionCloudView(return {...snapshot,actors: snapshot.actors.map(actor => {+ const notices = arrivalNotices(actor.externalId);+ if (notices.length) actor = { ...actor, arrivalNotices: notices };if (!actor.homeDeviceId) return { ...actor, homeDevice: null };const isSelf = actor.homeDeviceId === snapshot.selfDeviceId;const device = devices.find(candidate => candidate.deviceId === actor.homeDeviceId);diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 3874456b94..45d4a5f049 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -1670,8 +1670,14 @@ export async function setBotProfileAvatar(botId: string, image: { buffer: Bufferreturn profile;}+/**+ * Trusted, main-only inputs of a companion restored from the cloud (cloud-companions.md §3.1):+ * the preset it was made from. Never reachable from a renderer or model body.+ */+export interface RestoredBotOrigin { templateId?: unknown }+/** Main-owned creation path shared by the renderer and Bot runtime tools. */-export async function createBotProfile(raw: unknown) {+export async function createBotProfile(raw: unknown, restored?: RestoredBotOrigin) {const body =raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};const draftEntry = body.creationDraftToken ? readBotCreationDraft(body.creationDraftToken) : undefined;@@ -1744,6 +1750,7 @@ export async function createBotProfile(raw: unknown) {delete persistedCapabilities.invitation;delete persistedCapabilities.templateId;if (templateId) persistedCapabilities.templateId = templateId;+ else if (isBotTemplatePresetId(restored?.templateId)) persistedCapabilities.templateId = restored.templateId;if (prepareInvitation) persistedCapabilities.invitation = {id: randomUUID(), stage: 'skills', locale: readBotInvitationLocale(body.locale),avatarRequested: body.generateAvatar === true && !avatarImage,@@ -1848,7 +1855,7 @@ export async function prepareImportedBotInvitation(botId: string, requestId: str/** Shared profile mutation for trusted settings and owner-bound capability selection. */export async function updateBotProfile(raw: unknown, expectedVersion?: number,- validateAdditions?: (update: BotCapabilityUpdate) => Promise<void>) {+ validateAdditions?: (update: BotCapabilityUpdate) => Promise<void>, restored?: RestoredBotOrigin) {const body =raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};const id = readText(body.id, 'botId', 128, true);@@ -1940,7 +1947,9 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,capabilityBaseline: body.capabilityBaseline,});// Template identity survives renames and cannot be replaced through settings.- const retainedTemplate = typeof previous.templateId === 'string' ? previous.templateId : inferBotTemplatePresetId(version?.identitySource ?? '');+ const retainedTemplate = typeof previous.templateId === 'string' ? previous.templateId+ : isBotTemplatePresetId(restored?.templateId) ? restored.templateId+ : inferBotTemplatePresetId(version?.identitySource ?? '');if (retainedTemplate) nextConfig.templateId = retainedTemplate;else delete nextConfig.templateId;// Keep preparation checkpoints outside caller-editable capabilities.diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex c23c0e66a0..fd0f588c87 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -856,6 +856,7 @@ export const MAKER_INVOKE = {COMPANION_CLOUD_MERGE_CINDY: 'maker:companion-cloud:merge-cindy',/** A file of the companion's room, brought to this computer (works while its home is offline). */COMPANION_CLOUD_ATTACHMENT: 'maker:companion-cloud:attachment',+ COMPANION_CLOUD_DISMISS_NOTICES: 'maker:companion-cloud:dismiss-notices',/** Local copy of an avatar from another computer or the cloud (looked up first, optionally fetched). */COMPANION_AVATAR_RESOLVE: 'maker:companion-avatar:resolve',} as const;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 74622fc950..19ba52e7b8 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -2943,6 +2943,8 @@ let botGroupChatServiceHolder: BotGroupChatService | null = null;*/function settleCompanionOwner(): void { void botGroupChatServiceHolder?.chatServer; }let unsubscribeCompanionCloudBroadcast: (() => void) | null = null;+/** What a companion that arrived on this computer could not keep (shown once in its chat). */+const companionArrivalNotices = (botId: string) => activeCompanionCloud()?.arrivalNotices(botId) ?? [];const listCompanionDevices = async () => (await handleListDevices(deviceDirectoryDeps())).devices;/** Cloud-companion version of another computer's Cindy; 0 when it is old or cannot be reached. */async function companionCloudPeerVersion(deviceId: string): Promise<number> {@@ -12652,7 +12654,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)unsubscribeCompanionCloudBroadcast?.();unsubscribeCompanionCloudBroadcast = companionHomes.onChange((snapshot) => {const scope = captureDataOwnerBroadcastScope();- void companionCloudView(snapshot, listCompanionDevices).then((view) => {+ void companionCloudView(snapshot, listCompanionDevices, companionArrivalNotices).then((view) => {// Device lookups can finish out of order: a superseded snapshot is never pushed after a newer one.if (companionHomes.snapshot() !== snapshot) return;broadcastToAllWindows(MAKER_PUSH.COMPANION_CLOUD_CHANGED, view, scope);@@ -12989,7 +12991,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const currentCompanionHomes = () => { settleCompanionOwner(); return companionHomes; };ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_STATE, async (event) => {assertTrustedAppRendererEvent(event);- return companionCloudView(currentCompanionHomes().snapshot(), listCompanionDevices);+ return companionCloudView(currentCompanionHomes().snapshot(), listCompanionDevices, companionArrivalNotices);+ });+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_DISMISS_NOTICES, async (event, botId: unknown) => {+ assertTrustedAppRendererEvent(event);+ const id = companionBotId(botId);+ currentCompanionHomes();+ activeCompanionCloud()?.dismissArrivalNotices(id);});const companionBotId = (value: unknown) => {if (typeof value !== 'string' || !value.trim() || value.length > 200) throwIpcError('INVALID_PARAMS', 'botId required');diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 228ad4784e..21d0b30330 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6276,6 +6276,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:companion-cloud:merge-cindy', keepBotId, fromBotIds),getCompanionAttachment: (botId: string, mediaId: string): Promise<import('../shared/botGroupChat').BotGroupAttachment> =>ipcRenderer.invoke('maker:companion-cloud:attachment', botId, mediaId),+ dismissCompanionArrivalNotices: (botId: string): Promise<void> =>+ ipcRenderer.invoke('maker:companion-cloud:dismiss-notices', botId),resolveCompanionAvatar: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }): Promise<string | null> =>ipcRenderer.invoke('maker:companion-avatar:resolve', request),onBotProfileChanged: fanOutBotProfileChanged,diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsxindex c0dc3cbbd4..d4a6df0aa9 100644--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import { Spinner } from '@/components/ui/spinner';import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';import { useCompanionCloud } from './companionCloudStore';+import { useCompanionArrivalNotice } from './useCompanionArrivalNotice';import { CompanionShadowBanner } from './CompanionShadowBanner';import type { ComposerBotMention } from '@/lib/fileTypes';import { getBotLastReadAt, markBotRead } from './botReadState';@@ -95,6 +96,7 @@ function BotSessionGateView() {const liveAvatar = liveProfile?.avatar;const liveAvatarColor = liveProfile?.avatarColor;const liveInvitationStage = liveProfile?.invitation?.stage;+ useCompanionArrivalNotice(gate.kind === 'ready' ? botId : undefined, liveName);const gateIdentity = gate.kind === 'ready' ? gate.identity : null;const identity = useMemo(() =>diff --git a/apps/desktop/src/renderer/features/bots/useCompanionArrivalNotice.ts b/apps/desktop/src/renderer/features/bots/useCompanionArrivalNotice.tsnew file mode 100644index 0000000000..b157029d41--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/useCompanionArrivalNotice.ts@@ -0,0 +1,27 @@+import { useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { toast } from '@/lib/toast';+import { companionCloudApi, refreshCompanionCloud, useCompanionCloud } from './companionCloudStore';++/** Bots whose notice was already shown in this window, so a stale snapshot never repeats it. */+const shown = new Set<string>();++/**+ * One line after a companion arrived on this computer for what its old setup could not keep (the+ * permission level never travels; a saved model that is not usable here is replaced by this+ * computer's default). Shown when its chat opens, then dismissed in main+ * (docs/product-rules/cloud-companions.md §2).+ */+export function useCompanionArrivalNotice(botId: string | undefined, name: string | undefined): void {+ const { t } = useTranslation();+ const notices = useCompanionCloud().actors.find((actor) => actor.externalId === botId)?.arrivalNotices;+ useEffect(() => {+ if (!botId || !notices?.length || shown.has(botId)) return;+ shown.add(botId);+ for (const notice of notices) {+ toast.info(t(notice === 'model' ? 'bots.cloud.arrivalModel' : 'bots.cloud.arrivalPermissions', { name: name ?? '' }));+ }+ void companionCloudApi()?.dismissCompanionArrivalNotices?.(botId).then(refreshCompanionCloud, () => undefined);+ }, [botId, name, notices, t]);+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e5e321e289..dd87c52123 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10006,6 +10006,8 @@"switchFailed": "Couldn’t move {{name}} to “{{device}}”","homeOutdated": "The main computer “{{device}}” runs an older Cindy. Update it, or change the main computer there","arrivingLater": "{{name}} moved to this computer and is still getting ready. It will appear in your teammates soon",+ "arrivalPermissions": "{{name}} now uses this computer’s default permissions.",+ "arrivalModel": "{{name}}’s saved model isn’t available on this computer, so it follows this computer’s default model.","busyTitle": "{{name}} is still replying","busyDescription": "Move it to “{{device}}” once this reply finishes, or stop the reply and move it now.","busyWait": "Move When Done",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c634b6c660..44720368db 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9972,6 +9972,8 @@"switchFailed": "{{name}} を「{{device}}」に移せませんでした","homeOutdated": "メインのパソコン「{{device}}」の Cindy が古いバージョンです。更新するか、そのパソコンで変更してください","arrivingLater": "{{name}} はこのパソコンに移り、準備中です。まもなくチームメイト一覧に表示されます",+ "arrivalPermissions": "{{name}} はこのパソコンの既定の権限で動作します。",+ "arrivalModel": "{{name}} の保存済みモデルはこのパソコンでは使えないため、このパソコンの既定モデルを使います。","busyTitle": "{{name}} はまだ返信中です","busyDescription": "この返信が終わってから「{{device}}」に移すか、返信を止めてすぐに移せます。","busyWait": "終わってから移す",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 66f9c9d783..9a9c7de0e3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9972,6 +9972,8 @@"switchFailed": "{{name}}을(를) “{{device}}”(으)로 옮기지 못했습니다","homeOutdated": "주 컴퓨터 “{{device}}”의 Cindy가 이전 버전입니다. 업데이트하거나 그 컴퓨터에서 변경하세요","arrivingLater": "{{name}}이(가) 이 컴퓨터로 옮겨졌고 아직 준비 중입니다. 곧 팀원 목록에 표시됩니다",+ "arrivalPermissions": "{{name}}은(는) 이 컴퓨터의 기본 권한으로 실행됩니다.",+ "arrivalModel": "{{name}}에 저장된 모델을 이 컴퓨터에서 사용할 수 없어 이 컴퓨터의 기본 모델을 사용합니다.","busyTitle": "{{name}}이(가) 아직 답장 중입니다","busyDescription": "이번 답장이 끝난 뒤 “{{device}}”(으)로 옮기거나, 답장을 멈추고 바로 옮길 수 있습니다.","busyWait": "끝나면 옮기기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0f0fe7389c..0770a04aa6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9972,6 +9972,8 @@"switchFailed": "未能把 {{name}} 换到「{{device}}」","homeOutdated": "主力电脑「{{device}}」上的 Cindy 版本较旧,请先更新它,或在那台电脑上更换","arrivingLater": "{{name}} 已换到这台电脑,还在准备中,稍后会出现在伙伴列表里",+ "arrivalPermissions": "{{name}} 已按这台电脑的默认权限运行。",+ "arrivalModel": "{{name}} 之前选的模型在这台电脑上不可用,已改用这台电脑的默认模型。","busyTitle": "{{name}} 还在回复","busyDescription": "可以等这一轮结束后再换到「{{device}}」,也可以停止这一轮马上换。","busyWait": "等回复完再换",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d6cdcbde1a..450c6f86f5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9972,6 +9972,8 @@"switchFailed": "未能把 {{name}} 換到「{{device}}」","homeOutdated": "主力電腦「{{device}}」上的 Cindy 版本較舊,請先更新它,或在那台電腦上更換","arrivingLater": "{{name}} 已換到這台電腦,還在準備中,稍後會出現在夥伴列表裡",+ "arrivalPermissions": "{{name}} 已依這台電腦的預設權限運作。",+ "arrivalModel": "{{name}} 先前選的模型在這台電腦上無法使用,已改用這台電腦的預設模型。","busyTitle": "{{name}} 還在回覆","busyDescription": "可以等這一輪結束後再換到「{{device}}」,也可以停止這一輪馬上換。","busyWait": "等回覆完再換",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 732ccc0aa6..1131399ac8 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5557,6 +5557,7 @@ interface ElectronAPI {listCindyCopies: () => Promise<import('../shared/companionCloud').CompanionCindyCopy[]>;mergeCindy: (keepBotId: string, fromBotIds: string[]) => Promise<import('../shared/companionCloud').CompanionMergeResult>;getCompanionAttachment: (botId: string, mediaId: string) => Promise<import('../shared/botGroupChat').BotGroupAttachment>;+ dismissCompanionArrivalNotices: (botId: string) => Promise<void>;resolveCompanionAvatar: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }) => Promise<string | null>;onCompanionCloudChanged: (cb: (diff --git a/apps/desktop/src/shared/companionCloud.ts b/apps/desktop/src/shared/companionCloud.tsindex bb861e4086..b0f8e4c8e7 100644--- a/apps/desktop/src/shared/companionCloud.ts+++ b/apps/desktop/src/shared/companionCloud.ts@@ -7,6 +7,9 @@ export interface CompanionCloudHomeDevice {isSelf: boolean;}+/** What a move to this computer could not keep of the companion's old setup (cloud-companions.md §2). */+export type CompanionArrivalNoticeKind = 'permissions' | 'model';+export interface CompanionCloudActor {/** Chat Server actor id. */id: string;@@ -18,6 +21,8 @@ export interface CompanionCloudActor {homeDeviceId: string | null;/** Resolved home computer; only present in the renderer view (state IPC / change push). */homeDevice?: CompanionCloudHomeDevice | null;+ /** Only in the renderer view: shown once after the companion arrived here, then dismissed. */+ arrivalNotices?: CompanionArrivalNoticeKind[];}export interface CompanionCloudSnapshot {diff --git a/docs/product-rules/cloud-companions.md b/docs/product-rules/cloud-companions.mdindex ea67eb464f..d471ef21b4 100644--- a/docs/product-rules/cloud-companions.md+++ b/docs/product-rules/cloud-companions.md@@ -28,15 +28,25 @@2. 多台电脑上原有的 Cindy 合成一个:统一身份与聊天,保留旧记录的来源,资料冲突时由用户选择保留哪份(替代上面第 4 条里「其他电脑上的 Cindy 对话只作本机历史」的做法,分批落地,见 §6「未覆盖」)。+2026-10-22 产品裁决(用户确认,换电脑时能力配置与回复产物跟着走):++1. 能力配置跟着伙伴走:技能 / MCP / 工具集的**引用 id**与各自的选择模式、记忆开关、代输入与「它开的任务也交给总调度跟」开关、+ 模型偏好随行;MCP / 技能 / 工具集的配置与凭证从不随行。新电脑没有的引用保留,在能力设置里显示「这台电脑不可用」,+ 不静默删除。+2. 权限档**不**随行:新电脑上新建的伙伴按这台电脑的默认档,换电脑后提示一行。+3. 模型是偏好而不是连接:同一来源 + 型号在新电脑可用就沿用;不可用就跟随这台电脑的默认模型并提示一行,不带任何连接凭证。+4. 伙伴回复里引用的产物(生成的媒体、工作目录里的文件)跟着回复上云,换电脑后能在新电脑打开,不再是坏图或只剩文件名。+## 2. 数据归属| 存在服务器(跟着伙伴走) | 只留在主力电脑 ||---|---|| 身份:名字、头像(Chat Server actor) | 工作目录 `workspace/` 与其中文件 || 资料:简介、SOUL、自定义提示词、关于用户(USER.md)、来自哪个预设(`templateId`) | 模型连接、登录凭证、MCP 配置、权限档 |+| 能力配置(`companion.capabilities.v1`):技能 / MCP / 工具集的引用 id 与选择模式、记忆开关、代输入与跟进开关、模型偏好(自己选的模型链与任务模型,不含连接) | 技能 / MCP / 工具集本身的配置与凭证;权限档 || 记忆:`memories/*.md` 每条一份 | 完整运行记录(工具调用、思考) || 自有技能:`skills/<slug>/SKILL.md` | 例行任务的执行与运行记录(只在主力电脑运行) |-| 1:1 对话层:用户消息与伙伴最终回复,以及主人发送的附件原件 | 待办里在途的投递、插件的游标与回执 |+| 1:1 对话层:用户消息与伙伴最终回复,以及主人发送的附件原件、回复里引用的产物(生成的媒体、工作目录里被点名的文件) | 待办里在途的投递、插件的游标与回执 || 待办(未完成、设为稍后、近 30 天内完成的,最多 500 条,每条一份) | 工作台项目的文件本身 || 例行任务的定义(每条一份,不含运行记录) | || 工作台:项目目录(标明在哪台电脑上)与 PR / issue / 想法的判断 | |@@ -45,8 +55,15 @@- 服务器是对话层与资料快照的权威副本;主力电脑是运行与写入的唯一来源。- **只有主力电脑写云端资料**。其他电脑修改伙伴设置时,经现有远程设置(device-link)写到主力电脑,再由主力电脑上传。主力电脑离线时,其他端只读显示云端资料,不提供离线编辑,避免两端改出冲突。-- 模型候选链引用的是主力电脑的连接与型号,不跨电脑复用。换主力电脑后,新电脑先跟随本机默认模型,- 用户可再在设置里选。+- 模型是偏好,连接不跨电脑复用(2026-10-22 起,取代此前「换主力电脑后新电脑先跟随本机默认模型」):+ 只上传伙伴自己选定的模型链与任务模型(跟随默认的不上传,新电脑同样跟随它自己的默认;指定在别的电脑上运行的路线不带),+ 不含连接与凭证。接管时逐条检查这台电脑能否用同一来源 + 型号:能用的保留(按原顺序),不能用的去掉,一条都不能用就跟随+ 这台电脑的默认模型,并在伙伴聊天里提示一行。+- 能力引用的处理:技能 / MCP / 工具集只带 id;这台电脑没有的引用原样保留,能力设置里标成「这台电脑不可用」+ (沿用现有目录里 `available: false` 的呈现),装好之后自然生效,不静默删除。+- 权限档不随行:接管时新建的副本使用新建伙伴的默认档,并提示一行;接管已有的本机副本时保留它自己的权限档,不提示。+- 旧版本主力电脑没有 `companion.capabilities.v1`:接管时保持原行为(不改能力配置,新建的副本用默认值),其资料快照里的+ `templateId` 仍会恢复到新建的副本上。## 3. 主力电脑@@ -76,7 +93,7 @@显示的内部续接输入不上云。- 点「在这台电脑继续」:1. 服务器把主力电脑改成这台电脑(带原主力电脑做比较,避免两端同时抢);- 2. 这台电脑按云端资料、记忆和技能建立(或更新)本机伙伴,伙伴 ID 与云端一致;+ 2. 这台电脑按云端资料、记忆、技能和能力配置建立(或更新)本机伙伴,伙伴 ID 与云端一致(权限档不随行,见 §2);3. 把云端对话导入本机主任务作为历史,并以持久交接重建模型上下文,不重放任何旧请求;4. 打开这台电脑上的伙伴聊天,用户可以直接继续说话。- 手机上同样显示离线横幅,「换一台电脑继续」列出在线且已允许远程控制的电脑;选中后服务器改主力@@ -108,9 +125,17 @@任意电脑并发创建得到同一个房间。- 主力电脑把主任务里用户可见的消息和伙伴的最终回复按顺序导入这个房间(导入不触发伙伴执行、不发通知),以本机消息 ID 去重,断网后从上次位置续传。主人发送的图片和文件经房间附件上传,其他设备可以打开,换电脑时下载到新电脑;- 只有永远传不了(文件已不在、超过大小、旧格式地址、聊天服务器拒绝)时才退回文件名占位;暂时失败(断网、服务器 5xx、超时、+ 只有永远传不了(文件已不在、超过大小、旧格式地址、聊天服务器拒绝)时才退回文件名占位(伙伴回复不加占位,保持原话);暂时失败(断网、服务器 5xx、超时、签名地址过期——对象存储返回 401/403)时这一轮停下、下一轮连同这条消息重试,换电脑时的下载与合并 Cindy 时的搬运同样按这条区分(暂时失败则- 接管或合并本次失败、稍后重试)。只发附件没有文字的消息同样同步。伙伴回复里引用的文件暂不上传。+ 接管或合并本次失败、稍后重试)。只发附件没有文字的消息同样同步。+- 伙伴回复里引用的产物随回复上云(`replyArtifacts.ts`):正文里的 `cindy-media://blobs/…` 地址(该任务能读、本机有字节的),+ 以及回复里点名的文件——Markdown 链接目标、`xdt-file://` 链接、行内代码或正文里的路径(`documents/报告.docx`;不带目录的名字+ 只认 docx / xlsx / pptx / pdf / csv / zip 等交付格式),代码块里的示例不算。文件必须真实存在于该任务自己的工作目录内+ (符号链接按真实路径复核,隐藏文件与目录如 `.env`、`.git` 不上传,目录外与 UNC 路径不读),单个不超过 25 MB,每条回复最多 8 个;+ 经与主人附件同一条房间附件通道上传,永久 / 暂时失败的区分与主人附件一致(暂时失败这一轮停下重试,永久失败只发正文)。+ 换电脑导入时,房间里的附件先下载并入库(图片入媒体仓,同一字节得到同一个 `cindy-media://` 地址)、挂上任务引用,再写消息,+ 所以回复里原有的 `cindy-media://` 图片在新电脑直接显示;正文没提到的图片和非图片文件作为链接追加在回复下面+ (文件按房间附件落盘方式保存在本机,链接指向它),不再只写 `[附件: …]` 占位。- 房间保存完整对话:开始同步之前的本机历史(包括这台电脑接管前自己的历史)在后台按时间从旧到新补传,每轮有上限,交出前补完。房间按到达顺序排列,读取时(离线查看、接管导入、手机)按消息时间排序。- 主力电脑在线时,其他电脑与手机继续用现有远程方式(device-link)直接看和发主任务,体验不变。@@ -234,15 +259,22 @@- Agent 与用户同权:伙伴工具 `get_teammate_home` / `move_teammate_home` 查看与更换任一伙伴的主力电脑(与界面同一条路径),更换交给当前任务的权限档。- 头像:见 §3.2。+- 能力配置随行的已知取舍(2026-10-22):新电脑上不可用的模型被默认模型替换后,新主力电脑上传的偏好就不再带这条模型链,+ 之后再换回原电脑时那边跟随它自己的默认,不会恢复当初选的模型;提示只在伙伴聊天打开时出现一次(设置里不常驻)。+ `permissions` 在新建副本上是默认档,不推断也不提示原电脑上是什么档。技能的 `skills` 列表只是引用,伙伴自有技能仍按+ `companion.skill.v1` 随行;能力值读不出来时本轮不上传、不写墓碑,交出前的 flush 因此失败而不是丢掉它。+- 回复产物的已知限制:只认回复文字里点名的路径与地址,是启发式的(例如不带目录又不是交付格式的文件名不会被识别);+ 视频、音频等非图片的 `cindy-media://` 产物在新电脑上以文件链接出现,正文里原地址不会变成可播放;`workspace/` 本身仍不搬,+ 正文里的相对路径在新电脑的工作目录里不存在,打开要用追加的文件链接;同一个文件被多条回复引用会各上传一次。- 未覆盖、留作后续:手机与非主力电脑离线编辑资料;IM 渠道按伙伴绑定;离线时在其他端直接发送并排队;- 伙伴回复里引用的文件上云;手机端合并 Cindy;合并时让用户逐条选择同名内容保留哪份(目前两份都保留)。+ 手机端合并 Cindy;合并时让用户逐条选择同名内容保留哪份(目前两份都保留)。## 7. 实现位置- 服务器:`cindy-server/chat-server`(actor 的 `home_device_id`、按主力电脑过滤领取、私聊房间确定 ID、`/me` 的设备标识与能力开关)。- Desktop:`apps/desktop/src/main/companion-cloud/`(登记主力电脑、资料上传、对话导入、接管、降级、- 删除时停用);渲染层 `features/bots/` 的 `companionCloudStore.ts`(`maker:companion-cloud:*` 状态与变化推送)、- `CloudCompanionOfflineView.tsx`(离线横幅与云端对话)、`BotHomeComputerSetting.tsx`(设置里的「主力电脑」行与+ 删除时停用;`capabilities.ts` 能力配置随行,`replyArtifacts.ts` 回复产物);渲染层 `features/bots/` 的 `companionCloudStore.ts`(`maker:companion-cloud:*` 状态与变化推送)、+ `useCompanionArrivalNotice.ts`(换电脑后的权限 / 模型提示,打开聊天时一次)、`CloudCompanionOfflineView.tsx`(离线横幅与云端对话)、`BotHomeComputerSetting.tsx`(设置里的「主力电脑」行与换电脑的确认流程;聊天头部近况浮层 `BotGlancePopover.tsx` 的「电脑」块复用它,任何电脑上都可更换)。- Mobile:伙伴离线横幅、云端对话只读视图与换电脑选择。