Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(bots): 伙伴跨设备存在:任意电脑换主力电脑、完整历史与附件、合并 Cindy (#6257)

Dash48a8321cb6c1
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/attachmentFailure.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/attachmentFailure.test.ts
new file mode 100644
index 0000000000..4f89571038
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/__tests__/attachmentFailure.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+import { isTransientAttachmentFailure } from '../types.js';
+
+describe('attachment failures', () => {
+ it('retries what may still come and gives up only on what never will', () => {
+ const status = (code: number) => Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: code });
+ for (const error of [new Error('MEDIA_DOWNLOAD_FAILED'), new Error('ECONNRESET'), new Error('net::ERR_INTERNET_DISCONNECTED'),
+ new TypeError('fetch failed'), Object.assign(new Error('timed out'), { name: 'TimeoutError' }), status(503), status(429),
+ // An expired signed address, upload or download.
+ status(403), status(401), Object.assign(new Error('MEDIA_DOWNLOAD_FAILED'), { status: 403 })]) {
+ expect(isTransientAttachmentFailure(error)).toBe(true);
+ }
+ for (const error of [new Error('ATTACHMENT_TOO_LARGE'), new Error('ATTACHMENT_UNAVAILABLE'), new Error('INVALID_MEDIA_SIZE'),
+ new Error('MEDIA_UNAVAILABLE'), status(404), status(413),
+ // The chat server refusing the file is not a signature to renew.
+ Object.assign(new Error('FORBIDDEN'), { status: 403 }),
+ Object.assign(new Error('MEDIA_DOWNLOAD_FAILED'), { status: 404 }), 'nope']) {
+ expect(isTransientAttachmentFailure(error)).toBe(false);
+ }
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/avatarCache.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/avatarCache.test.ts
new file mode 100644
index 0000000000..77e13cc6ec
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/__tests__/avatarCache.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, vi } from 'vitest';
+import { companionAvatarKey, createCompanionAvatarCache, type CompanionAvatarCacheDeps } from '../avatarCache.js';
+
+const HASH = 'a'.repeat(64);
+const BLOB = `cindy-media://blobs/${HASH}.png`;
+const CLOUD = 'https://cdn.example.com/cindy/public/avatar/owner/793983c0.png';
+const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
+
+function setup(overrides: Partial<CompanionAvatarCacheDeps> = {}) {
+ const store = new Map<string, string>();
+ let clock = 0;
+ const account = { key: 'owner-a', current: true };
+ const get = vi.fn(async (key: string) => store.get(key) ?? null);
+ const put = vi.fn(async (key: string, _bytes: Uint8Array, _mimeType: string) => { const url = `cindy-media://blobs/${'b'.repeat(64)}.png`; store.set(key, url); return url; });
+ const deps = {
+ localBlob: vi.fn(async (_url: string): Promise<string | null> => null),
+ get, put,
+ scope: vi.fn(() => {
+ const captured = account.key;
+ const check = () => { if (account.key !== captured) throw new Error('OWNER_CHANGED'); };
+ return { key: captured, get: async (key: string) => { check(); return get(key); },
+ put: async (key: string, bytes: Uint8Array, mimeType: string) => { check(); return put(key, bytes, mimeType); } };
+ }),
+ fetchFromDevice: vi.fn(async () => ({ buffer: PNG })),
+ fetchPublic: vi.fn(async () => ({ buffer: PNG })),
+ sniff: vi.fn((bytes: Uint8Array) => (bytes[0] === 0x89 ? 'image/png' : null)),
+ now: () => clock,
+ ...overrides,
+ };
+ return { cache: createCompanionAvatarCache(deps), deps, store, account, tick: (ms: number) => { clock += ms; } };
+}
+
+describe('companion avatar cache', () => {
+ it('keys only avatars held elsewhere', () => {
+ expect(companionAvatarKey(CLOUD)).toBe(`companion-avatar:${CLOUD}`);
+ expect(companionAvatarKey(BLOB, 'laptop')).toBe(`companion-avatar:blob:${HASH}`);
+ // A local blob needs no copy; emoji and presets are not addresses.
+ expect(companionAvatarKey(BLOB)).toBeNull();
+ expect(companionAvatarKey('🦊')).toBeNull();
+ expect(companionAvatarKey('http://insecure.example/a.png')).toBeNull();
+ });
+
+ it('only looks unless asked to fetch, then keeps the copy and answers from it', async () => {
+ const t = setup();
+ expect(await t.cache.resolve({ avatar: CLOUD })).toBeNull();
+ expect(t.deps.fetchPublic).not.toHaveBeenCalled();
+ const copy = await t.cache.resolve({ avatar: CLOUD, fetch: true });
+ expect(copy).toMatch(/^cindy-media:\/\/blobs\//);
+ expect(t.deps.put).toHaveBeenCalledWith(`companion-avatar:${CLOUD}`, PNG, 'image/png');
+ // Offline from now on: the copy still answers, nothing is fetched again.
+ vi.mocked(t.deps.fetchPublic).mockRejectedValue(new Error('offline'));
+ expect(await t.cache.resolve({ avatar: CLOUD, fetch: true })).toBe(copy);
+ expect(t.deps.fetchPublic).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses content already in the local store before asking the other computer', async () => {
+ const t = setup({ localBlob: vi.fn(async () => BLOB) });
+ expect(await t.cache.resolve({ avatar: BLOB, deviceId: 'laptop', fetch: true })).toBe(BLOB);
+ expect(t.deps.fetchFromDevice).not.toHaveBeenCalled();
+ });
+
+ it('copies another computer\'s avatar through device-link', async () => {
+ const t = setup();
+ expect(await t.cache.resolve({ avatar: BLOB, deviceId: 'laptop', fetch: true })).toMatch(/^cindy-media:/);
+ expect(t.deps.fetchFromDevice).toHaveBeenCalledWith('laptop', BLOB);
+ });
+
+ it('keeps only image bytes and backs off after a failure', async () => {
+ const t = setup({ fetchPublic: vi.fn(async () => ({ buffer: new Uint8Array([1, 2, 3]) })) });
+ expect(await t.cache.resolve({ avatar: CLOUD, fetch: true })).toBeNull();
+ expect(t.deps.put).not.toHaveBeenCalled();
+ await t.cache.resolve({ avatar: CLOUD, fetch: true });
+ expect(t.deps.fetchPublic).toHaveBeenCalledTimes(1);
+ t.tick(61_000);
+ await t.cache.resolve({ avatar: CLOUD, fetch: true });
+ expect(t.deps.fetchPublic).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares one download between concurrent requests', async () => {
+ const t = setup();
+ const [a, b] = await Promise.all([t.cache.resolve({ avatar: CLOUD, fetch: true }), t.cache.resolve({ avatar: CLOUD, fetch: true })]);
+ expect(a).toBe(b);
+ expect(t.deps.fetchPublic).toHaveBeenCalledTimes(1);
+ });
+
+ it('never keeps a copy for the next account when the account changes during the download', async () => {
+ const finish: Array<() => void> = [];
+ const t = setup({ fetchPublic: vi.fn(() => new Promise<{ buffer: Uint8Array }>((resolve) => { finish.push(() => resolve({ buffer: PNG })); })) });
+ const first = t.cache.resolve({ avatar: CLOUD, fetch: true });
+ await vi.waitFor(() => expect(t.deps.fetchPublic).toHaveBeenCalledOnce());
+ t.account.key = 'owner-b';
+ // The new account does not join the old account's download.
+ const second = t.cache.resolve({ avatar: CLOUD, fetch: true });
+ await vi.waitFor(() => expect(t.deps.fetchPublic).toHaveBeenCalledTimes(2));
+ finish[0]!();
+ expect(await first).toBeNull();
+ finish[1]!();
+ expect(await second).toMatch(/^cindy-media:\/\/blobs\//);
+ expect(t.deps.put).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts
index 9577147776..21190d7334 100644
--- a/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts
+++ b/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts
@@ -20,7 +20,8 @@ afterEach(() => { runtime?.dispose(); runtime = undefined; });
function setup(options: { home: string | null; handler?: ApiHandler; devices?: DeviceLinkDeviceView[]; profiles?: string[];
installationId?: string; probe?: (deviceId: string) => Promise<boolean>; values?: Array<{ key: string; value: unknown }>;
readValues?: () => Promise<Array<{ key: string; value: unknown }>>; syncProfile?: (botId: string) => Promise<void>;
- turnActive?: () => boolean }) {
+ turnActive?: () => boolean; homeLink?: CompanionCloudHost['homeLink']; stopBotTurns?: CompanionCloudHost['stopBotTurns'];
+ canonicalSession?: CompanionCloudHost['canonicalSession']; paused?: (botId: string) => boolean }) {
const actors: CompanionRuntimeActor[] = [{ id: 'actor-1', kind: 'bot', externalId: 'bot_mia', name: 'Mia', avatar: null, homeDeviceId: options.home }];
const { api, calls } = fakeApi(options.handler ?? ((route, method) => {
// The home has uploaded the profile snapshot a take-over builds from.
@@ -38,16 +39,19 @@ function setup(options: { home: string | null; handler?: ApiHandler; devices?: D
const host: CompanionCloudHost = {
homes: createCompanionHomeRegistry(), openState: () => state,
readValues: options.readValues ?? (async () => options.values ?? [{ key: 'companion.profile.v1', value: { name: 'Mia' } }]),
- canonicalSession: async () => 'session-1', rowsAfter: async () => [], latestRows: async () => [],
+ canonicalSession: options.canonicalSession ?? (async () => 'session-1'), rowsAfter: async () => [], latestRows: async () => [],
deliverToCanonical: async () => ({ ok: true }),
materializer: local.host, listDevices: async () => options.devices ?? [],
...(options.installationId ? { installationId: () => options.installationId! } : {}),
...(options.probe ? { probeCompanionCloud: options.probe } : {}),
...(options.turnActive ? { isBotBusy: async () => options.turnActive!() } : {}),
+ ...(options.homeLink ? { homeLink: options.homeLink } : {}),
+ ...(options.stopBotTurns ? { stopBotTurns: options.stopBotTurns } : {}),
};
runtime = startCompanionCloud({ api, host, endpoint: 'https://chat', humanActorId: 'human', selfDeviceId: 'desk', current: () => true,
bots: () => actors.filter(a => a.homeDeviceId === 'desk' && !state.isDemoted(a.externalId)).map(a => ({ botId: a.externalId, actorId: a.id, name: a.name })),
- actors: () => actors, refresh, publish, ...(options.syncProfile ? { syncProfile: options.syncProfile } : {}) });
+ actors: () => actors, refresh, publish, ...(options.syncProfile ? { syncProfile: options.syncProfile } : {}),
+ ...(options.paused ? { paused: options.paused } : {}) });
return { runtime, actors, calls, local, state, refresh, publish };
}
@@ -228,6 +232,18 @@ describe('transfer', () => {
expect(failing.state.isDemoted('bot_mia')).toBe(false);
});
+ it('uploads an edit made while the name and avatar were being published, before moving the home', async () => {
+ let values: Array<{ key: string; value: unknown }> = [{ key: 'companion.profile.v1', value: { name: 'Mia' } }];
+ const t = setup({ home: 'desk', devices: [device('laptop')], readValues: async () => values,
+ syncProfile: async () => { values = [...values, { key: 'companion.memory.v1:late.md', value: { content: 'saved meanwhile' } }]; } });
+ expect(await t.runtime.transfer('bot_mia', 'laptop')).toEqual({ ok: true });
+ const late = t.calls.findIndex(call => call.method === 'PUT' && String(call.route).includes('late.md')
+ || (call.data as { key?: string } | undefined)?.key === 'companion.memory.v1:late.md');
+ const patch = t.calls.findIndex(call => call.method === 'PATCH');
+ expect(late).toBeGreaterThanOrEqual(0);
+ expect(late).toBeLessThan(patch);
+ });
+
it('does not move the home while a turn is still running, checked before and after the flush', async () => {
const busy = setup({ home: 'desk', devices: [device('laptop')], turnActive: () => true });
expect(await busy.runtime.transfer('bot_mia', 'laptop')).toEqual({ ok: false, code: 'BUSY' });
@@ -257,6 +273,129 @@ describe('transfer', () => {
});
});
+describe('moving a companion that is still working', () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('waits for the turn to finish when asked, then moves it', async () => {
+ vi.useFakeTimers();
+ let busy = true;
+ const t = setup({ home: 'desk', devices: [device('laptop')], turnActive: () => busy });
+ const moved = t.runtime.transfer('bot_mia', 'laptop', { whenBusy: 'wait' });
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ busy = false;
+ await vi.advanceTimersByTimeAsync(2_000);
+ vi.useRealTimers();
+ expect(await moved).toEqual({ ok: true });
+ expect(t.actors[0]!.homeDeviceId).toBe('laptop');
+ });
+
+ it('gives up as busy when the turn does not finish in time', async () => {
+ vi.useFakeTimers();
+ const t = setup({ home: 'desk', devices: [device('laptop')], turnActive: () => true });
+ const moved = t.runtime.transfer('bot_mia', 'laptop', { whenBusy: 'wait' });
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(await moved).toEqual({ ok: false, code: 'BUSY' });
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ });
+
+ it('stops the turn first when asked', async () => {
+ vi.useFakeTimers();
+ let busy = true;
+ const stopBotTurns = vi.fn(async () => { busy = false; });
+ const t = setup({ home: 'desk', devices: [device('laptop')], turnActive: () => busy, stopBotTurns });
+ const moved = t.runtime.transfer('bot_mia', 'laptop', { whenBusy: 'stop' });
+ await vi.advanceTimersByTimeAsync(2_000);
+ vi.useRealTimers();
+ expect(await moved).toEqual({ ok: true });
+ expect(stopBotTurns).toHaveBeenCalledWith('bot_mia');
+ });
+
+ it('still refuses by default', async () => {
+ const t = setup({ home: 'desk', devices: [device('laptop')], turnActive: () => true });
+ expect(await t.runtime.transfer('bot_mia', 'laptop')).toEqual({ ok: false, code: 'BUSY' });
+ });
+
+ it('passes the choice to the home when asked from another computer', async () => {
+ const handOver = vi.fn(async () => ({ ok: true as const }));
+ const t = setup({ home: 'laptop', devices: [device('laptop')], homeLink: {
+ version: async () => 2, targets: async () => [{ deviceId: 'tablet', name: 'Tablet', online: true }], handOver } });
+ expect(await t.runtime.switchHome('bot_mia', 'tablet', { whenBusy: 'stop' })).toEqual({ ok: true });
+ expect(handOver).toHaveBeenCalledWith('laptop', 'bot_mia', 'tablet', { whenBusy: 'stop' });
+ });
+});
+
+describe('switch home from any computer', () => {
+ const link = (version: number, targets = [{ deviceId: 'desk', name: '', online: true }, { deviceId: 'tablet', name: 'Tablet', online: true }]) => ({
+ version: vi.fn(async () => version),
+ targets: vi.fn(async () => targets),
+ handOver: vi.fn(async (): Promise<{ ok: true } | { ok: false; code: 'BUSY' }> => ({ ok: true })),
+ });
+
+ it('hands over from here when this computer is the home', async () => {
+ const t = setup({ home: 'desk', devices: [device('laptop')] });
+ expect(await t.runtime.homeChoices('bot_mia')).toEqual({ homeDeviceId: 'desk', homeName: '', mode: 'local', targets: [{ deviceId: 'laptop', name: 'laptop', online: true }] });
+ expect(await t.runtime.switchHome('bot_mia', 'laptop')).toEqual({ ok: true });
+ expect(t.state.isDemoted('bot_mia')).toBe(true);
+ });
+
+ it('asks the online home to hand the companion over, and re-reads homes when it moved here', async () => {
+ const homeLink = link(2);
+ const t = setup({ home: 'laptop', devices: [device('laptop'), device('desk', { isSelf: true, name: 'Desk' })], homeLink });
+ expect(await t.runtime.homeChoices('bot_mia')).toEqual({ homeDeviceId: 'laptop', homeName: 'laptop', mode: 'remote', targets: [
+ { deviceId: 'desk', name: 'Desk', online: true, isSelf: true },
+ { deviceId: 'tablet', name: 'Tablet', online: true, isSelf: false },
+ ] });
+ expect(await t.runtime.switchHome('bot_mia', 'desk')).toEqual({ ok: true });
+ expect(homeLink.handOver).toHaveBeenCalledWith('laptop', 'bot_mia', 'desk', undefined);
+ expect(t.refresh).toHaveBeenCalled();
+ // The home itself moves it: this computer never writes the home directly.
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ });
+
+ it('passes the home\'s refusal through unchanged', async () => {
+ const homeLink = link(2);
+ homeLink.handOver.mockResolvedValue({ ok: false, code: 'BUSY' });
+ const t = setup({ home: 'laptop', devices: [device('laptop')], homeLink });
+ expect(await t.runtime.switchHome('bot_mia', 'tablet')).toEqual({ ok: false, code: 'BUSY' });
+ });
+
+ it('refuses a computer the home did not offer', async () => {
+ const homeLink = link(2);
+ const t = setup({ home: 'laptop', devices: [device('laptop')], homeLink });
+ expect(await t.runtime.switchHome('bot_mia', 'phone')).toEqual({ ok: false, code: 'TARGET_UNAVAILABLE' });
+ expect(homeLink.handOver).not.toHaveBeenCalled();
+ });
+
+ it('only offers this computer when the home cannot be reached, and takes it over', async () => {
+ const homeLink = link(0);
+ const t = setup({ home: 'laptop', devices: [device('laptop'), device('desk', { isSelf: true, name: 'Desk' })], homeLink });
+ expect(await t.runtime.homeChoices('bot_mia')).toEqual({ homeDeviceId: 'laptop', homeName: 'laptop', mode: 'takeOver',
+ targets: [{ deviceId: 'desk', name: 'Desk', online: true, isSelf: true }] });
+ const offline = setup({ home: 'laptop', devices: [device('laptop', { online: false })], homeLink });
+ expect((await offline.runtime.homeChoices('bot_mia')).mode).toBe('takeOver');
+ expect(await offline.runtime.switchHome('bot_mia', 'desk')).toEqual({ ok: true });
+ expect(offline.calls.find(call => call.method === 'PATCH')).toMatchObject({ data: { homeDeviceId: 'desk', expectedHomeDeviceId: 'laptop' } });
+ expect(homeLink.handOver).not.toHaveBeenCalled();
+ });
+
+ it('does not offer a move when the home runs an older Cindy', async () => {
+ const homeLink = link(1);
+ const t = setup({ home: 'laptop', devices: [device('laptop')], homeLink });
+ expect(await t.runtime.homeChoices('bot_mia')).toEqual({ homeDeviceId: 'laptop', homeName: 'laptop', mode: 'unavailable', reason: 'HOME_OUTDATED', targets: [] });
+ expect(await t.runtime.switchHome('bot_mia', 'desk')).toEqual({ ok: false, code: 'HOME_OUTDATED' });
+ expect(homeLink.targets).not.toHaveBeenCalled();
+ });
+
+ it('re-reads homes when the hand-over answer is lost', async () => {
+ const homeLink = link(2);
+ homeLink.handOver.mockRejectedValue(new Error('[INVOKE_TIMEOUT] no answer'));
+ const t = setup({ home: 'laptop', devices: [device('laptop')], homeLink });
+ expect((await t.runtime.switchHome('bot_mia', 'tablet')).ok).toBe(false);
+ expect(t.refresh).toHaveBeenCalled();
+ });
+});
+
describe('transcript', () => {
it('maps authors to roles and pages oldest-first', async () => {
const page = Array.from({ length: 100 }, (_, i) => ({ id: `m${i}`, seq: String(200 - i), authorId: i % 2 ? 'actor-1' : 'human',
@@ -523,3 +662,96 @@ describe('installation guard', () => {
expect(t.runtime.isShadowed('bot_mia')).toBe(false);
});
});
+
+describe('merging copies of Cindy', () => {
+ function mergeSetup(options: { sourceHome: string; flush?: ReturnType<typeof vi.fn>; turnActive?: () => boolean;
+ canonicalSession?: CompanionCloudHost['canonicalSession']; paused?: (botId: string) => boolean }) {
+ const order: string[] = [];
+ const flush = options.flush ?? vi.fn(async () => { order.push('flush'); return { ok: true as const }; });
+ const homeLink = { version: vi.fn(async () => 2), targets: vi.fn(async () => []), handOver: vi.fn(async () => ({ ok: true as const })), flush };
+ const t = setup({ home: 'desk', homeLink, ...(options.turnActive ? { turnActive: options.turnActive } : {}),
+ ...(options.canonicalSession ? { canonicalSession: options.canonicalSession } : {}),
+ ...(options.paused ? { paused: options.paused } : {}), handler: (route, method) => {
+ if (route === '/preferences') return method === 'GET' ? [{ key: 'companion.profile.v1', value: { ...MIA, templateId: 'cindy' }, revision: 1 }] : { revision: 1 };
+ if (route === '/conversations') return { id: ROOM };
+ if (route.includes('/messages?')) return [];
+ if (route.endsWith('/import')) return {};
+ if (method === 'PATCH') { order.push(`patch ${route}`); return {}; }
+ throw new Error(`unexpected ${method} ${route}`);
+ } });
+ t.actors.splice(0, t.actors.length,
+ { id: 'actor-keep', kind: 'bot', externalId: 'cindy-default', name: 'Cindy', avatar: null, homeDeviceId: 'desk' },
+ { id: 'actor-from', kind: 'bot', externalId: 'bot_lap', name: 'Cindy', avatar: null, homeDeviceId: options.sourceHome });
+ return { ...t, order, flush };
+ }
+
+ it('has the other copy\'s computer send what it has not sent yet before reading it, and retires it last', async () => {
+ const t = mergeSetup({ sourceHome: 'laptop' });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toMatchObject({ ok: true, merged: 1 });
+ expect(t.flush).toHaveBeenCalledWith('laptop', 'bot_lap');
+ // Once before reading it, once more right before retiring it.
+ expect(t.order).toEqual(['flush', 'flush', 'patch /actors/actor-from']);
+ });
+
+ it('does not merge while the other copy is still replying, and leaves it active', async () => {
+ const flush = vi.fn(async () => ({ ok: false as const, code: 'BUSY' }));
+ const t = mergeSetup({ sourceHome: 'laptop', flush });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toEqual({ ok: false, code: 'BUSY' });
+ expect(t.order).toEqual([]);
+ });
+
+ it('sends a copy homed here itself, and waits while it is busy', async () => {
+ let busy = true;
+ const t = mergeSetup({ sourceHome: 'desk', turnActive: () => busy });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toEqual({ ok: false, code: 'BUSY' });
+ busy = false;
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toMatchObject({ ok: true, merged: 1 });
+ expect(t.flush).not.toHaveBeenCalled();
+ });
+
+ it('leaves the copies active when the kept Cindy has no task here to take the conversation', async () => {
+ const t = mergeSetup({ sourceHome: 'laptop', canonicalSession: async () => null });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toMatchObject({ ok: false });
+ expect(t.order).toEqual(['flush']);
+ });
+
+ it('re-checks every copy right before retiring it, and stops when one got busy meanwhile', async () => {
+ let calls = 0;
+ const flush = vi.fn(async () => (++calls === 1 ? { ok: true as const } : { ok: false as const, code: 'BUSY' }));
+ const t = mergeSetup({ sourceHome: 'laptop', flush });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toEqual({ ok: false, code: 'BUSY' });
+ expect(flush).toHaveBeenCalledTimes(2);
+ expect(t.order.filter(step => step.startsWith('patch'))).toEqual([]);
+ });
+
+ it('does not count a copy as sent when a turn started during its flush', async () => {
+ let checks = 0;
+ // Idle when asked first, busy once the flush is done.
+ const t = mergeSetup({ sourceHome: 'desk', turnActive: () => ++checks > 1 });
+ expect(await t.runtime.flushHere('bot_lap')).toEqual({ ok: false, code: 'BUSY' });
+ });
+
+ it('stops the merge when a copy\'s main task cannot be told, instead of counting its history as sent', async () => {
+ const t = mergeSetup({ sourceHome: 'desk', canonicalSession: async (botId) => {
+ if (botId === 'bot_lap') throw new Error('COMPANION_TASK_CONFLICT');
+ return 'session-1';
+ } });
+ expect(await t.runtime.mergeCindy('cindy-default', ['bot_lap'])).toMatchObject({ ok: false });
+ expect(t.order.filter(step => step.startsWith('patch'))).toEqual([]);
+ });
+
+ it('asks to resume a paused copy, kept or merged, instead of failing part way', async () => {
+ const source = mergeSetup({ sourceHome: 'desk', paused: (botId) => botId === 'bot_lap' });
+ expect(await source.runtime.mergeCindy('cindy-default', ['bot_lap'])).toEqual({ ok: false, code: 'PAUSED' });
+ runtime?.dispose();
+ const kept = mergeSetup({ sourceHome: 'laptop', paused: (botId) => botId === 'cindy-default' });
+ expect(await kept.runtime.mergeCindy('cindy-default', ['bot_lap'])).toEqual({ ok: false, code: 'PAUSED' });
+ expect(kept.flush).not.toHaveBeenCalled();
+ });
+
+ it('answers a flush request only as the copy\'s home', async () => {
+ const t = mergeSetup({ sourceHome: 'laptop' });
+ expect(await t.runtime.flushHere('bot_lap')).toEqual({ ok: false, code: 'HOME_CONFLICT' });
+ expect(await t.runtime.flushHere('cindy-default')).toEqual({ ok: true });
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts
index 2d0bde46b8..45248330eb 100644
--- a/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts
+++ b/apps/desktop/src/main/companion-cloud/__tests__/materialize.test.ts
@@ -284,4 +284,99 @@ describe('materializeCompanion', () => {
local.setProfile({ status: 'deleting', displayName: 'Mia', description: '' });
await expect(materializeCompanion({ api, state: memoryState().state, host: local.host, actor, roomId: async () => ROOM })).rejects.toThrow('PROFILE_DELETING');
});
+
+ it('brings the room\'s files along with the history, and keeps a name for one that cannot come', async () => {
+ const withFiles = { ...roomMessage('m1', 1, 'human', 'look', 1_000), content: [{ type: 'text', text: 'look' },
+ { type: 'media', mediaId: 'media-1', caption: 'cat.png' }, { type: 'media', mediaId: 'media-2', caption: 'gone.pdf' }] };
+ const { api } = cloud([profilePref], [withFiles]);
+ const local = fakeLocal();
+ const { state } = memoryState();
+ const download = vi.fn(async (_room: string, mediaId: string) => {
+ if (mediaId === 'media-2') throw Object.assign(new Error('NOT_FOUND'), { status: 404 });
+ return { name: 'cat.png', category: 'image', mimeType: 'image/png', size: 3, url: 'cindy-media://blobs/x.png', path: null };
+ });
+ await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM, download });
+ expect(download).toHaveBeenCalledWith(ROOM, 'media-1');
+ expect(local.host.insertHistory).toHaveBeenCalledWith('session-1', expect.objectContaining({
+ text: 'look\n[附件: gone.pdf]', attachments: [expect.objectContaining({ url: 'cindy-media://blobs/x.png' })] }), expect.anything());
+ });
+
+ it('fails the take-over while a file may still come, and brings it on the retry', async () => {
+ const withFile = { ...roomMessage('m1', 1, 'human', 'look', 1_000), content: [{ type: 'text', text: 'look' },
+ { type: 'media', mediaId: 'media-1', caption: 'cat.png' }] };
+ const { api } = cloud([profilePref], [withFile]);
+ const local = fakeLocal();
+ const { state } = memoryState();
+ let online = false;
+ const download = vi.fn(async () => {
+ if (!online) throw new Error('MEDIA_DOWNLOAD_FAILED');
+ return { name: 'cat.png', category: 'image', mimeType: 'image/png', size: 3, url: 'cindy-media://blobs/x.png', path: null };
+ });
+ await expect(materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM, download })).rejects.toThrow('MEDIA_DOWNLOAD_FAILED');
+ expect(local.host.insertHistory).not.toHaveBeenCalled();
+ expect(state.bot('bot_mia')?.demoted).toBe(true);
+ online = true;
+ await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM, download });
+ expect(local.host.insertHistory).toHaveBeenCalledWith('session-1', expect.objectContaining({
+ text: 'look', attachments: [expect.objectContaining({ url: 'cindy-media://blobs/x.png' })] }), expect.anything());
+ });
+
+ it('imports the whole room, in message-time order', async () => {
+ // The second page holds older history that arrived later (seq after the first page).
+ const page1 = Array.from({ length: 100 }, (_, i) => roomMessage(`n${i}`, 300 - i, 'human', `new ${i}`, 50_000 - i));
+ const page2 = [roomMessage('old', 100, 'human', 'oldest', 1_000)];
+ const { api } = fakeApi((route, method) => {
+ if (route === '/preferences' && method === 'GET') return [{ ...profilePref, revision: 1 }];
+ if (route.startsWith(`/conversations/${ROOM}/messages?`)) return route.includes('before=') ? page2 : page1;
+ throw new Error(`unexpected ${method} ${route}`);
+ });
+ const local = fakeLocal();
+ const { state } = memoryState();
+ const result = await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });
+ expect(result.inserted).toBe(101);
+ expect(local.rows[0]!.content).toBe('oldest');
+ });
+
+ it('brings todos, routines and the workbench along in one batch each; a routine tombstone removes it, a todo one keeps it', async () => {
+ const todo = { id: 'todo:1', title: 'Compare quotes', history: [] };
+ const routine = { id: 'routine-1', input: { name: 'Daily', prompt: 'p', enabled: true, triggers: [] }, originDeviceId: 'laptop' };
+ const workbench = { directories: [{ path: '/projects/game', addedAt: 'x', deviceId: 'laptop' }], tasks: {} };
+ const { api } = cloud([profilePref, { key: 'companion.todo.v1:todo:1', value: todo }, { key: 'companion.todo.v1:todo:gone', value: null },
+ { key: 'companion.routine.v1:routine-1', value: routine }, { key: 'companion.routine.v1:routine-gone', value: null },
+ { key: 'companion.workbench.v1', value: workbench }]);
+ const applyTodos = vi.fn(async () => undefined);
+ const applyRoutines = vi.fn(async () => undefined);
+ const applyWorkbench = vi.fn(async () => undefined);
+ const local = fakeLocal({ applyTodos, applyRoutines, applyWorkbench });
+ const { state } = memoryState();
+ await materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM });
+ // A todo tombstone only means it left the travelling window: this computer keeps its copy.
+ expect(applyTodos).toHaveBeenCalledWith('bot_mia', [todo], [], expect.anything());
+ expect(applyRoutines).toHaveBeenCalledWith('bot_mia', [routine], ['routine-gone'], expect.anything());
+ expect(applyWorkbench).toHaveBeenCalledWith('bot_mia', workbench, expect.anything(), { replace: false });
+ // Applied keys may be tombstoned later by this computer.
+ expect(state.bot('bot_mia')?.prefs['companion.todo.v1:todo:1']?.local).toBe(true);
+ });
+
+ it('lets the cloud workbench replace one this computer synced before, a tombstone included; an unsynced one joins', async () => {
+ const { api } = cloud([profilePref, { key: 'companion.workbench.v1', value: null }]);
+ const applyWorkbench = vi.fn(async () => undefined);
+ const synced = memoryState();
+ synced.state.update('bot_mia', actor.id, entry => { entry.prefs['companion.workbench.v1'] = { hash: 'old', revision: 2, local: true }; });
+ await materializeCompanion({ api, state: synced.state, host: fakeLocal({ applyWorkbench }).host, actor, roomId: async () => ROOM });
+ expect(applyWorkbench).toHaveBeenCalledWith('bot_mia', null, expect.anything(), { replace: true });
+ expect(synced.state.bot('bot_mia')?.prefs['companion.workbench.v1']?.hash).not.toBe('old');
+ applyWorkbench.mockClear();
+ await materializeCompanion({ api, state: memoryState().state, host: fakeLocal({ applyWorkbench }).host, actor, roomId: async () => ROOM });
+ expect(applyWorkbench).not.toHaveBeenCalled();
+ });
+
+ it('stays demoted and retries when the routines cannot be restored', async () => {
+ const { api } = cloud([profilePref, { key: 'companion.routine.v1:r', value: { id: 'r', input: { triggers: [] } } }]);
+ const local = fakeLocal({ applyRoutines: vi.fn(async () => { throw new Error('ROUTINES_UNAVAILABLE'); }) });
+ const { state } = memoryState();
+ await expect(materializeCompanion({ api, state, host: local.host, actor, roomId: async () => ROOM })).rejects.toThrow('RESTORE_INCOMPLETE');
+ expect(state.bot('bot_mia')?.demoted).toBe(true);
+ });
});
+
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/merge.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/merge.test.ts
new file mode 100644
index 0000000000..fc836fead2
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/__tests__/merge.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it, vi } from 'vitest';
+import { CINDY_DEFAULT_IDENTITY } from '../../../shared/botTemplatePreset.js';
+import { isCindyCompanion, mergeCompanionsInto, mergedRoutineId, mergedTodoId, renamedEntry } from '../merge.js';
+import { fakeApi, fakeLocal } from './fakes.js';
+
+const KEEP_ROOM = '10000000-0000-4000-8000-00000000000a';
+const FROM_ROOM = '10000000-0000-4000-8000-00000000000b';
+const keep = { id: 'actor-keep', externalId: 'cindy-default', name: 'Cindy', homeDeviceId: 'desk' };
+const from = { id: 'actor-from', externalId: 'bot_laptop_cindy', name: 'Cindy', homeDeviceId: 'laptop', label: 'MacBook Pro' };
+
+describe('telling the copies of Cindy apart', () => {
+ it('goes by the preset, never by name', () => {
+ expect(isCindyCompanion('cindy-default', null)).toBe(true);
+ expect(isCindyCompanion('bot_1', { templateId: 'cindy' })).toBe(true);
+ expect(isCindyCompanion('bot_1', { soul: CINDY_DEFAULT_IDENTITY })).toBe(true);
+ expect(isCindyCompanion('bot_1', { name: 'Cindy', soul: 'my own' })).toBe(false);
+ });
+
+ it('names a second copy after where it came from', () => {
+ expect(renamedEntry('user_tea.md', 'MacBook Pro')).toBe('user_tea-macbook-pro.md');
+ expect(renamedEntry('brew', '工作')).toBe('brew-merged');
+ });
+});
+
+describe('merging copies of Cindy', () => {
+ function setup() {
+ const imports: Array<{ room: string; messages: Array<{ sourceId: string; authorId: string; createdAt: string; content: unknown[] }> }> = [];
+ const added: Array<{ key: string; value: unknown; revision: number }> = [];
+ const files: Array<{ type: string; mediaId: string; caption: string }> = [];
+ const { api, calls } = fakeApi((route, method, data, actorId) => {
+ if (route === '/preferences' && method === 'GET' && actorId === 'actor-from') return [...added,
+ { key: 'companion.profile.v1', value: { name: 'Cindy', soul: 'theirs' }, revision: 1 },
+ { key: 'companion.memory.v1:user_tea.md', value: { filename: 'user_tea.md', content: 'likes green tea' }, revision: 2 },
+ { key: 'companion.memory.v1:user_new.md', value: { filename: 'user_new.md', content: 'only there' }, revision: 3 },
+ { key: 'companion.memory.v1:user_same.md', value: { filename: 'user_same.md', content: 'same' }, revision: 4 },
+ { key: 'companion.memory.v1:user_gone.md', value: null, revision: 5 },
+ { key: 'companion.todo.v1:todo:1', value: { id: 'todo:1', title: 'x', history: [] }, revision: 6 },
+ { key: 'companion.routine.v1:routine-1', value: { id: 'routine-1', input: { triggers: [] }, originDeviceId: 'laptop' }, revision: 7 },
+ ];
+ if (route.startsWith(`/conversations/${FROM_ROOM}/messages?`)) return [
+ { id: 'm2', seq: '2', authorId: 'actor-from', createdAt: new Date(2_000).toISOString(), content: [{ type: 'text', text: 'hello back' }] },
+ { id: 'm1', seq: '1', authorId: 'human', createdAt: new Date(1_000).toISOString(), content: [{ type: 'text', text: 'hi' }, ...files] },
+ ];
+ if (route.endsWith('/import')) { imports.push({ room: route.split('/')[2]!, messages: (data as { messages: never[] }).messages }); return {}; }
+ if (method === 'PATCH') return {};
+ throw new Error(`unexpected ${method} ${route}`);
+ });
+ const local = fakeLocal({ applyTodos: vi.fn(async () => undefined), applyRoutines: vi.fn(async () => undefined) });
+ local.memories.set('user_tea.md', 'likes black tea');
+ local.memories.set('user_same.md', 'same');
+ const importHistory = vi.fn<() => Promise<void>>(async () => undefined);
+ const run = () => mergeCompanionsInto({ api, host: local.host, keep, from: [from], humanActorId: 'human',
+ roomOf: async (actor) => (actor.id === keep.id ? KEEP_ROOM : FROM_ROOM), importHistory, fence: { assertCurrent: () => undefined } });
+ const addPreference = (n: number) => { added.push({ key: `companion.memory.v1:late-${n}.md`, value: { content: 'late' }, revision: Math.max(1, 100 + n) }); };
+ const withAttachment = () => { files.push({ type: 'media', mediaId: 'media-1', caption: 'cat.png' }); };
+ return { run, api, local, calls, imports, importHistory, addPreference, withAttachment };
+ }
+
+ it('brings memories, todos and the conversation over, keeping a different same-name memory as a copy', async () => {
+ const t = setup();
+ const summary = await t.run();
+ expect(t.local.memories.get('user_tea.md')).toBe('likes black tea');
+ expect(t.local.memories.get('user_tea-macbook-pro.md')).toBe('likes green tea');
+ expect(t.local.memories.get('user_new.md')).toBe('only there');
+ expect(summary).toMatchObject({ merged: 1, messages: 2, memories: 2, renamed: ['user_tea-macbook-pro.md'] });
+ expect(t.local.host.applyTodos).toHaveBeenCalledWith('cindy-default', [{ id: mergedTodoId('cindy-default', 'actor-from', 'todo:1'), title: 'x', history: [] }], [], expect.anything());
+ // In message-time order, authored by the kept companion, with the original times.
+ expect(t.imports[0]!.room).toBe(KEEP_ROOM);
+ expect(t.imports[0]!.messages.map(m => [m.authorId, m.createdAt])).toEqual([['human', new Date(1_000).toISOString()], ['actor-keep', new Date(2_000).toISOString()]]);
+ expect(t.calls.find(call => call.method === 'PATCH')).toMatchObject({ route: '/actors/actor-from', data: { disabled: true } });
+ expect(t.importHistory).toHaveBeenCalledOnce();
+ });
+
+ it('can run again without duplicating anything', async () => {
+ const t = setup();
+ await t.run();
+ const second = await t.run();
+ expect(second.memories).toBe(0);
+ expect(second.renamed).toEqual([]);
+ // The same batch: the server dedupes by operation and source id.
+ expect(t.imports[1]!.messages.map(m => m.sourceId)).toEqual(t.imports[0]!.messages.map(m => m.sourceId));
+ });
+
+ it('retires the copies only after the history is in, so a failed merge can run again', async () => {
+ const t = setup();
+ t.importHistory.mockRejectedValueOnce(new Error('OFFLINE'));
+ await expect(t.run()).rejects.toThrow('OFFLINE');
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ const summary = await t.run();
+ expect(summary.merged).toBe(1);
+ expect(t.calls.filter(call => call.method === 'PATCH')).toHaveLength(1);
+ });
+
+ it('never overwrites a renamed copy that holds something else', async () => {
+ const t = setup();
+ t.local.memories.set('user_tea-macbook-pro.md', 'likes oolong');
+ const summary = await t.run();
+ expect(t.local.memories.get('user_tea-macbook-pro.md')).toBe('likes oolong');
+ expect(t.local.memories.get('user_tea-macbook-pro-2.md')).toBe('likes green tea');
+ expect(summary.renamed).toEqual(['user_tea-macbook-pro-2.md']);
+ expect((await t.run()).renamed).toEqual([]);
+ });
+
+ it('gives merged routines ids of their own in the kept Cindy', async () => {
+ const t = setup();
+ await t.run();
+ const id = mergedRoutineId('cindy-default', 'actor-from', 'routine-1');
+ expect(id).toMatch(/^[a-zA-Z0-9_-]{16,128}$/);
+ expect(id).not.toBe(mergedRoutineId('bot_other', 'actor-from', 'routine-1'));
+ // Two copies holding the same id (e.g. a todo from the same old workbench entry) never collide.
+ expect(mergedTodoId('cindy-default', 'actor-a', 'todo:legacy-x')).not.toBe(mergedTodoId('cindy-default', 'actor-b', 'todo:legacy-x'));
+ expect(mergedTodoId('cindy-default', 'actor-a', 'todo:legacy-x')).toMatch(/^todo:/);
+ expect(t.local.host.applyRoutines).toHaveBeenCalledWith('cindy-default',
+ [{ id, input: { triggers: [] }, originDeviceId: 'laptop' }], [], expect.anything());
+ });
+
+ it('stops with the copies active when one added something after it was read', async () => {
+ const t = setup();
+ let extra = 0;
+ const run = () => mergeCompanionsInto({ api: t.api, host: t.local.host, keep, from: [from], humanActorId: 'human',
+ roomOf: async (actor) => (actor.id === keep.id ? KEEP_ROOM : FROM_ROOM), importHistory: t.importHistory,
+ fence: { assertCurrent: () => undefined }, beforeRetire: async () => { extra += 1; t.addPreference(extra); } });
+ await expect(run()).rejects.toThrow('COMPANION_STILL_CHANGING');
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ });
+
+ it('notices a copy that changed a preference without raising the newest revision', async () => {
+ const t = setup();
+ // Revisions count per key: a new memory at revision 1 leaves the highest revision (7) as it was.
+ const run = () => mergeCompanionsInto({ api: t.api, host: t.local.host, keep, from: [from], humanActorId: 'human',
+ roomOf: async (actor) => (actor.id === keep.id ? KEEP_ROOM : FROM_ROOM), importHistory: t.importHistory,
+ fence: { assertCurrent: () => undefined }, beforeRetire: async () => { t.addPreference(-99); } });
+ await expect(run()).rejects.toThrow('COMPANION_STILL_CHANGING');
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ });
+
+ it('fails with the copies active while a file of the conversation may still come', async () => {
+ const t = setup();
+ const media = { upload: vi.fn(), download: vi.fn(async () => { throw new Error('MEDIA_DOWNLOAD_FAILED'); }) };
+ t.withAttachment();
+ await expect(mergeCompanionsInto({ api: t.api, host: t.local.host, keep, from: [from], humanActorId: 'human', media,
+ roomOf: async (actor) => (actor.id === keep.id ? KEEP_ROOM : FROM_ROOM), importHistory: t.importHistory,
+ fence: { assertCurrent: () => undefined } })).rejects.toThrow('MEDIA_DOWNLOAD_FAILED');
+ expect(t.calls.some(call => call.method === 'PATCH')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts
index 1350e118bf..4bd925a354 100644
--- a/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts
+++ b/apps/desktop/src/main/companion-cloud/__tests__/mirror.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { UI_ACTION_TRIGGER_PREFIX } from '../../../shared/interruptedTurn.js';
import { createCompanionMirror, mirrorMessageText, splitMirrorText, type CompanionMirrorCursor, type CompanionMirrorRow } from '../mirror.js';
import { fakeApi, memoryState, rejection } from './fakes.js';
@@ -19,10 +19,8 @@ describe('mirrorMessageText', () => {
.toBe('look\n[附件: cat.png]\n[附件: a.pdf]');
expect(mirrorMessageText(reply('hello'))).toBe('hello');
});
- it('keeps an attachment-only message as placeholders, but not one from another source', () => {
+ it('keeps an attachment-only message as placeholders', () => {
expect(mirrorMessageText(row('user', { text: '', images: [{ url: 'x', originalName: 'cat.png' }], files: [] }))).toBe('[附件: cat.png]');
- expect(mirrorMessageText(row('user', { text: '', images: [{ url: 'x' }], files: [] },
- { agentMeta: JSON.stringify({ imSource: { channel: 'feishu' } }) }))).toBeNull();
});
it.each([
['tool rows', row('tool_use', { name: 'Bash' })],
@@ -31,23 +29,39 @@ describe('mirrorMessageText', () => {
['messages that came from the room', user('hi', { clientId: 'chat-direct:exec-1' })],
['imported cloud history', reply('old', { clientId: 'cloud-history:abc' })],
['empty text', reply(' ')],
+ ['automatic continuations', user('继续', { agentMeta: JSON.stringify({ autoResume: true }) })],
+ ['coordination between teammates', user('hand off', { agentMeta: JSON.stringify({ botTaskCoordination: { kind: 'x' } }) })],
+ ['a delegated continuation', user('continue', { agentMeta: JSON.stringify({ autoReviewUserText: { kind: 'delegated-continuation' } }) })],
['private coordination replies', reply('internal', { agentMeta: JSON.stringify({ botPrivateReply: true }) })],
['progress commentary', reply('checking files', { agentMeta: JSON.stringify({ assistantPhase: 'commentary' }) })],
['sub-agent output', reply('sub result', { agentMeta: JSON.stringify({ parentToolUseId: 'toolu_1' }) })],
['sub-agent output (snake case)', reply('sub result', { agentMeta: JSON.stringify({ parent_tool_use_id: 'toolu_1' }) })],
['Claude sub-agent output (parentUuid)', reply('sub result', { agentMeta: JSON.stringify({ parentUuid: 'toolu_subagent' }) })],
- ['input sent by another task or teammate', user('do this', { agentMeta: JSON.stringify({ origin: { kind: 'session', senderSessionId: 's' } }) })],
- ['input from an automation', user('scheduled', { agentMeta: JSON.stringify({ origin: { kind: 'scheduler', scheduleId: 'r' } }) })],
- ['input from a plugin', user('plugin says', { agentMeta: JSON.stringify({ sourcePlugin: { pluginId: 'p' } }) })],
- ['input from an IM channel', user('from feishu', { agentMeta: JSON.stringify({ imSource: { channel: 'feishu' } }) })],
- ['input from a shared-task member', user('guest', { agentMeta: JSON.stringify({ sharedTaskAuthor: { memberId: 'm' } }) })],
- ['a group-sourced message', user('group', { agentMeta: JSON.stringify({ sourceGroup: { groupId: 'g' } }) })],
])('drops %s', (_name, value) => {
expect(mirrorMessageText(value)).toBeNull();
});
});
describe('owner-typed input', () => {
+ it('keeps what the owner typed, which the host marks for the auto reviewer', () => {
+ // Regression: this marker means "the owner said this"; treating it as another source dropped
+ // nearly every message the owner sent.
+ expect(mirrorMessageText(user('发送', { agentMeta: JSON.stringify({ autoReviewUserText: '发送',
+ sourceDevice: { deviceId: 'phone', platform: 'mobile' } }) }))).toBe('发送');
+ });
+
+ it('keeps visible input from other sources, labelled as the chat labels it', () => {
+ const labelled = (meta: unknown, text = 'hi') => mirrorMessageText(user(text, { agentMeta: JSON.stringify(meta) }));
+ expect(labelled({ origin: { kind: 'session', senderSessionId: 's', senderSessionTitle: '整理' } })).toBe('〔来自任务「整理」〕\nhi');
+ expect(labelled({ origin: { kind: 'session', senderSessionId: 's', senderBotId: 'b', senderBotName: 'Mia' } })).toBe('〔来自伙伴「Mia」〕\nhi');
+ expect(labelled({ origin: { kind: 'scheduler', scheduleId: 'r' } })).toBe('〔来自定时任务〕\nhi');
+ expect(labelled({ sourcePlugin: { pluginId: 'p', name: 'Art' } })).toBe('〔来自插件「Art」〕\nhi');
+ expect(labelled({ sharedTaskAuthor: { memberId: 'm', displayName: 'Ann' } })).toBe('〔来自共享任务成员「Ann」〕\nhi');
+ expect(labelled({ sourceGroup: { groupId: 'g' } })).toBe('〔来自群聊〕\nhi');
+ // IM: the person's own words, without the context the host wrapped around them.
+ expect(labelled({ imSource: { im: 'feishu', userText: '取消订单' } }, '<group_chat_context>…</group_chat_context>\n取消订单')).toBe('〔来自飞书〕\n取消订单');
+ });
+
it('keeps what the owner typed on another device', () => {
expect(mirrorMessageText(user('from my phone', { agentMeta: JSON.stringify({ sourceDevice: { deviceId: 'phone', platform: 'mobile' } }) })))
.toBe('from my phone');
@@ -67,7 +81,7 @@ describe('splitMirrorText', () => {
});
});
-function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolean) {
+function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolean, uploadMedia?: Parameters<typeof createCompanionMirror>[0]['uploadMedia']) {
let imports = 0;
const { api, calls } = fakeApi((route, method) => {
if (route === '/conversations' && method === 'POST') return { id: ROOM };
@@ -87,9 +101,10 @@ function setup(rows: CompanionMirrorRow[], failImport?: (call: number) => boolea
rowsAfter: async (_sessionId, cursor, limit) => rows.filter(after(cursor))
.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 } : {}),
});
const imported = () => calls.filter(call => call.route.endsWith('/import'))
- .map(call => (call.data as { messages: Array<{ sourceId: string; authorId: string; content: Array<{ text: string }> }> }).messages);
+ .map(call => (call.data as { messages: Array<{ sourceId: string; authorId: string; content: Array<{ type?: string; text: string; mediaId?: string }> }> }).messages);
return { mirror, state, calls, imported, rows };
}
@@ -122,6 +137,81 @@ describe('companion conversation mirror', () => {
expect(batches.flat().at(-1)!.content[0]!.text).toBe('r259');
});
+ it('sends the owner\'s files themselves when they upload, and only their names otherwise', async () => {
+ const withFiles = user('look');
+ withFiles.content = JSON.stringify({ text: 'look', images: [{ url: 'cindy-media://blobs/a.png', mimeType: 'image/png', originalName: 'cat.png', size: 3 }],
+ files: [{ name: 'a.pdf', path: '/tmp/a.pdf' }] });
+ const upload = vi.fn(async (_room: string, _source: string, files: Array<{ name: string }>) =>
+ [{ type: 'media', mediaId: files[0]!.name === 'cat.png' ? 'm-1' : 'm-2', caption: files[0]!.name }]);
+ const t = setup([withFiles], undefined, upload);
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(upload).toHaveBeenCalledWith(ROOM, expect.stringContaining(withFiles.id),
+ [expect.objectContaining({ category: 'image', url: 'cindy-media://blobs/a.png', name: 'cat.png' })], 'human');
+ expect(upload).toHaveBeenCalledWith(ROOM, expect.stringContaining(withFiles.id),
+ [expect.objectContaining({ category: 'file', path: '/tmp/a.pdf', name: 'a.pdf' })], 'human');
+ expect(t.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'look' },
+ { type: 'media', mediaId: 'm-1', caption: 'cat.png' }, { type: 'media', mediaId: 'm-2', caption: 'a.pdf' }]);
+
+ // One file fails: it keeps its name, the other still goes up.
+ const partial = setup([withFiles], undefined, vi.fn(async (_room: string, _source: string, files: Array<{ name: string }>) => {
+ if (files[0]!.name === 'a.pdf') throw new Error('ATTACHMENT_UNAVAILABLE');
+ return [{ type: 'media', mediaId: 'm-1', caption: 'cat.png' }];
+ }));
+ await partial.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(partial.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'look\n[附件: a.pdf]' }, { type: 'media', mediaId: 'm-1', caption: 'cat.png' }]);
+
+ const failing = setup([withFiles], undefined, vi.fn(async () => { throw new Error('ATTACHMENT_UNAVAILABLE'); }));
+ await failing.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(failing.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'look\n[附件: cat.png]\n[附件: a.pdf]' }]);
+ });
+
+ it('stops the pass while a file may still go up, and sends it with its message on the retry', async () => {
+ const withFile = user('look');
+ withFile.content = JSON.stringify({ text: 'look', files: [{ name: 'a.pdf', path: '/tmp/a.pdf' }] });
+ let online = false;
+ const upload = vi.fn(async () => {
+ if (!online) throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 });
+ return [{ type: 'media', mediaId: 'm-2', caption: 'a.pdf' }];
+ });
+ const t = setup([withFile], undefined, upload);
+ await expect(t.mirror.syncBot('bot', 'actor', 'Mia')).rejects.toThrow('MEDIA_UPLOAD_FAILED');
+ expect(t.imported()).toEqual([]);
+ online = true;
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(t.imported()[0]![0]!.content).toEqual([{ type: 'text', text: 'look' }, { type: 'media', mediaId: 'm-2', caption: 'a.pdf' }]);
+ });
+
+ 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);
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ const first = t.imported().length;
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ const older = t.imported().slice(first).flat().map(message => message.content[0]!.text);
+ expect(older).toEqual(Array.from({ length: 60 }, (_, i) => (i % 2 ? `r${i}` : `u${i}`)));
+ expect(t.state.bot('bot')?.backfill?.done).toBe(true);
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(t.imported().length).toBe(first + 2);
+ });
+
+ it('uploads the older history in the same pass when the first sync is a hand-over', async () => {
+ const rows = Array.from({ length: 260 }, (_, i) => (i % 2 ? reply(`r${i}`) : user(`u${i}`)));
+ const t = setup(rows);
+ await t.mirror.syncBot('bot', 'actor', 'Mia', { drain: true });
+ const texts = t.imported().flat().map(message => message.content[0]!.text);
+ expect(new Set(texts).size).toBe(260);
+ expect(t.state.bot('bot')?.backfill?.done).toBe(true);
+ });
+
+ it('uploads history from before the mirror started, also when the cursor came from a take-over', async () => {
+ const old = [user('before'), reply('long ago')];
+ const t = setup([...old]);
+ // Take-over: mirroring continues after the newest own row; older rows are still history.
+ t.state.update('bot', 'actor', entry => { entry.mirror = { sessionId: 'session-1', createdAt: old[1]!.createdAt, id: old[1]!.id }; });
+ await t.mirror.syncBot('bot', 'actor', 'Mia');
+ expect(t.imported().flat().map(message => message.content[0]!.text)).toEqual(['before', 'long ago']);
+ });
+
it('advances the cursor only past successfully imported batches', async () => {
const rows = Array.from({ length: 120 }, (_, i) => user(`u${i}`));
const t = setup([], call => call === 2);
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/room.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/room.test.ts
new file mode 100644
index 0000000000..ccbf659c7b
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/__tests__/room.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { ROOM_HISTORY_MAX_PAGES, readAllRoomMessages, transcriptPageOf } from '../room.js';
+import type { CompanionTranscriptMessage } from '../../../shared/companionCloud.js';
+import { fakeApi } from './fakes.js';
+
+const message = (seq: number, createdAt: number, author = 'human') => ({
+ id: `m${seq}`, seq: String(seq), authorId: author, createdAt: new Date(createdAt).toISOString(), content: [{ type: 'text', text: `t${seq}` }],
+});
+
+describe('reading the whole room', () => {
+ it('pages through every message and orders by message time, not arrival', async () => {
+ // Seq 101..200 arrived later but are older history (uploaded by a backfill).
+ const room = [...Array.from({ length: 100 }, (_, i) => message(i + 1, 10_000 + i)),
+ ...Array.from({ length: 100 }, (_, i) => message(i + 101, 1_000 + i, 'bot'))];
+ const { api } = fakeApi((route) => {
+ const before = /before=(\d+)/.exec(route)?.[1];
+ const older = room.filter(m => !before || BigInt(m.seq) < BigInt(before)).reverse();
+ return older.slice(0, 100);
+ });
+ const all = await readAllRoomMessages(api, 'room', 'bot');
+ expect(all).toHaveLength(200);
+ expect(all[0]!.text).toBe('t101');
+ expect(all.at(-1)!.text).toBe('t100');
+ expect(all[0]!.role).toBe('assistant');
+ });
+});
+
+describe('reading the whole room for a take-over or a merge', () => {
+ const pages = (count: number) => fakeApi((route) => {
+ // `count` full pages, newest first; seq counts down from count * 100.
+ const before = Number(/before=(\d+)/.exec(route)?.[1] ?? count * 100 + 1);
+ const top = before - 1;
+ if (top < 1) return [];
+ return Array.from({ length: Math.min(100, top) }, (_, i) => message(top - i, top - i));
+ });
+
+ it('reads past the view limit to the first message instead of stopping part way', async () => {
+ const { api } = pages(ROOM_HISTORY_MAX_PAGES + 2);
+ expect(await readAllRoomMessages(api, 'room', 'bot')).toHaveLength(ROOM_HISTORY_MAX_PAGES * 100);
+ expect(await readAllRoomMessages(api, 'room', 'bot', { complete: true })).toHaveLength((ROOM_HISTORY_MAX_PAGES + 2) * 100);
+ });
+
+ it('fails instead of reading forever when the cursor does not move', async () => {
+ const stuck = Array.from({ length: 100 }, (_, i) => message(500 - i, 500 - i));
+ const { api } = fakeApi(() => stuck);
+ await expect(readAllRoomMessages(api, 'room', 'bot', { complete: true })).rejects.toThrow('ROOM_HISTORY_STALLED');
+ });
+});
+
+describe('transcript pages', () => {
+ const at = (createdAt: number, n: number): CompanionTranscriptMessage => ({ id: `x${n}`, seq: String(n), role: 'user', text: `${n}`, createdAt });
+
+ it('returns the latest page and a cursor for older messages, keeping equal times together', () => {
+ // 102 messages; the 100-message boundary falls between two that share a time: both stay.
+ const messages = Array.from({ length: 102 }, (_, i) => at(i === 2 ? 1 : i, i));
+ const first = transcriptPageOf(messages);
+ expect(first.messages).toHaveLength(101);
+ expect(first.messages[0]!.text).toBe('1');
+ expect(first.nextBefore).toBe('1');
+ expect(transcriptPageOf(messages, 1).messages.map(m => m.text)).toEqual(['0']);
+ const short = transcriptPageOf(Array.from({ length: 150 }, (_, i) => at(i + 1, i + 1)));
+ expect(short.messages).toHaveLength(100);
+ expect(short.nextBefore).toBe('51');
+ expect(transcriptPageOf(Array.from({ length: 150 }, (_, i) => at(i + 1, i + 1)), 51).messages.map(m => m.text).at(-1)).toBe('50');
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/travellingTodos.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/travellingTodos.test.ts
new file mode 100644
index 0000000000..10208e758d
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/__tests__/travellingTodos.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { portableTodo, travellingTodos } from '../travel.js';
+
+const day = 24 * 60 * 60_000;
+const todo = (id: string, status: 'open' | 'done', updatedAt: number, extra: Record<string, unknown> = {}) => ({
+ id, revision: 1, key: id, origin: 'assigned', title: id, progress: '', outcome: '', value: '', next: null, sources: [], associations: [],
+ status, createdAt: new Date(0).toISOString(), updatedAt: new Date(updatedAt).toISOString(), sourceDeadline: null, deadlineCandidate: null,
+ suggestedDate: null, decision: null, history: Array.from({ length: 30 }, (_, i) => ({ summary: `h${i}`, at: 'x' })),
+ action: { requestId: 'req', revision: 1, state: 'received' }, legacyId: 'old', ...extra,
+}) as never;
+
+describe('todos that travel with a companion', () => {
+ it('takes open, later and recently closed todos, newest first', () => {
+ const now = 100 * day;
+ const items = [todo('todo:old-done', 'done', now - 40 * day), todo('todo:open', 'open', now - 90 * day),
+ todo('todo:recent-done', 'done', now - day), todo('todo:later', 'done', now - 60 * day, { decision: { kind: 'later' } })];
+ expect(travellingTodos(items, now).map((item: { id: string }) => item.id)).toEqual(['todo:recent-done', 'todo:later', 'todo:open']);
+ });
+
+ it('leaves the delivery in flight and old history behind', () => {
+ const value = portableTodo(todo('todo:a', 'open', 0));
+ expect(value.action).toBeNull();
+ expect(value.legacyId).toBeUndefined();
+ expect((value.history as unknown[]).length).toBe(20);
+ });
+});
diff --git a/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts
index 876bce7055..c1813c1657 100644
--- a/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts
+++ b/apps/desktop/src/main/companion-cloud/__tests__/uploader.test.ts
@@ -107,6 +107,28 @@ describe('companion profile uploader', () => {
expect(t.rows.get('companion.memory.v1:a.md')?.value).toEqual({ filename: 'a.md', content: 'new home' });
});
+ it('leaves a part that could not be read untouched in the cloud, and refuses a hand-over', async () => {
+ const t = setup();
+ const routine = { key: 'companion.routine.v1:r1', value: { id: 'r1' } };
+ t.setValues([profile('soul'), routine]);
+ await t.uploader.syncBot('bot', 'actor');
+ // The routine engine is not ready this time: the profile still goes up, the routine is not tombstoned.
+ t.setValues([profile('soul v2'), { key: 'companion.routine.v1:', value: null, unread: true }]);
+ await t.uploader.syncBot('bot', 'actor');
+ expect(t.writes().map(w => [w.key, w.value === null])).toEqual([
+ ['companion.profile.v1', false], ['companion.routine.v1:r1', false], ['companion.profile.v1', false]]);
+ await expect(t.uploader.syncBot('bot', 'actor', Number.POSITIVE_INFINITY, { requireAll: true })).rejects.toThrow('COMPANION_READ_INCOMPLETE');
+ });
+
+ it('clears a todo that left the travelling window from the cloud', async () => {
+ const t = setup();
+ t.setValues([profile('soul'), { key: 'companion.todo.v1:todo:1', value: { id: 'todo:1' } }]);
+ await t.uploader.syncBot('bot', 'actor');
+ t.setValues([profile('soul')]);
+ await t.uploader.syncBot('bot', 'actor');
+ expect(t.writes().filter(w => w.key === 'companion.todo.v1:todo:1').map(w => w.value)).toEqual([{ id: 'todo:1' }, null]);
+ });
+
it('spreads a large first upload over cycles', async () => {
const t = setup();
t.setValues(Array.from({ length: 45 }, (_, i) => memory(`m${i}.md`, `v${i}`)));
diff --git a/apps/desktop/src/main/companion-cloud/avatarCache.ts b/apps/desktop/src/main/companion-cloud/avatarCache.ts
new file mode 100644
index 0000000000..de99ee70ae
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/avatarCache.ts
@@ -0,0 +1,108 @@
+/**
+ * Local copy of companion avatars that live elsewhere (cloud-companions.md §2): the avatar of a
+ * companion on another computer (`cindy-media://blobs/…` there) and a cloud actor's public image
+ * (`https://…`). Shown from this computer first, so an offline main computer or a restart never
+ * turns a known avatar back into an initial.
+ *
+ * Bytes go into the media store as a regenerable cache (media-storage-and-protocols.md: the
+ * integration-cache index, `isCache`, recycled by the store's size limit). Both sources are
+ * immutable per address — a blob address is its content hash and a new cloud avatar gets a new
+ * address — so a hit never needs revalidation.
+ */
+import { BOT_AVATAR_MAX_BYTES, isManagedBotAvatarUrl } from '../../shared/botAvatarValue.js';
+
+export const COMPANION_AVATAR_CACHE = 'companion-avatar';
+
+/**
+ * The account's media store, captured when a lookup starts: a download that finishes after the
+ * account changed is never written into the next one (`put` throws instead).
+ */
+export interface CompanionAvatarScope {
+ /** Identifies the account; in-flight downloads and retry pauses are kept per account. */
+ key: string;
+ get: (cacheKey: string) => Promise<string | null>;
+ put: (cacheKey: string, bytes: Uint8Array, mimeType: string) => Promise<string>;
+}
+
+export interface CompanionAvatarCacheDeps {
+ /** Local blob address when this store already holds that content (any source). */
+ localBlob: (url: string) => Promise<string | null>;
+ scope: () => CompanionAvatarScope;
+ /** Image bytes of another computer's media (device-link), bounded. */
+ fetchFromDevice: (deviceId: string, url: string) => Promise<{ buffer: Uint8Array; mimeType?: string }>;
+ /** Public image bytes through the guarded download (no private networks), bounded. */
+ fetchPublic: (url: string) => Promise<{ buffer: Uint8Array; mimeType?: string }>;
+ /** Image MIME from the bytes themselves; null when they are not a supported image. */
+ sniff: (bytes: Uint8Array) => string | null;
+ now?: () => number;
+}
+
+export interface CompanionAvatarRequest {
+ avatar: string;
+ /** The computer that holds a `cindy-media://` avatar. */
+ deviceId?: string | null;
+ /** Download and keep it when it is not cached yet (otherwise only look). */
+ fetch?: boolean;
+}
+
+const FAILURE_BACKOFF_MS = 60_000;
+const BLOB_RE = /^cindy-media:\/\/blobs\/([0-9a-f]{64})\.[a-z0-9]+$/;
+
+/** Cache key of an avatar address, or null when it is not one this cache keeps. */
+export function companionAvatarKey(avatar: string, deviceId?: string | null): string | null {
+ if (avatar.startsWith('https://') && avatar.length <= 2048) return `${COMPANION_AVATAR_CACHE}:${avatar}`;
+ const blob = isManagedBotAvatarUrl(avatar) ? BLOB_RE.exec(avatar) : null;
+ return blob && deviceId ? `${COMPANION_AVATAR_CACHE}:blob:${blob[1]}` : null;
+}
+
+export function createCompanionAvatarCache(deps: CompanionAvatarCacheDeps) {
+ const now = deps.now ?? Date.now;
+ const inflight = new Map<string, Promise<string | null>>();
+ const failedUntil = new Map<string, number>();
+
+ async function lookup(scope: CompanionAvatarScope, request: CompanionAvatarRequest, key: string): Promise<string | null> {
+ // Same content already here (e.g. it was handed to this computer once): no copy needed.
+ if (!request.avatar.startsWith('https://')) {
+ const local = await deps.localBlob(request.avatar).catch(() => null);
+ if (local) return local;
+ }
+ return scope.get(key).catch(() => null);
+ }
+
+ async function download(scope: CompanionAvatarScope, request: CompanionAvatarRequest, key: string): Promise<string | null> {
+ const fetched = request.avatar.startsWith('https://')
+ ? await deps.fetchPublic(request.avatar)
+ : await deps.fetchFromDevice(request.deviceId!, request.avatar);
+ if (fetched.buffer.byteLength === 0 || fetched.buffer.byteLength > BOT_AVATAR_MAX_BYTES) return null;
+ // The sender's MIME is not trusted: only bytes that are an image are kept.
+ const mimeType = deps.sniff(fetched.buffer);
+ if (!mimeType?.startsWith('image/')) return null;
+ return scope.put(key, fetched.buffer, mimeType);
+ }
+
+ return {
+ /** Local address of the avatar, or null (not cached, not cacheable, or the download failed). */
+ async resolve(request: CompanionAvatarRequest): Promise<string | null> {
+ const key = companionAvatarKey(request.avatar, request.deviceId);
+ if (!key) return null;
+ const scope = deps.scope();
+ const hit = await lookup(scope, request, key);
+ if (hit || !request.fetch) return hit;
+ const slot = `${scope.key}\n${key}`;
+ if ((failedUntil.get(slot) ?? 0) > now()) return null;
+ const pending = inflight.get(slot);
+ if (pending) return pending;
+ const run = download(scope, request, key)
+ .catch(() => null)
+ .then((url) => {
+ if (url) failedUntil.delete(slot); else failedUntil.set(slot, now() + FAILURE_BACKOFF_MS);
+ return url;
+ })
+ .finally(() => { inflight.delete(slot); });
+ inflight.set(slot, run);
+ return run;
+ },
+ };
+}
+
+export type CompanionAvatarCache = ReturnType<typeof createCompanionAvatarCache>;
diff --git a/apps/desktop/src/main/companion-cloud/avatarCacheHost.ts b/apps/desktop/src/main/companion-cloud/avatarCacheHost.ts
new file mode 100644
index 0000000000..3706ff300b
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/avatarCacheHost.ts
@@ -0,0 +1,41 @@
+/** Production wiring of the companion avatar cache (media store, device-link, guarded download). */
+import { promises as fsp } from 'node:fs';
+
+import { BOT_AVATAR_MAX_BYTES } from '../../shared/botAvatarValue.js';
+import { rewriteToRemoteMediaOrigin } from '../../shared/remoteMediaUrl.js';
+import { resolveSafe } from '../cindy-media/blobStore.js';
+import { getActiveAppSession } from '../appSessionState.js';
+import { integrationCacheGet, integrationCachePut } from '../cindy-media/integrationCache.js';
+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+import { captureRemoteMediaOwner } from '../device-link/remoteMediaPersistentCache.js';
+import { fetchRemoteMediaImageBytes } from '../device-link/remoteMediaProtocol.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { fetchPublicImageBytes } from '../im/publicImageFetch.js';
+import { COMPANION_AVATAR_CACHE, createCompanionAvatarCache } from './avatarCache.js';
+
+const AVATAR_FETCH_TIMEOUT_MS = 15_000;
+
+export const companionAvatarCache = createCompanionAvatarCache({
+ localBlob: async (url) => {
+ // resolveSafe validates the address shape; the file must exist here.
+ await fsp.access(resolveSafe(url).absPath);
+ return url;
+ },
+ // The account and its database are captured before any download: late bytes never enter the next account.
+ scope: () => {
+ const session = getActiveAppSession();
+ const assertCurrent = captureRemoteMediaOwner();
+ const db = getDbClient().drizzle;
+ return {
+ key: `${session.mode}:${session.dataOwnerId ?? ''}`,
+ get: async (cacheKey) => { assertCurrent(); return (await integrationCacheGet(cacheKey, db))?.url ?? null; },
+ put: async (cacheKey, bytes, mimeType) => {
+ assertCurrent();
+ return (await integrationCachePut({ cacheKey, integration: COMPANION_AVATAR_CACHE, buffer: bytes, mimeType, assertStillValid: assertCurrent }, db)).url;
+ },
+ };
+ },
+ fetchFromDevice: (deviceId, url) => fetchRemoteMediaImageBytes(rewriteToRemoteMediaOrigin(url, { kind: 'device', deviceId })),
+ fetchPublic: (url) => fetchPublicImageBytes(url, BOT_AVATAR_MAX_BYTES, undefined, { timeoutMs: AVATAR_FETCH_TIMEOUT_MS }),
+ sniff: (bytes) => sniffMediaMime(bytes),
+});
diff --git a/apps/desktop/src/main/companion-cloud/host.ts b/apps/desktop/src/main/companion-cloud/host.ts
index c2198db175..02e0d71560 100644
--- a/apps/desktop/src/main/companion-cloud/host.ts
+++ b/apps/desktop/src/main/companion-cloud/host.ts
@@ -13,11 +13,18 @@ import { getDbClient } from '../localDb/client/current.js';
import { createBotProfile, getBotMemoryService, setBotProfileAvatar, updateBotProfile } from '../localDb/ipc/bots.js';
import { decodeBotAvatarImage } from '../localDb/ipc/botAvatarSelection.js';
import { createMessage } from '../localDb/ipc/messages.js';
-import { botProfiles, botSessionLinks, messages } from '../localDb/schema.js';
+import { commitChatImageUrls } from '../cindy-media/chatAttachments.js';
+import { botProfileVersions, botProfiles, botSessionLinks, messages } from '../localDb/schema.js';
+import { inferBotTemplatePresetId } from '../../shared/botTemplatePreset.js';
import { resolveBotCanonicalSession } from '../maker-ipc/botCanonicalSessionRegistry.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';
+import { companionTodoStore } from '../maker-ipc/botTodoAccess.js';
+import { mergeCompanionWorkbench, readCompanionWorkbench } from '../maker-ipc/botWorkbenchService.js';
+import { importCompanionRoutines, listCompanionRoutines, type CompanionRoutineValue } from '../routines/service.js';
+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';
@@ -27,24 +34,40 @@ import type { CompanionLog } from './types.js';
import {
COMPANION_MEMORY_PREFIX,
COMPANION_PROFILE_KEY,
+ COMPANION_ROUTINE_PREFIX,
COMPANION_SKILL_PREFIX,
+ COMPANION_TODO_PREFIX,
+ COMPANION_WORKBENCH_KEY,
type CompanionPreferenceValue,
} from './uploader.js';
/** Derived memory files: USER.md travels inside the profile, MEMORY.md is a rebuilt index. */
const SKIPPED_MEMORY_FILES = new Set(['USER.md', 'MEMORY.md']);
-export async function readCompanionValues(botId: string): Promise<CompanionPreferenceValue[]> {
+function profileTemplateId(capabilitiesJson: string | null, identitySource: string): string | null {
+ try {
+ const value = (JSON.parse(capabilitiesJson ?? '{}') as { templateId?: unknown }).templateId;
+ if (typeof value === 'string' && value) return value;
+ } catch { /* fall back to the identity */ }
+ return inferBotTemplatePresetId(identitySource);
+}
+
+export async function readCompanionValues(botId: string, selfDeviceId: string | null = null): Promise<CompanionPreferenceValue[]> {
const userDataDir = ownerScopedUserDataPath();
const [row] = await getDbClient().drizzle
- .select({ displayName: botProfiles.displayName, description: botProfiles.description })
- .from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);
+ .select({ displayName: botProfiles.displayName, description: botProfiles.description, capabilities: botProfileVersions.capabilitiesJson })
+ .from(botProfiles)
+ .leftJoin(botProfileVersions, and(eq(botProfileVersions.botId, botProfiles.id), eq(botProfileVersions.version, botProfiles.currentVersion)))
+ .where(eq(botProfiles.id, botId)).limit(1);
if (!row) return [];
// Strict: an unreadable SOUL/USER/prompt file aborts the cycle instead of uploading it as empty.
const folder = await readBotProfileFolder(userDataDir, botId, { strict: true });
+ // Which preset it was made from: every computer can then tell the copies of Cindy apart from a
+ // teammate that is only named Cindy (the merge never goes by name).
+ const templateId = profileTemplateId(row.capabilities, folder.identitySource);
const values: CompanionPreferenceValue[] = [{ key: COMPANION_PROFILE_KEY, value: {
name: row.displayName, description: row.description, soul: folder.identitySource,
- systemPrompt: folder.systemPromptOverride, user: folder.userContextSource,
+ systemPrompt: folder.systemPromptOverride, user: folder.userContextSource, ...(templateId ? { templateId } : {}),
} }];
const memoryDir = botProfileMemoryDir(userDataDir, botId);
// Only a missing folder means "no memories"; any other read error aborts this cycle so the
@@ -64,6 +87,21 @@ export async function readCompanionValues(botId: string): Promise<CompanionPrefe
slug: skill.slug, content: skill.source, ...(skill.enabled ? {} : { enabled: false }),
} });
}
+ // Todos, routines and the workbench move with the companion too (cloud-companions.md §2). A read
+ // failure aborts the cycle like the files above, so nothing is tombstoned by mistake.
+ // These parts are read separately: one that cannot be read now (e.g. routines before their engine
+ // is ready) leaves its cloud values untouched instead of stopping the profile and memories.
+ const part = async (prefix: string, read: () => Promise<CompanionPreferenceValue[]>) => {
+ try { values.push(...await read()); } catch { values.push({ key: prefix, value: null, unread: true }); }
+ };
+ await part(COMPANION_TODO_PREFIX, async () => travellingTodos((await companionTodoStore(botId).read()).items)
+ .map(item => ({ key: `${COMPANION_TODO_PREFIX}${item.id}`, value: portableTodo(item) })));
+ await part(COMPANION_ROUTINE_PREFIX, async () => (await listCompanionRoutines(botId, selfDeviceId))
+ .map(routine => ({ key: `${COMPANION_ROUTINE_PREFIX}${routine.id}`, value: routine })));
+ if (selfDeviceId) await part(COMPANION_WORKBENCH_KEY, async () => {
+ const workbench = await readCompanionWorkbench(userDataDir, botId, selfDeviceId);
+ return workbench.directories.length || Object.keys(workbench.tasks).length ? [{ key: COMPANION_WORKBENCH_KEY, value: workbench }] : [];
+ });
return values;
}
@@ -105,8 +143,29 @@ type MaterializeLocal = Omit<CompanionMaterializeHost, 'latestRows'>;
function createMaterializer(input: {
ensureCanonicalSession: (botId: string) => Promise<string>;
rebuildContext: (sessionId: string) => Promise<'rebuilt' | 'busy'>;
+ selfDeviceId?: () => string | null;
}): MaterializeLocal {
return {
+ applyTodos: async (botId, items, remove, fence) => {
+ fence.assertCurrent();
+ const todos = items.filter((item): item is TeammateTodo => !!item && typeof item === 'object'
+ && typeof (item as { id?: unknown }).id === 'string' && (item as { id: string }).id.startsWith('todo:')
+ && typeof (item as { title?: unknown }).title === 'string' && Array.isArray((item as { history?: unknown }).history));
+ await companionTodoStore(botId).importItems(todos, remove);
+ },
+ applyRoutines: async (botId, routines, remove, fence) => {
+ fence.assertCurrent();
+ const valid = routines.filter((routine): routine is CompanionRoutineValue => !!routine && typeof routine === 'object'
+ && typeof (routine as { id?: unknown }).id === 'string' && !!(routine as { input?: unknown }).input
+ && Array.isArray((routine as { input: { triggers?: unknown } }).input.triggers));
+ await importCompanionRoutines(botId, valid, remove, input.selfDeviceId?.() ?? null);
+ },
+ applyWorkbench: async (botId, value, fence, options) => {
+ const self = input.selfDeviceId?.();
+ if (!self) throw new Error('DEVICE_UNKNOWN');
+ fence.assertCurrent();
+ await mergeCompanionWorkbench(ownerScopedUserDataPath(), botId, self, value, options);
+ },
readProfile: async botId => {
const [row] = await getDbClient().drizzle
.select({ status: botProfiles.status, displayName: botProfiles.displayName, description: botProfiles.description })
@@ -174,8 +233,22 @@ function createMaterializer(input: {
// Same row shape as ordinary messages; the client id keeps it out of the mirror.
insertHistory: async (sessionId, row, fence) => {
fence.assertCurrent();
+ // Files brought from the room open like any attachment of the message.
+ 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.
+ if (images.length) {
+ const commit = await commitChatImageUrls({ sessionId, urls: images.map(image => image.url) });
+ if (commit.failed > 0) throw new Error('HISTORY_IMAGE_COMMIT_FAILED');
+ fence.assertCurrent();
+ }
await createMessage(sessionId, { clientId: row.clientId, role: row.role, createdAt: row.createdAt,
- content: row.role === 'user' ? { text: row.text, images: [], files: [] } : [{ type: 'text', text: row.text }] });
+ content: row.role === 'user' ? { text: row.text, images, files: others }
+ : [{ type: 'text', text: [row.text, ...names].filter(Boolean).join('\n') }] });
},
rebuildContext: sessionId => input.rebuildContext(sessionId),
};
@@ -229,6 +302,13 @@ export function companionShadowStore() {
};
}
+/** Every live task the companion runs in: its main task, group lanes and delegations. */
+async function companionSessionIds(botId: string): Promise<string[]> {
+ const rows = await getDbClient().drizzle.select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks)
+ .where(and(eq(botSessionLinks.botId, botId), isNull(botSessionLinks.archivedAt)));
+ return rows.map(row => row.sessionId);
+}
+
export function createCompanionCloudHost(input: {
deliverToCanonical: CompanionCloudHost['deliverToCanonical'];
ensureCanonicalSession: (botId: string) => Promise<string>;
@@ -237,6 +317,11 @@ export function createCompanionCloudHost(input: {
isTurnActive?: (sessionId: string) => boolean;
listDevices: () => Promise<DeviceLinkDeviceView[]>;
probeCompanionCloud?: (deviceId: string) => Promise<boolean>;
+ homeLink?: CompanionCloudHost['homeLink'];
+ /** This computer's device-link id: names its workbench folders and routine check commands. */
+ selfDeviceId?: () => string | null;
+ /** Stop the turn running (and the input queued) in this Session, like the user's Stop. */
+ stopTurn?: (sessionId: string) => Promise<void>;
log?: CompanionLog;
}): CompanionCloudHost {
// Every reader (send guards, routines, lists) sees only the active owner's homes, and that
@@ -249,9 +334,12 @@ export function createCompanionCloudHost(input: {
`${createHash('sha256').update(`${endpoint}\n${humanActorId}`).digest('hex')}.json`),
current, log: input.log,
}),
- readValues: readCompanionValues,
+ readValues: botId => readCompanionValues(botId, input.selfDeviceId?.() ?? null),
+ // No main task yet is nothing to sync; conflicting ones are not: syncing, a hand-over and a merge
+ // must stop rather than count this computer's history as sent.
canonicalSession: async botId => {
const resolved = await resolveBotCanonicalSession(botId);
+ if (resolved.status === 'conflict') throw new Error('COMPANION_TASK_CONFLICT');
return resolved.status === 'resolved' ? resolved.sessionId : null;
},
rowsAfter: readMirrorRowsAfter,
@@ -260,13 +348,14 @@ export function createCompanionCloudHost(input: {
onLocalChange: onBotRemoteResourceChanged,
materializer: createMaterializer(input),
listDevices: input.listDevices,
- ...(input.isTurnActive ? { isBotBusy: async (botId: string) => {
- // Every live task the companion runs in: its main task, group lanes and delegations.
- const rows = await getDbClient().drizzle.select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks)
- .where(and(eq(botSessionLinks.botId, botId), isNull(botSessionLinks.archivedAt)));
- return rows.some(row => input.isTurnActive!(row.sessionId));
+ ...(input.isTurnActive ? { isBotBusy: async (botId: string) =>
+ (await companionSessionIds(botId)).some(sessionId => input.isTurnActive!(sessionId)) } : {}),
+ ...(input.isTurnActive && input.stopTurn ? { stopBotTurns: async (botId: string) => {
+ const busy = (await companionSessionIds(botId)).filter(sessionId => input.isTurnActive!(sessionId));
+ await Promise.all(busy.map(sessionId => input.stopTurn!(sessionId)));
} } : {}),
...(input.probeCompanionCloud ? { probeCompanionCloud: input.probeCompanionCloud } : {}),
+ ...(input.homeLink ? { homeLink: input.homeLink } : {}),
installationId: companionInstallationId,
shadows: companionShadowStore(),
};
diff --git a/apps/desktop/src/main/companion-cloud/materialize.ts b/apps/desktop/src/main/companion-cloud/materialize.ts
index 11e56e2e04..17af8c0cf5 100644
--- a/apps/desktop/src/main/companion-cloud/materialize.ts
+++ b/apps/desktop/src/main/companion-cloud/materialize.ts
@@ -1,7 +1,7 @@
/**
* Build or update the local companion from its cloud copy (cloud-companions.md §3.1 step 2-3):
- * profile, memories and own skills from the companion's preferences, then the latest room
- * history as local history, then a deterministic context rebuild. Nothing old is replayed.
+ * profile, memories and own skills from the companion's preferences, then the room's whole
+ * conversation as local history, then a deterministic context rebuild. Nothing old is replayed.
* Every local write is fenced by the owner that started it. The copy stays demoted (does not
* run, upload or mirror) until everything is restored; a partial restore throws and the
* automatic take-over retries it.
@@ -9,12 +9,13 @@
import type { CompanionMirrorCursor, CompanionMirrorRow } from './mirror.js';
import { COMPANION_HISTORY_CLIENT_PREFIX } from './mirror.js';
import { directRoomSourceId } from './directRoom.js';
-import { readRecentRoomMessages } from './room.js';
+import { readAllRoomMessages } from './room.js';
import type { CompanionCloudState } from './state.js';
-import { errorCode, type CompanionApi, type CompanionLog } from './types.js';
-import { COMPANION_MEMORY_PREFIX, COMPANION_PROFILE_KEY, COMPANION_SKILL_PREFIX, TOMBSTONE_HASH, isCompanionProfileSnapshot, valueHash } from './uploader.js';
-
-export const COMPANION_HISTORY_LIMIT = 200;
+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_WORKBENCH_KEY, TOMBSTONE_HASH, isCompanionProfileSnapshot, valueHash,
+} from './uploader.js';
export interface CompanionLocalProfile { status: string; displayName: string; description: string }
@@ -47,19 +48,40 @@ export interface CompanionMaterializeHost {
readSkill: (botId: string, slug: string) => Promise<string | null>;
saveSkill: (botId: string, slug: string, content: string, enabled: boolean, fence: CompanionWriteFence) => Promise<void>;
removeSkill: (botId: string, slug: string, fence: CompanionWriteFence) => Promise<void>;
+ /** The companion's todos from the cloud replace the same ids here; `remove` ids are deleted. */
+ applyTodos?: (botId: string, items: unknown[], remove: string[], fence: CompanionWriteFence) => Promise<void>;
+ /** Its routines from the cloud are created or updated with their ids; `remove` ids are deleted. */
+ applyRoutines?: (botId: string, routines: unknown[], remove: string[], fence: CompanionWriteFence) => Promise<void>;
+ /**
+ * Its workbench folders and portable judgments join this computer's, or with `replace` take their
+ * place (`null`: the companion has none).
+ */
+ applyWorkbench?: (botId: string, value: unknown, fence: CompanionWriteFence, options?: { replace?: boolean }) => Promise<void>;
ensureCanonicalSession: (botId: string, fence: CompanionWriteFence) => Promise<string>;
/**
* Local rows created at or after `fromMs`, including rewound and deleted ones (`removed`):
* dedupe against mirrored, delivered and deliberately removed messages.
*/
localMessageTimes: (sessionId: string, fromMs: number) => Promise<Array<{ role: string; createdAt: number; clientId: string; removed?: boolean }>>;
- insertHistory: (sessionId: string, row: { clientId: string; role: 'user' | 'assistant'; text: string; createdAt: number }, fence: CompanionWriteFence) => Promise<void>;
+ insertHistory: (sessionId: string, row: {
+ clientId: string; role: 'user' | 'assistant'; text: string; createdAt: number;
+ /** Files of the message, already downloaded to this computer. */
+ attachments?: CompanionHistoryAttachment[];
+ }, fence: CompanionWriteFence) => Promise<void>;
/** Rebuild the native context from DB history like a companion restart; never interrupts a turn. */
rebuildContext: (sessionId: string, fence: CompanionWriteFence) => Promise<'rebuilt' | 'busy'>;
/** Newest first; `excludeClientIdPrefix` leaves out rows whose client id starts with it. */
latestRows: (sessionId: string, limit: number, options?: { excludeClientIdPrefix?: string }) => Promise<CompanionMirrorRow[]>;
}
+/** A room file brought to this computer: images in the media store, other files by path. */
+export interface CompanionHistoryAttachment {
+ name: string; category: string; mimeType: string; size: number; url: string | null; path: string | null;
+}
+
+/** Download one of the room's files to this computer. */
+export type CompanionRoomDownload = (roomId: string, mediaId: string) => Promise<CompanionHistoryAttachment>;
+
export interface CompanionMaterializeActor { id: string; externalId: string; name: string; avatar: string | null }
export interface CompanionMaterializeResult {
@@ -84,6 +106,8 @@ export async function materializeCompanion(input: {
log?: CompanionLog;
/** Publish the demotion (send guard, routines, lists) before the first local write. */
onDemoted?: () => void;
+ /** Brings the room's files along with the history; without it only their names come. */
+ download?: CompanionRoomDownload;
}): Promise<CompanionMaterializeResult> {
const { api, state, host, actor, log } = input;
const fence = input.fence ?? noFence;
@@ -179,6 +203,36 @@ export async function materializeCompanion(input: {
}
}
+ // 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),
+ // so this computer keeps its own copy.
+ const batches = [
+ { prefix: COMPANION_TODO_PREFIX, kind: 'todo', run: host.applyTodos, removes: false },
+ { prefix: COMPANION_ROUTINE_PREFIX, kind: 'routine', run: host.applyRoutines, removes: true },
+ ] as const;
+ for (const batch of batches) {
+ const rows = [...prefs].filter(([key]) => key.startsWith(batch.prefix));
+ if (!rows.length || !batch.run) continue;
+ await apply(batch.kind, async () => {
+ const values = rows.flatMap(([, row]) => (row.value === null ? [] : [row.value]));
+ const removed = batch.removes ? rows.flatMap(([key, row]) => (row.value === null ? [key.slice(batch.prefix.length)] : [])) : [];
+ await step(() => batch.run!(botId, values, removed, fence));
+ for (const [key, row] of rows) applied.set(key, { hash: row.value === null ? TOMBSTONE_HASH : valueHash(row.value), revision: row.revision });
+ });
+ }
+ // A workbench this computer synced before is the cloud's from back then: the cloud replaces it, so
+ // a folder or judgment removed meanwhile (or all of them) stays removed. One that never synced
+ // (an old copy of its own) joins, and goes up with the rest.
+ const workbench = prefs.get(COMPANION_WORKBENCH_KEY);
+ const replaceWorkbench = !!knownPrefs[COMPANION_WORKBENCH_KEY];
+ if (workbench && host.applyWorkbench && (workbench.value !== null || replaceWorkbench)) {
+ await apply('workbench', async () => {
+ await step(() => host.applyWorkbench!(botId, workbench.value, fence, { replace: replaceWorkbench }));
+ applied.set(COMPANION_WORKBENCH_KEY, { hash: workbench.value === null ? TOMBSTONE_HASH : valueHash(workbench.value), revision: workbench.revision });
+ });
+ }
+
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 }; });
@@ -187,7 +241,8 @@ export async function materializeCompanion(input: {
const sessionId = await step(() => host.ensureCanonicalSession(botId, fence));
const roomId = await step(() => input.roomId());
- const inserted = await importCloudHistory({ api, host, sessionId, botActorId: actor.id, roomId, fence });
+ const inserted = await importCloudHistory({ api, host, sessionId, botActorId: actor.id, roomId, fence,
+ ...(input.download ? { download: input.download } : {}), ...(log ? { log } : {}) });
// Keep the mirror coherent: everything up to now is already in the room. Imported history
// (possibly stamped by a peer's clock) never sets the cursor.
const [latest] = await host.latestRows(sessionId, 1, { excludeClientIdPrefix: COMPANION_HISTORY_CLIENT_PREFIX });
@@ -216,7 +271,7 @@ export async function materializeCompanion(input: {
return { created: !local, inserted, rebuild, ...(backup !== undefined ? { backup } : {}) };
}
-/** Insert the room's latest messages that are not already local, oldest first. */
+/** Insert the room's whole conversation that is not already local, in message-time order. */
export async function importCloudHistory(input: {
api: CompanionApi;
host: Pick<CompanionMaterializeHost, 'localMessageTimes' | 'insertHistory'>;
@@ -224,9 +279,11 @@ export async function importCloudHistory(input: {
botActorId: string;
roomId: string;
fence?: CompanionWriteFence;
+ download?: CompanionRoomDownload;
+ log?: CompanionLog;
}): Promise<number> {
const fence = input.fence ?? noFence;
- const messages = await readRecentRoomMessages(input.api, input.roomId, input.botActorId, COMPANION_HISTORY_LIMIT);
+ const messages = await readAllRoomMessages(input.api, input.roomId, input.botActorId, { complete: true });
if (!messages.length) return 0;
// Rows already imported, and delivered direct-room messages, name their room message in the
// client id: exact. Rows mirrored from this Session keep their local timestamp; the server
@@ -241,8 +298,24 @@ export async function importCloudHistory(input: {
for (const message of messages) {
if (known.has(message.id) || present.has(`${message.role}:${message.createdAt}`)) continue;
fence.assertCurrent();
+ // Files come along when they can be fetched; a file that cannot keeps its name in the text.
+ const attachments: CompanionHistoryAttachment[] = [];
+ const missing: string[] = [];
+ for (const file of message.attachments ?? []) {
+ try {
+ if (!input.download) throw new Error('DOWNLOAD_UNAVAILABLE');
+ attachments.push(await input.download(input.roomId, file.mediaId));
+ } catch (error) {
+ // A file that may still come fails the take-over (retried); this message is not inserted yet.
+ if (isTransientAttachmentFailure(error)) throw error;
+ missing.push(file.name);
+ input.log?.warn('Companion history attachment not brought over', { code: errorCode(error) });
+ }
+ fence.assertCurrent();
+ }
+ const text = [message.text, ...missing.map(name => `[附件: ${name}]`)].filter(Boolean).join('\n');
await input.host.insertHistory(input.sessionId, { clientId: `${COMPANION_HISTORY_CLIENT_PREFIX}${message.id}`,
- role: message.role, text: message.text, createdAt: message.createdAt }, fence);
+ role: message.role, text, createdAt: message.createdAt, ...(attachments.length ? { attachments } : {}) }, fence);
inserted += 1;
}
fence.assertCurrent();
diff --git a/apps/desktop/src/main/companion-cloud/merge.ts b/apps/desktop/src/main/companion-cloud/merge.ts
new file mode 100644
index 0000000000..a43272f047
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/merge.ts
@@ -0,0 +1,261 @@
+/**
+ * Merging the copies of Cindy that grew on separate computers into one companion
+ * (cloud-companions.md, 2026-10-16 裁决 2). Runs on the kept Cindy's home: the other copies'
+ * memories, own skills, todos, routines, workbench and conversation join it; their profile does
+ * not (the kept one is the user's chosen base). Nothing is overwritten silently: a memory or skill
+ * that exists on both sides with different content is kept as a second, renamed entry. The merged
+ * copies are retired in the cloud only once everything, the kept task's history included, is in;
+ * their own data stays there and on their computers. Every step is idempotent, so a failed merge
+ * (sources still active) is simply run again.
+ */
+import { createHash } from 'node:crypto';
+import { inferBotTemplatePresetId } from '../../shared/botTemplatePreset.js';
+import type { CompanionHistoryAttachment, CompanionMaterializeHost, CompanionWriteFence } from './materialize.js';
+import type { CompanionMediaUpload, CompanionMirrorAttachment } from './mirror.js';
+import { readAllRoomMessages, readRoomPage } from './room.js';
+import { 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_WORKBENCH_KEY,
+} from './uploader.js';
+
+export interface CompanionMergeActor {
+ id: string; externalId: string; name: string; homeDeviceId?: string | null;
+ /** Where it came from (its computer's name), for naming a second copy of a same-name memory or skill. */
+ label?: string;
+}
+
+export interface CompanionMergeSummary {
+ merged: number;
+ messages: number;
+ memories: number;
+ skills: number;
+ /** Memories and skills that existed on both sides with different content, kept under these names. */
+ renamed: string[];
+}
+
+type PrefRow = { key: string; value: unknown; revision: number };
+
+/** Copies of Cindy: made from the Cindy preset, or the provisioned default Cindy. Never by name. */
+export function isCindyCompanion(externalId: string, profile: unknown): boolean {
+ if (externalId === 'cindy-default') return true;
+ const value = profile && typeof profile === 'object' ? profile as { templateId?: unknown; soul?: unknown } : {};
+ if (value.templateId === 'cindy') return true;
+ return typeof value.soul === 'string' && inferBotTemplatePresetId(value.soul) === 'cindy';
+}
+
+const BATCH = 50;
+const BATCH_BYTES = 200_000;
+const text = (value: unknown) => typeof value === 'string' ? value : undefined;
+const record = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
+
+/** `name.md` → `name-<suffix>.md` (then `-2`, `-3`…); skills are slugs without an extension. */
+export function renamedEntry(name: string, suffix: string, attempt = 1): string {
+ const dot = name.lastIndexOf('.');
+ const safe = (suffix.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'merged')
+ + (attempt > 1 ? `-${attempt}` : '');
+ return dot > 0 ? `${name.slice(0, dot)}-${safe}${name.slice(dot)}` : `${name}-${safe}`;
+}
+
+const RENAME_ATTEMPTS = 50;
+
+/**
+ * Where a source entry goes in the kept companion: its own name when free, else the first renamed
+ * name that is free or already holds the same content (a rerun); null when it is already there.
+ */
+async function mergeTarget(name: string, suffix: string, content: string, read: (name: string) => Promise<string | null>): Promise<string | null> {
+ const current = await read(name);
+ if (current === null) return name;
+ if (current === content) return null;
+ for (let attempt = 1; attempt <= RENAME_ATTEMPTS; attempt += 1) {
+ const target = renamedEntry(name, suffix, attempt);
+ const existing = await read(target);
+ if (existing === content) return null;
+ if (existing === null) return target;
+ }
+ throw new Error('MERGE_NAME_EXHAUSTED');
+}
+
+/**
+ * Every todo and routine joining another companion gets an id of its own, stable per (kept
+ * companion, source, original id): copies of Cindy can hold the same id (a todo made from the same
+ * old workbench entry, a routine the source still owns here), and nothing merged may replace
+ * another. A rerun derives the same ids, so it replaces only what it brought before.
+ */
+function mergedEntryHash(keepBotId: string, sourceActorId: string, id: string): string {
+ return createHash('sha256').update(`${keepBotId}\n${sourceActorId}\n${id}`).digest('hex').slice(0, 40);
+}
+export function mergedRoutineId(keepBotId: string, sourceActorId: string, routineId: string): string {
+ return `m${mergedEntryHash(keepBotId, sourceActorId, routineId)}`;
+}
+export function mergedTodoId(keepBotId: string, sourceActorId: string, todoId: string): string {
+ return `todo:m-${mergedEntryHash(keepBotId, sourceActorId, todoId)}`;
+}
+
+export async function mergeCompanionsInto(input: {
+ api: CompanionApi;
+ host: Pick<CompanionMaterializeHost, 'readMemory' | 'restoreMemory' | 'readSkill' | 'saveSkill' | 'applyTodos' | 'applyRoutines' | 'applyWorkbench'>;
+ keep: CompanionMergeActor;
+ from: CompanionMergeActor[];
+ humanActorId: string;
+ /** Room of a companion (deterministic per companion actor). */
+ roomOf: (actor: CompanionMergeActor) => Promise<string>;
+ media?: { upload: CompanionMediaUpload; download: (roomId: string, mediaId: string) => Promise<CompanionHistoryAttachment> };
+ /** After the conversation is in the kept room: bring it into the kept companion's own task. */
+ importHistory: () => Promise<void>;
+ /** Right before retiring: each copy's home sends anything it produced meanwhile (throws when it cannot). */
+ beforeRetire?: () => Promise<void>;
+ fence: CompanionWriteFence;
+ log?: CompanionLog;
+}): Promise<CompanionMergeSummary> {
+ const { api, host, keep, fence } = input;
+ const summary: CompanionMergeSummary = { merged: 0, messages: 0, memories: 0, skills: 0, renamed: [] };
+ const keepRoom = await input.roomOf(keep);
+ // What each copy had in the cloud when the merge read it: anything newer at the end was missed.
+ const seen = new Map<string, string>();
+ for (const source of input.from) {
+ fence.assertCurrent();
+ seen.set(source.id, await cloudMark(api, source, input.roomOf));
+ const rows = await api<PrefRow[]>('/preferences', 'GET', undefined, source.id);
+ const prefs = (Array.isArray(rows) ? rows : []).filter(row => row.value !== null);
+ const suffix = source.label || (source.name && source.name !== keep.name ? source.name : source.externalId.slice(-8));
+
+ for (const row of prefs.filter(candidate => candidate.key.startsWith(COMPANION_MEMORY_PREFIX))) {
+ const filename = row.key.slice(COMPANION_MEMORY_PREFIX.length);
+ const content = text(record(row.value)?.content);
+ if (content === undefined) continue;
+ // A second run finds the (renamed) copy already there.
+ const target = await mergeTarget(filename, suffix, content, name => host.readMemory(keep.externalId, name));
+ if (target === null) continue;
+ if (target !== filename) summary.renamed.push(target);
+ fence.assertCurrent();
+ await host.restoreMemory(keep.externalId, target, content, fence);
+ summary.memories += 1;
+ }
+
+ for (const row of prefs.filter(candidate => candidate.key.startsWith(COMPANION_SKILL_PREFIX))) {
+ const slug = row.key.slice(COMPANION_SKILL_PREFIX.length);
+ const content = text(record(row.value)?.content);
+ if (content === undefined) continue;
+ const target = await mergeTarget(slug, suffix, content, name => host.readSkill(keep.externalId, name));
+ if (target === null) continue;
+ if (target !== slug) summary.renamed.push(target);
+ fence.assertCurrent();
+ await host.saveSkill(keep.externalId, target, content, record(row.value)?.enabled !== false, fence);
+ summary.skills += 1;
+ }
+
+ // Todos and routines get ids of their own in the kept companion (the store also gives a
+ // same-key todo its own key).
+ const todos = prefs.filter(row => row.key.startsWith(COMPANION_TODO_PREFIX)).map(row => row.value).flatMap(value => {
+ const todo = record(value);
+ return todo && typeof todo.id === 'string' ? [{ ...todo, id: mergedTodoId(keep.externalId, source.id, todo.id) }] : [];
+ });
+ if (todos.length && host.applyTodos) await host.applyTodos(keep.externalId, todos, [], fence);
+ const routines = prefs.filter(row => row.key.startsWith(COMPANION_ROUTINE_PREFIX)).map(row => row.value).flatMap(value => {
+ const routine = record(value);
+ return routine && typeof routine.id === 'string' ? [{ ...routine, id: mergedRoutineId(keep.externalId, source.id, routine.id) }] : [];
+ });
+ if (routines.length && host.applyRoutines) await host.applyRoutines(keep.externalId, routines, [], fence);
+ const workbench = prefs.find(row => row.key === COMPANION_WORKBENCH_KEY);
+ if (workbench && host.applyWorkbench) await host.applyWorkbench(keep.externalId, workbench.value, fence);
+
+ summary.messages += await mergeConversation({ ...input, source, keepRoom });
+ }
+ await input.importHistory();
+ // A copy that kept working during the merge (a new turn, a memory saved) has more in the cloud
+ // than was read: stop with every copy active; running the merge again brings the rest.
+ await input.beforeRetire?.();
+ for (const source of input.from) {
+ fence.assertCurrent();
+ if (await cloudMark(api, source, input.roomOf) !== seen.get(source.id)) throw new Error('COMPANION_STILL_CHANGING');
+ }
+ // Only now are the merged copies no longer companions: other computers hide and stop their copy.
+ // Until here a failure leaves every source active, so the merge can run again.
+ for (const source of input.from) {
+ fence.assertCurrent();
+ await api(`/actors/${source.id}`, 'PATCH', { disabled: true });
+ summary.merged += 1;
+ }
+ return summary;
+}
+
+/** The source's conversation into the kept room, by message time, keeping each message's time. */
+async function mergeConversation(input: {
+ api: CompanionApi;
+ keep: CompanionMergeActor;
+ source: CompanionMergeActor;
+ keepRoom: string;
+ humanActorId: string;
+ roomOf: (actor: CompanionMergeActor) => Promise<string>;
+ media?: { upload: CompanionMediaUpload; download: (roomId: string, mediaId: string) => Promise<CompanionHistoryAttachment> };
+ fence: CompanionWriteFence;
+ log?: CompanionLog;
+}): Promise<number> {
+ const sourceRoom = await input.roomOf(input.source);
+ const messages = await readAllRoomMessages(input.api, sourceRoom, input.source.id, { complete: true });
+ const prepared: Array<{ sourceId: string; authorId: string; createdAt: string; content: Array<Record<string, unknown>> }> = [];
+ for (const message of messages) {
+ const authorId = message.role === 'assistant' ? input.keep.id : input.humanActorId;
+ const sourceId = `merge:${input.source.id}:${message.id}`;
+ // Room files belong to their room: bring each over (download, upload again); a file that
+ // cannot come keeps its name in the text.
+ const media: Array<{ type: string; mediaId?: string; caption?: string }> = [];
+ const missing: string[] = [];
+ for (const file of message.attachments ?? []) {
+ try {
+ if (!input.media) throw new Error('MEDIA_UNAVAILABLE');
+ const local = await input.media.download(sourceRoom, file.mediaId);
+ const attachment: CompanionMirrorAttachment = { id: file.mediaId, name: local.name, category: local.url ? 'image' : 'file',
+ mimeType: local.mimeType, size: local.size, url: local.url, path: local.path };
+ media.push(...await input.media.upload(input.keepRoom, sourceId, [attachment], authorId));
+ } catch (error) {
+ // A file that may still come fails the merge (every copy stays active, so it can run again).
+ if (isTransientAttachmentFailure(error)) throw error;
+ missing.push(file.name);
+ input.log?.warn('Merged attachment kept as its name', { code: error instanceof Error ? error.message.slice(0, 80) : 'UNKNOWN' });
+ }
+ input.fence.assertCurrent();
+ }
+ const body = [message.text, ...missing.map(name => `[附件: ${name}]`)].filter(Boolean).join('\n');
+ prepared.push({ sourceId, authorId, createdAt: new Date(message.createdAt).toISOString(),
+ content: [...(body ? [{ type: 'text', text: body }] : []), ...media] });
+ }
+ let imported = 0;
+ let start = 0;
+ while (start < prepared.length) {
+ // Same limits as the mirror: at most 50 messages and about 200 KB per request.
+ let end = start; let bytes = 0;
+ while (end < prepared.length && end - start < BATCH) {
+ const size = Buffer.byteLength(JSON.stringify(prepared[end]));
+ if (end > start && bytes + size > BATCH_BYTES) break;
+ bytes += size; end += 1;
+ }
+ const batch = prepared.slice(start, end);
+ input.fence.assertCurrent();
+ await input.api(`/conversations/${input.keepRoom}/import`, 'POST', {
+ operationId: `companion-merge:${createHash('sha256').update(JSON.stringify(batch)).digest('hex').slice(0, 48)}`, messages: batch });
+ imported += batch.length;
+ start = end;
+ }
+ return imported;
+}
+
+/**
+ * What a copy has in the cloud: every preference with its revision (revisions count per key, so a
+ * new, changed or removed one changes the list) and the newest room message (room order). Any
+ * difference means it added something.
+ */
+async function cloudMark(api: CompanionApi, actor: CompanionMergeActor, roomOf: (actor: CompanionMergeActor) => Promise<string>): Promise<string> {
+ const rows = await api<PrefRow[]>('/preferences', 'GET', undefined, actor.id);
+ const prefs = (Array.isArray(rows) ? rows : []).map(row => `${row.key}\u0000${row.revision}`).sort();
+ const page = await readRoomPage(api, await roomOf(actor));
+ const seq = page.reduce((max, message) => (BigInt(message.seq) > max ? BigInt(message.seq) : max), 0n);
+ return createHash('sha256').update(JSON.stringify([prefs, String(seq)])).digest('hex');
+}
+
+/** The profile snapshot of a companion actor, for telling the copies of Cindy apart. */
+export async function readProfileSnapshot(api: CompanionApi, actorId: string): Promise<unknown> {
+ const rows = await api<PrefRow[]>('/preferences', 'GET', undefined, actorId);
+ return (Array.isArray(rows) ? rows : []).find(row => row.key === COMPANION_PROFILE_KEY)?.value ?? null;
+}
diff --git a/apps/desktop/src/main/companion-cloud/mirror.ts b/apps/desktop/src/main/companion-cloud/mirror.ts
index bdf94be9d7..5d72e45e29 100644
--- a/apps/desktop/src/main/companion-cloud/mirror.ts
+++ b/apps/desktop/src/main/companion-cloud/mirror.ts
@@ -5,9 +5,11 @@
*/
import { createHash } from 'node:crypto';
import { isSubagentParentToolUseId } from '@cindy/maker-shared/message-render';
+import { messageSourceSenderFromMeta } from '@cindy/maker-shared/message-source';
+import { imChannelDisplayName } from '../../shared/imMessageSource.js';
import { visibleMessageText } from '../localDb/conversationSearch.pure.js';
import type { CompanionCloudState } from './state.js';
-import { chatRejection, type CompanionApi } from './types.js';
+import { chatRejection, errorCode, isTransientAttachmentFailure, type CompanionApi, type CompanionLog } from './types.js';
export interface CompanionMirrorRow {
id: string;
@@ -34,6 +36,8 @@ const PART_BYTES = 60_000;
const RESCAN_WINDOW_MS = 10 * 60_000;
const RESCAN_LIMIT = 200;
const RECENT_IDS = 400;
+/** Owner attachments the mirror uploads at most (larger ones stay a name in the room). */
+export const MIRROR_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
const parse = (raw: string | null): unknown => {
if (!raw) return null;
@@ -56,16 +60,63 @@ function attachmentNames(content: unknown): string[] {
}
/**
- * Host-stamped sender/source metadata (message-source.md). A user row carrying any of these
- * was sent by another task, teammate, plugin, IM channel, automation, Orca or a shared-task
- * member — not typed by the owner — so it never goes up as the owner's words.
- * `sourceDevice` (the owner on another device) is the one source that stays.
+ * User rows the companion's own chat hides (automatic continuations, coordination between
+ * teammates): not part of the visible conversation, so not in the room either.
*/
-const NON_OWNER_SOURCE_KEYS = ['origin', 'sourcePlugin', 'sharedTaskAuthor', 'imSource', 'hookSource', 'sourceGroup',
- 'botTaskCoordination', 'autoReviewUserText', 'autoResume'] as const;
+const HIDDEN_INPUT_KEYS = ['botTaskCoordination', 'autoResume'] as const;
+
+const SCHEDULER_LABEL = '定时任务';
+
+/**
+ * Where a visible user row came from when the owner did not type it here, in the words the chat
+ * shows next to it (message-source.md): the room shows the same conversation as the chat, with the
+ * same attribution. Owner input (also from another device; `autoReviewUserText` marks it) has none.
+ */
+export function mirrorSourceLabel(meta: Record<string, unknown>): string | null {
+ const sender = messageSourceSenderFromMeta(meta);
+ const quote = (name: unknown) => (typeof name === 'string' && name.trim() ? `「${name.trim().slice(0, 80)}」` : '');
+ if (sender?.kind === 'plugin') return `来自插件${quote(sender.name)}`;
+ if (sender?.kind === 'session') return sender.botId ? `来自伙伴${quote(sender.botName)}` : `来自任务${quote(sender.title)}`;
+ if (sender?.kind === 'shared-member') return `来自共享任务成员${quote(sender.name)}`;
+ const origin = meta.origin && typeof meta.origin === 'object' ? meta.origin as Record<string, unknown> : null;
+ if (origin?.kind === 'scheduler') return `来自${SCHEDULER_LABEL}`;
+ if (origin?.kind === 'orca') return '来自协同任务';
+ for (const key of ['imSource', 'hookSource'] as const) {
+ const source = meta[key] && typeof meta[key] === 'object' ? meta[key] as Record<string, unknown> : null;
+ if (source) return `来自${imChannelDisplayName(source.im) ?? '外部渠道'}`;
+ }
+ if (meta.sourceGroup) return '来自群聊';
+ return null;
+}
+
+/** A file the owner sent with a message, as the room media upload reads it. */
+export interface CompanionMirrorAttachment {
+ id: string; name: string; category: 'image' | 'file'; mimeType: string; size: number; url: string | null; path: string | null;
+}
+
+/**
+ * The owner's attachments of a mirrored user row (images from the media store, files by path on
+ * this computer). Only rows that are part of the visible conversation have any.
+ */
+export function mirrorAttachments(row: CompanionMirrorRow): CompanionMirrorAttachment[] {
+ if (row.role !== 'user' || mirrorMessageText(row) === null) return [];
+ const content = parse(row.content);
+ if (!content || typeof content !== 'object' || Array.isArray(content)) return [];
+ const record = content as Record<string, unknown>;
+ const list = (value: unknown) => (Array.isArray(value) ? value : []).map(item => (item && typeof item === 'object' ? item as Record<string, unknown> : {}));
+ const text = (value: unknown) => (typeof value === 'string' ? value : '');
+ const name = (item: Record<string, unknown>, fallback: string) =>
+ ([item.originalName, item.name].find((value): value is string => typeof value === 'string' && !!value.trim()) ?? fallback).replace(/[\r\n]+/g, ' ').slice(0, 200);
+ return [
+ ...list(record.images).map((item, index) => ({ id: `${row.id}:image:${index}`, name: name(item, '图片'), category: 'image' as const,
+ mimeType: text(item.mimeType) || 'image/png', size: typeof item.size === 'number' ? item.size : 0, url: text(item.url) || null, path: null })),
+ ...list(record.files).map((item, index) => ({ id: `${row.id}:file:${index}`, name: name(item, '文件'), category: 'file' as const,
+ mimeType: text(item.mimeType) || 'application/octet-stream', size: typeof item.size === 'number' ? item.size : 0, url: null, path: text(item.path) || null })),
+ ].filter(attachment => attachment.url || attachment.path);
+}
/** Room text of a canonical row, or null when the row is not part of the visible conversation. */
-export function mirrorMessageText(row: CompanionMirrorRow): string | null {
+export function mirrorMessageText(row: CompanionMirrorRow, options: { placeholders?: boolean } = {}): string | null {
if (row.role !== 'user' && row.role !== 'assistant') return null;
if (row.clientId.startsWith(COMPANION_DIRECT_CLIENT_PREFIX) || row.clientId.startsWith(COMPANION_HISTORY_CLIENT_PREFIX)) return null;
const parsedMeta = parse(row.agentMeta);
@@ -76,13 +127,21 @@ export function mirrorMessageText(row: CompanionMirrorRow): string | null {
|| (meta.parentToolUseId ?? null) !== null || (meta.parent_tool_use_id ?? null) !== null
// Claude sub-agent rows; same predicate as the renderer (a legacy transcript link is not one).
|| (typeof meta.parentUuid === 'string' && !!meta.parentUuid && isSubagentParentToolUseId(meta.parentUuid)))) return null;
- if (row.role === 'user' && NON_OWNER_SOURCE_KEYS.some(key => meta[key] !== undefined && meta[key] !== null && meta[key] !== false)) return null;
- const text = visibleMessageText(row.role, row.content);
+ if (row.role === 'user' && HIDDEN_INPUT_KEYS.some(key => meta[key] !== undefined && meta[key] !== null && meta[key] !== false)) return null;
+ // A delegated continuation (not something said in this chat) carries this marker as an object.
+ if (row.role === 'user' && meta.autoReviewUserText && typeof meta.autoReviewUserText === 'object') return null;
+ // IM input keeps the person's own words apart from the context the host put around them.
+ const im = row.role === 'user' && meta.imSource && typeof meta.imSource === 'object' ? meta.imSource as Record<string, unknown> : null;
+ const typed = typeof im?.userText === 'string' && im.userText.trim() ? im.userText.trim() : visibleMessageText(row.role, row.content);
+ const label = row.role === 'user' ? mirrorSourceLabel(meta) : null;
+ const text = label && typed ? `〔${label}〕\n${typed}` : typed;
// Attachments count on their own: an images-only message is still the owner's message.
// Hidden synthetic inputs carry no attachments, so they stay out.
const names = row.role === 'user' ? attachmentNames(parse(row.content)) : [];
const result = [text, ...names.map(name => `[附件: ${name}]`)].filter(Boolean).join('\n').trim();
- return result || null;
+ if (!result) return null;
+ // With the files themselves in the room, only the typed text goes along (it may be empty).
+ return options.placeholders === false ? text.trim() : result;
}
/** Split into room-sized parts without breaking surrogate pairs. */
@@ -100,18 +159,26 @@ export function splitMirrorText(text: string): string[] {
}
interface ImportMessage {
- sourceId: string; authorId: string; createdAt: string; content: Array<{ type: 'text'; text: string }>;
+ sourceId: string; authorId: string; createdAt: string; content: Array<{ type: string; text?: string; mediaId?: string; caption?: string }>;
}
+/** Room media blocks of uploaded files, in order (chatServerMedia upload). */
+export type CompanionMediaUpload = (roomId: string, source: string, attachments: CompanionMirrorAttachment[], authorId: string) =>
+ Promise<Array<{ type: string; mediaId?: string; caption?: string }>>;
+
export function createCompanionMirror(deps: {
api: CompanionApi;
state: CompanionCloudState;
humanActorId: () => string;
+ /** Null when the companion has no main task yet; throws when it cannot be told, so nothing counts as sent. */
canonicalSession: (botId: string) => Promise<string | null>;
/** Strictly after the cursor, ascending by (createdAt, id); user/assistant rows that were not rewound. */
rowsAfter: (sessionId: string, cursor: CompanionMirrorCursor, limit: number) => Promise<CompanionMirrorRow[]>;
/** Newest first, same filters as rowsAfter. */
latestRows: (sessionId: string, limit: number) => Promise<CompanionMirrorRow[]>;
+ /** Uploads the owner's attachments so other devices can open them; absent keeps name placeholders. */
+ uploadMedia?: CompanionMediaUpload;
+ log?: CompanionLog;
}) {
async function ensureRoom(botId: string, actorId: string, name: string): Promise<string> {
const known = deps.state.bot(botId);
@@ -137,20 +204,41 @@ export function createCompanionMirror(deps: {
*/
async function importRows(botId: string, actorId: string, roomId: string, sessionId: string, rows: CompanionMirrorRow[], advance = true) {
const parts: Array<{ message: ImportMessage; row: number; last: boolean; bytes: number }> = [];
- rows.forEach((row, index) => {
- const text = mirrorMessageText(row);
- if (!text) return;
- const pieces = splitMirrorText(text);
+ for (const [index, row] of rows.entries()) {
+ if (!mirrorMessageText(row)) continue;
+ const sourceId = `cindy:${sessionId}:${row.id}`;
+ const authorId = row.role === 'user' ? deps.humanActorId() : actorId;
+ // The files themselves when they can be uploaded; a file that cannot (too large, gone, an old
+ // 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) : []) {
+ if (file.size > MIRROR_ATTACHMENT_MAX_BYTES) continue;
+ try { media.push(...await deps.uploadMedia!(roomId, sourceId, [file], authorId)); uploaded.push(file.name); }
+ catch (error) {
+ // A file that may still go up stops this pass (the cursor stays), so the retry sends it.
+ if (isTransientAttachmentFailure(error)) throw error;
+ deps.log?.warn('Companion attachment upload skipped; name only', { code: errorCode(error) });
+ }
+ }
+ // Every attachment that did not go up (as listed in the row) keeps its name in the text.
+ const names = attachmentNames(parse(row.content));
+ for (const name of uploaded) { const at = names.indexOf(name); if (at >= 0) names.splice(at, 1); }
+ const text = media.length
+ ? [mirrorMessageText(row, { placeholders: false }) ?? '', ...names.map(name => `[附件: ${name}]`)].filter(Boolean).join('\n')
+ : mirrorMessageText(row) ?? '';
+ const pieces = text ? splitMirrorText(text) : [''];
pieces.forEach((piece, n) => {
+ const last = n === pieces.length - 1;
const message: ImportMessage = {
- sourceId: `cindy:${sessionId}:${row.id}${n ? `:p${n}` : ''}`.slice(0, 200),
- authorId: row.role === 'user' ? deps.humanActorId() : actorId,
+ sourceId: `${sourceId}${n ? `:p${n}` : ''}`.slice(0, 200),
+ authorId,
createdAt: new Date(row.createdAt).toISOString(),
- content: [{ type: 'text', text: piece }],
+ content: [...(piece ? [{ type: 'text', text: piece }] : []), ...(last ? media : [])],
};
- parts.push({ message, row: index, last: n === pieces.length - 1, bytes: Buffer.byteLength(JSON.stringify(message)) });
+ parts.push({ message, row: index, last, bytes: Buffer.byteLength(JSON.stringify(message)) });
});
- });
+ }
const moveTo = (upTo: number) => {
if (!advance) return;
let index = upTo;
@@ -208,6 +296,8 @@ export function createCompanionMirror(deps: {
const from = eligible.length > COMPANION_BACKFILL_LIMIT ? eligible[eligible.length - COMPANION_BACKFILL_LIMIT]! : 0;
if (rows.length) await importRows(botId, actorId, roomId, sessionId, rows.slice(from));
else deps.state.update(botId, actorId, entry => { entry.mirror = { sessionId, createdAt: 0, id: '' }; });
+ // Before a hand-over the older history goes up too: this copy stops mirroring once demoted.
+ if (options.drain) await backfillBot(botId, actorId, roomId, sessionId, true);
return;
}
// Assistant rows are stamped when they start and persisted later, and imported history can
@@ -221,10 +311,39 @@ export function createCompanionMirror(deps: {
let after: CompanionMirrorCursor = { createdAt: cursor.createdAt, id: cursor.id };
for (let page = 0; options.drain || page < MAX_PAGES; page += 1) {
const rows = await deps.rowsAfter(sessionId, after, PAGE);
- if (!rows.length) return;
+ if (!rows.length) break;
await importRows(botId, actorId, roomId, sessionId, rows);
after = rows[rows.length - 1]!;
- if (rows.length < PAGE) return;
+ if (rows.length < PAGE) break;
+ }
+ await backfillBot(botId, actorId, roomId, sessionId, options.drain === true);
+ }
+
+ /**
+ * Upload the Session's history from before the mirror cursor (older conversation, or this
+ * computer's own history from before it took the companion over), oldest first, a bounded
+ * amount per pass. The room dedupes by source id, so rows already there are no-ops; it orders
+ * by arrival, so readers sort by message time.
+ */
+ async function backfillBot(botId: string, actorId: string, roomId: string, sessionId: string, drain: boolean) {
+ const entry = deps.state.bot(botId);
+ const mirror = entry?.mirror;
+ if (!mirror || mirror.sessionId !== sessionId) return;
+ const progress = entry?.backfill?.sessionId === sessionId ? entry.backfill : { sessionId, createdAt: 0, id: '' };
+ if (progress.done) return;
+ const behindMirror = (row: CompanionMirrorRow) => row.createdAt < mirror.createdAt || (row.createdAt === mirror.createdAt && row.id <= mirror.id);
+ let after: CompanionMirrorCursor = { createdAt: progress.createdAt, id: progress.id };
+ for (let page = 0; drain || page < MAX_PAGES; page += 1) {
+ const fetched = await deps.rowsAfter(sessionId, after, PAGE);
+ const rows = fetched.filter(behindMirror);
+ // Rows this computer imported recently are already in the room.
+ const recent = new Set(deps.state.bot(botId)?.mirror?.recent ?? []);
+ const pending = rows.filter(row => !recent.has(row.id));
+ if (pending.length) await importRows(botId, actorId, roomId, sessionId, pending, false);
+ if (rows.length) after = rows[rows.length - 1]!;
+ const done = rows.length < fetched.length || fetched.length < PAGE;
+ deps.state.update(botId, actorId, next => { next.backfill = { sessionId, createdAt: after.createdAt, id: after.id, ...(done ? { done: true } : {}) }; });
+ if (done) return;
}
}
diff --git a/apps/desktop/src/main/companion-cloud/room.ts b/apps/desktop/src/main/companion-cloud/room.ts
index aea7740a7d..6da7c66368 100644
--- a/apps/desktop/src/main/companion-cloud/room.ts
+++ b/apps/desktop/src/main/companion-cloud/room.ts
@@ -11,19 +11,26 @@ export interface CompanionRoomMessage {
deleted?: boolean;
threadRootId?: string | null;
createdAt: string;
- content?: Array<{ type?: string; text?: string; caption?: string; fallback?: string }>;
+ content?: Array<{ type?: string; text?: string; caption?: string; fallback?: string; mediaId?: string }>;
}
const PAGE = 100;
-/** Visible user/assistant text of a room message; null for system rows, threads and deletions. */
+/**
+ * Visible user/assistant text of a room message, with its files; null for system rows, threads
+ * and deletions. Files appear as attachments, not as text.
+ */
export function roomMessageView(message: CompanionRoomMessage, botActorId: string): CompanionTranscriptMessage | null {
if (message.deleted || message.origin === 'system' || message.threadRootId) return null;
- const text = (message.content ?? []).map(block => block.type === 'text' ? block.text ?? ''
- : block.type === 'media' ? `[附件: ${block.caption ?? '文件'}]` : block.fallback ?? '').filter(Boolean).join('\n').trim();
+ const blocks = message.content ?? [];
+ const attachments = blocks.flatMap(block => block.type === 'media' && typeof block.mediaId === 'string' && block.mediaId
+ ? [{ mediaId: block.mediaId, name: (block.caption ?? '').trim() || '文件' }] : []);
+ const text = blocks.map(block => block.type === 'text' ? block.text ?? ''
+ : block.type === 'media' ? (block.mediaId ? '' : `[附件: ${block.caption ?? '文件'}]`) : block.fallback ?? '').filter(Boolean).join('\n').trim();
const createdAt = Date.parse(message.createdAt);
- if (!text || !Number.isFinite(createdAt)) return null;
- return { id: message.id, seq: message.seq, role: message.authorId === botActorId ? 'assistant' : 'user', text, createdAt };
+ if ((!text && !attachments.length) || !Number.isFinite(createdAt)) return null;
+ return { id: message.id, seq: message.seq, role: message.authorId === botActorId ? 'assistant' : 'user', text, createdAt,
+ ...(attachments.length ? { attachments } : {}) };
}
export async function readRoomPage(api: CompanionApi, roomId: string, before?: string): Promise<CompanionRoomMessage[]> {
@@ -41,15 +48,48 @@ export async function readTranscriptPage(api: CompanionApi, roomId: string, botA
return { messages, ...(page.length === PAGE && oldest ? { nextBefore: oldest } : {}) };
}
-/** Latest `limit` visible messages, oldest first. */
-export async function readRecentRoomMessages(api: CompanionApi, roomId: string, botActorId: string, limit: number, maxPages = 5) {
+/** Room pages read at most for the whole conversation (100 messages each). */
+export const ROOM_HISTORY_MAX_PAGES = 500;
+
+/** Message time first: history uploaded later (backfill, merges) arrives after newer messages. */
+export function byMessageTime(a: CompanionTranscriptMessage, b: CompanionTranscriptMessage): number {
+ if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
+ const left = BigInt(a.seq); const right = BigInt(b.seq);
+ return left < right ? -1 : left > right ? 1 : 0;
+}
+
+/** Every visible message of the room (bounded by `maxPages`), in message-time order. */
+/**
+ * The room's messages in message-time order. A view reads at most `ROOM_HISTORY_MAX_PAGES`
+ * pages; `complete` (a take-over or a merge, which treat the result as the whole history) reads
+ * to the very first page and fails rather than return part of it.
+ */
+export async function readAllRoomMessages(api: CompanionApi, roomId: string, botActorId: string,
+ options: { complete?: boolean } = {}) {
const collected: CompanionTranscriptMessage[] = [];
let before: string | undefined;
- for (let page = 0; page < maxPages && collected.length < limit; page += 1) {
+ for (let page = 0; options.complete || page < ROOM_HISTORY_MAX_PAGES; page += 1) {
const result = await readTranscriptPage(api, roomId, botActorId, before);
- collected.unshift(...result.messages);
+ collected.push(...result.messages);
if (!result.nextBefore) break;
+ // Paging must move to older messages; a cursor that does not would read forever.
+ if (before !== undefined && BigInt(result.nextBefore) >= BigInt(before)) throw new Error('ROOM_HISTORY_STALLED');
before = result.nextBefore;
}
- return collected.slice(-limit);
+ return collected.sort(byMessageTime);
+}
+
+const TRANSCRIPT_PAGE = 100;
+
+/**
+ * One display page of the whole conversation in message-time order: the latest messages older
+ * than `before` (a message time in ms). Messages sharing the page's oldest time stay together.
+ */
+export function transcriptPageOf(messages: readonly CompanionTranscriptMessage[], before?: number): CompanionTranscriptPage {
+ let end = messages.length;
+ if (before !== undefined) while (end > 0 && messages[end - 1]!.createdAt >= before) end -= 1;
+ let start = Math.max(0, end - TRANSCRIPT_PAGE);
+ while (start > 0 && messages[start - 1]!.createdAt === messages[start]!.createdAt) start -= 1;
+ const page = messages.slice(start, end);
+ return { messages: page, ...(start > 0 && page.length ? { nextBefore: String(page[0]!.createdAt) } : {}) };
}
diff --git a/apps/desktop/src/main/companion-cloud/runtime.ts b/apps/desktop/src/main/companion-cloud/runtime.ts
index e24ed06e3f..f6f73d341c 100644
--- a/apps/desktop/src/main/companion-cloud/runtime.ts
+++ b/apps/desktop/src/main/companion-cloud/runtime.ts
@@ -4,25 +4,33 @@
* failures are logged and retried, never surfaced to chat.
*/
import type {
+ CompanionCindyCopy,
+ CompanionMergeResult,
+ CompanionTranscriptMessage,
CompanionCloudActionResult,
+ CompanionHomeChoices,
+ CompanionSwitchOptions,
CompanionTranscriptPage,
CompanionTransferTarget,
} from '../../shared/companionCloud.js';
import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';
import { isMobilePlatform } from '@cindy/maker-shared/device-list';
import type { CompanionHomeRegistry } from './homes.js';
-import { materializeCompanion, rebuildPending, type CompanionMaterializeHost, type CompanionMaterializeResult } from './materialize.js';
-import { createCompanionMirror, type CompanionMirrorCursor, type CompanionMirrorRow } from './mirror.js';
-import { readTranscriptPage } from './room.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 { readAllRoomMessages, transcriptPageOf } from './room.js';
+import { isCindyCompanion, mergeCompanionsInto, readProfileSnapshot } from './merge.js';
+import { importCloudHistory } from './materialize.js';
import type { CompanionCloudState } from './state.js';
-import { chatRejection, errorCode, type CompanionApi, type CompanionLog } from './types.js';
-import { COMPANION_PROFILE_KEY, COMPANION_VALUE_TOO_LARGE, createCompanionUploader, isCompanionProfileSnapshot, type CompanionPreferenceValue } from './uploader.js';
+import { chatRejection, errorCode, isUnreachable, type CompanionApi, type CompanionLog } from './types.js';
+import { COMPANION_PROFILE_KEY, COMPANION_READ_INCOMPLETE, COMPANION_VALUE_TOO_LARGE, createCompanionUploader, isCompanionProfileSnapshot, type CompanionPreferenceValue } from './uploader.js';
/** Electron/database side of the feature, wired in register.ts. */
export interface CompanionCloudHost {
homes: CompanionHomeRegistry;
openState: (endpoint: string, humanActorId: string, current: () => boolean) => CompanionCloudState;
readValues: (botId: string) => Promise<CompanionPreferenceValue[]>;
+ /** 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[]>;
latestRows: (sessionId: string, limit: number, options?: { excludeClientIdPrefix?: string }) => Promise<CompanionMirrorRow[]>;
@@ -36,6 +44,21 @@ export interface CompanionCloudHost {
listDevices?: () => Promise<DeviceLinkDeviceView[]>;
/** Does that computer's Cindy support cloud companions (`maker:companion-cloud:caps`)? */
probeCompanionCloud?: (deviceId: string) => Promise<boolean>;
+ /**
+ * Ask a companion's home on another computer (device-link): its cloud-companion version (0 when
+ * it cannot be reached), the computers it can hand the companion to, and the hand-over itself.
+ */
+ homeLink?: {
+ version: (deviceId: string) => Promise<number>;
+ targets: (deviceId: string) => Promise<CompanionTransferTarget[]>;
+ handOver: (deviceId: string, botId: string, targetDeviceId: string, options?: CompanionSwitchOptions) => Promise<CompanionCloudActionResult>;
+ /** Ask the kept Cindy's home to merge the other copies into it. */
+ merge?: (deviceId: string, keepBotId: string, fromBotIds: string[]) => Promise<CompanionMergeResult>;
+ /** Ask a copy's home to send everything it has not sent yet (before a merge reads the cloud). */
+ flush?: (deviceId: string, botId: string) => Promise<CompanionCloudActionResult>;
+ };
+ /** Stop every running or queued turn of the companion (its main task, group lanes, delegations). */
+ stopBotTurns?: (botId: string) => Promise<void>;
/** A turn is running (or queued) in any of the companion's tasks (main task, group lanes, delegations). */
isBotBusy?: (botId: string) => Promise<boolean>;
/** Random id of this Cindy installation (per userData); absent disables the install guard. */
@@ -63,9 +86,23 @@ export interface CompanionCloudRuntime {
/** Demote local copies homed elsewhere and materialize companions handed to this computer. */
reconcile: (localProfiles: Array<{ id: string; status: string }>) => void;
takeOver: (botId: string) => Promise<CompanionCloudActionResult>;
- transfer: (botId: string, targetDeviceId: string) => Promise<CompanionCloudActionResult>;
+ transfer: (botId: string, targetDeviceId: string, options?: CompanionSwitchOptions) => Promise<CompanionCloudActionResult>;
transferTargets: () => Promise<CompanionTransferTarget[]>;
+ /** Where the companion can move, seen from this computer (any computer, not only its home). */
+ homeChoices: (botId: string) => Promise<CompanionHomeChoices>;
+ /** Move the companion to `targetDeviceId` from any computer: hand over here, ask its home, or take over. */
+ switchHome: (botId: string, targetDeviceId: string, options?: CompanionSwitchOptions) => Promise<CompanionCloudActionResult>;
transcript: (botId: string, before?: string) => Promise<CompanionTranscriptPage>;
+ /** The copies of Cindy in the cloud when there is more than one (otherwise empty). */
+ cindyCopies: () => Promise<CompanionCindyCopy[]>;
+ /** Merge the other copies into `keepBotId`, on its home (here, or asked over device-link). */
+ mergeCindy: (keepBotId: string, fromBotIds: string[]) => Promise<CompanionMergeResult>;
+ /** The same merge, asked by another computer: only when this computer runs the kept copy. */
+ 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>;
+ /** 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). */
retire: (botId: string) => Promise<void>;
/** Demoted here, or homed on this device but owned by another Cindy installation. */
@@ -93,15 +130,7 @@ type Only = Set<string> | null | undefined;
const union = (left: Only, right: Set<string> | null): Only =>
left === null || right === null ? null : new Set([...(left ?? []), ...right]);
-const TRANSPORT_CODES = /^(REQUEST_TIMEOUT|CHAT_ENDPOINT_UNAVAILABLE|ECONN\w*|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|EPIPE)$/;
-/** The server could not be reached (or is temporarily failing): retry later. */
-export function isUnreachable(error: unknown): boolean {
- if (!(error instanceof Error)) return false;
- const status = (error as { status?: unknown }).status;
- if (typeof status === 'number') return status >= 500 || status === 408 || status === 429;
- const code = (error as { code?: unknown }).code;
- return TRANSPORT_CODES.test(error.message) || (typeof code === 'string' && TRANSPORT_CODES.test(code));
-}
+export { isUnreachable };
function actionFailure(error: unknown, fallback: 'FAILED' | 'OFFLINE' = 'FAILED'): CompanionCloudActionResult {
const conflict = chatRejection(error, 409, 'HOME_DEVICE_CONFLICT');
@@ -110,6 +139,18 @@ function actionFailure(error: unknown, fallback: 'FAILED' | 'OFFLINE' = 'FAILED'
}
const AUTO_RETRY_MS = 60_000;
+/** How long a whole room read serves "load older" in the cloud conversation view. */
+const TRANSCRIPT_CACHE_MS = 5 * 60_000;
+/** How long a companion's profile snapshot answers "is this a copy of Cindy". */
+const PROFILE_CACHE_MS = 5 * 60_000;
+
+/** Home versions that accept a hand-over request from another computer (device-link caps). */
+const REMOTE_HAND_OVER_VERSION = 2;
+/** How long a move waits for the companion to finish its turn (the device-link budget is larger). */
+export const COMPANION_BUSY_WAIT_MS = 4 * 60_000;
+/** After asking the turn to stop, how long it may take to settle. */
+const COMPANION_STOP_SETTLE_MS = 30_000;
+const BUSY_POLL_MS = 2_000;
/** The home has uploaded the profile snapshot a take-over builds the companion from. */
export function hasProfileSnapshot(rows: unknown): boolean {
@@ -131,6 +172,8 @@ export function startCompanionCloud(input: {
current: () => boolean;
/** Active local companions whose home is this computer (and not demoted). */
bots: () => CompanionCloudBot[];
+ /** A local companion the owner paused: not synced or moved, and a merge asks to resume it first. */
+ paused?: (botId: string) => boolean;
/** The account's actors as last read by register(). */
actors?: () => CompanionRuntimeActor[];
/** Re-read actors now (forced register). */
@@ -139,6 +182,8 @@ export function startCompanionCloud(input: {
publish?: () => void;
/** Publish the companions' actor name and avatar now (they sync outside the preferences). */
syncProfile?: (botId: string) => Promise<void>;
+ /** Room files (chatServerMedia): the mirror uploads the owner's attachments; readers download them. */
+ media?: { upload: CompanionMediaUpload; download: CompanionRoomDownload };
log?: CompanionLog;
uploadIntervalMs?: number;
mirrorIntervalMs?: number;
@@ -154,7 +199,8 @@ export function startCompanionCloud(input: {
onLostHome: () => { void input.refresh?.().catch(() => undefined); },
});
const mirror = createCompanionMirror({ api: input.api, state, humanActorId: () => input.humanActorId,
- canonicalSession: input.host.canonicalSession, rowsAfter: input.host.rowsAfter, latestRows: input.host.latestRows });
+ canonicalSession: input.host.canonicalSession, rowsAfter: input.host.rowsAfter, latestRows: input.host.latestRows,
+ ...(input.media ? { uploadMedia: input.media.upload } : {}), ...(input.log ? { log: input.log } : {}) });
let disposed = false;
const live = () => !disposed && input.current();
const aborts = new AbortController();
@@ -231,6 +277,76 @@ export function startCompanionCloud(input: {
}, input.mirrorIntervalMs ?? 15_000, 2_000);
const unsubscribe = input.host.onLocalChange?.(botId => { mirrors.kick(botId); uploads.kick(botId); });
+ /** Profile snapshots of companion actors (to find the copies of Cindy), read at most every few minutes. */
+ const profiles = new Map<string, { at: number; value: unknown }>();
+ const profileOf = async (actorId: string) => {
+ const cached = profiles.get(actorId);
+ if (cached && Date.now() - cached.at < PROFILE_CACHE_MS) return cached.value;
+ const value = await readProfileSnapshot(input.api, actorId);
+ profiles.set(actorId, { at: Date.now(), value });
+ return value;
+ };
+
+ /** Merge here (this computer runs the kept copy). */
+ async function mergeHere(keepBotId: string, fromBotIds: string[]): Promise<CompanionMergeResult> {
+ // A paused copy (kept or merged) is not synced: say so instead of failing part way.
+ if (input.paused?.(keepBotId)) return { ok: false, code: 'PAUSED' };
+ const keep = pick(null).find(bot => bot.botId === keepBotId);
+ const keepActor = actorOf(keepBotId);
+ const materializer = input.host.materializer;
+ if (!keep || !keepActor || !materializer) return { ok: false, code: 'FAILED' };
+ const copies = await runtime.cindyCopies();
+ const from = fromBotIds.flatMap(botId => {
+ const actor = actorOf(botId);
+ return actor && botId !== keepBotId && copies.some(copy => copy.botId === botId) ? [actor] : [];
+ });
+ if (!from.length || !copies.some(copy => copy.botId === keepBotId)) return { ok: false, code: 'FAILED' };
+ const roomOf = (actor: { id: string; externalId: string; name: string }) => mirror.ensureRoom(actor.externalId, actor.id, actor.name);
+ // The merge reads the cloud: each copy's own computer first sends what it has not sent yet
+ // (conversation backlog, a memory just edited). A busy copy waits; a failed sync stops the merge.
+ for (const actor of from) {
+ const synced = await syncCopy(actor);
+ if (!synced.ok) return synced as CompanionMergeResult;
+ }
+ const devices = await input.host.listDevices?.().catch(() => []) ?? [];
+ const labelled = from.map(actor => ({ ...actor, label: devices.find(device => device.deviceId === actor.homeDeviceId)?.name?.trim() || '' }));
+ try {
+ const summary = await mergeCompanionsInto({ api: input.api, host: materializer, keep: keepActor, from: labelled, humanActorId: input.humanActorId,
+ roomOf, fence, ...(input.media ? { media: input.media } : {}), ...(input.log ? { log: input.log } : {}),
+ beforeRetire: async () => {
+ for (const actor of from) {
+ const synced = await syncCopy(actor);
+ if (!synced.ok) throw Object.assign(new Error(synced.code), { companionResult: synced });
+ }
+ },
+ importHistory: async () => {
+ // Without its task here the merged conversation would never reach the kept Cindy: fail,
+ // so the copies stay active and the merge can run again.
+ const sessionId = await input.host.canonicalSession(keepBotId);
+ if (!sessionId) throw new Error('COMPANION_TASK_UNAVAILABLE');
+ const inserted = await importCloudHistory({ api: input.api, host: materializer, sessionId, botActorId: keepActor.id,
+ roomId: await roomOf(keepActor), fence, ...(input.media ? { download: input.media.download } : {}), ...(input.log ? { log: input.log } : {}) });
+ // The merged conversation becomes the companion's context at its next idle point.
+ if (inserted > 0) state.update(keepBotId, keepActor.id, entry => { entry.pendingRebuild = true; });
+ } });
+ for (const actor of from) actor.disabled = true;
+ input.log?.info?.('Copies of Cindy merged', { actorId: keepActor.id, merged: summary.merged, messages: summary.messages });
+ await input.refresh?.().catch(() => undefined);
+ publish(); mirrors.kick(keepBotId); uploads.kick(keepBotId);
+ return { ok: true, ...summary };
+ } catch (error) {
+ input.log?.warn('Merging copies of Cindy will need another try', { code: errorCode(error) });
+ await input.refresh?.().catch(() => undefined);
+ publish();
+ // A copy that got busy (or could not send) right before retiring: say why, as before the merge.
+ const settled = (error as { companionResult?: CompanionCloudActionResult } | null)?.companionResult;
+ return (settled ?? actionFailure(error)) as CompanionMergeResult;
+ }
+ }
+
+ /** The last whole read of each room for the cloud conversation view. */
+ const transcripts = new Map<string, { at: number; messages: CompanionTranscriptMessage[] }>();
+
// One materialize per companion at a time; take-over and automatic runs share it.
const materializing = new Map<string, Promise<CompanionMaterializeResult>>();
const autoRetryAt = new Map<string, number>();
@@ -241,6 +357,7 @@ export function startCompanionCloud(input: {
const pending = materializing.get(botId);
if (pending) return pending;
const run = materializeCompanion({ api: input.api, state, log: input.log, fence, onDemoted: publish, host: { ...materializer, latestRows: input.host.latestRows },
+ ...(input.media ? { download: input.media.download } : {}),
actor: { id: actor.id, externalId: botId, name: actor.name, avatar: actor.avatar ?? null },
roomId: () => mirror.ensureRoom(botId, actor.id, actor.name) })
.finally(() => { materializing.delete(botId); });
@@ -362,14 +479,73 @@ export function startCompanionCloud(input: {
// The whole conversation backlog first: the old copy stops mirroring once demoted, and a long
// drain must not leave edits made meanwhile behind.
await mirror.syncBot(bot.botId, bot.actorId, bot.name, { drain: true });
+ // The actor's name and avatar too (once demoted, this copy may no longer publish them). Before
+ // the values: an avatar upload takes a while, and an edit made meanwhile must still go up.
+ await input.syncProfile?.(bot.botId);
// Every portable value must reach the server: a skipped one would be lost by the move. Repeat
- // until a pass writes nothing, so the move starts from what is on disk right now.
+ // until a pass writes nothing, so the move starts from what is on disk right now; that last pass
+ // is the last await before the busy check and the move.
for (let pass = 0; ; pass += 1) {
if (await uploader.syncBot(bot.botId, bot.actorId, Number.POSITIVE_INFINITY, { requireAll: true }) === 0) break;
if (pass >= 2) throw new Error('COMPANION_STILL_CHANGING');
}
- // The actor's name and avatar too: once demoted, this copy may no longer publish them.
- await input.syncProfile?.(bot.botId);
+ }
+
+ /** A sync that must be complete (a hand-over, a merge) did not finish: why, as an action result. */
+ function syncFailure(error: unknown): CompanionCloudActionResult {
+ const code = errorCode(error);
+ return [COMPANION_VALUE_TOO_LARGE, COMPANION_READ_INCOMPLETE, 'COMPANION_STILL_CHANGING', 'INVALID_AVATAR', 'AVATAR_UPLOAD_FAILED'].includes(code)
+ ? { ok: false, code: 'FAILED' } : actionFailure(error, 'OFFLINE');
+ }
+
+ /** Everything of a companion homed here reaches the server, without moving it. */
+ async function flushOwn(botId: string): Promise<CompanionCloudActionResult> {
+ if (!input.selfDeviceId || actorOf(botId)?.homeDeviceId !== input.selfDeviceId) return { ok: false, code: 'HOME_CONFLICT' };
+ if (input.paused?.(botId)) return { ok: false, code: 'PAUSED' };
+ if (await input.host.isBotBusy?.(botId)) return { ok: false, code: 'BUSY' };
+ try {
+ await flush(botId);
+ // A turn that started during the flush keeps producing: not settled yet (as before a hand-over).
+ if (await input.host.isBotBusy?.(botId)) return { ok: false, code: 'BUSY' };
+ return { ok: true };
+ }
+ catch (error) {
+ input.log?.warn('Companion sync before a merge did not finish', { code: errorCode(error) });
+ return syncFailure(error);
+ }
+ }
+
+ /**
+ * A copy about to be merged: its home sends what it has not sent yet. A home that cannot be
+ * reached (or predates the request) keeps the rest on that computer; the cloud has what it last sent.
+ */
+ async function syncCopy(actor: CompanionRuntimeActor): Promise<CompanionCloudActionResult> {
+ const home = actor.homeDeviceId;
+ if (!home) return { ok: true };
+ if (home === input.selfDeviceId) return flushOwn(actor.externalId);
+ const link = input.host.homeLink;
+ if (!link?.flush) return { ok: true };
+ const version = await link.version(home).catch(() => 0);
+ if (version < REMOTE_HAND_OVER_VERSION) return { ok: true };
+ try { return await link.flush(home, actor.externalId); }
+ catch (error) { return actionFailure(error, 'OFFLINE'); }
+ }
+
+ /** True once the companion has no running or queued turn; `wait` / `stop` give it time to get there. */
+ async function settleBusy(botId: string, whenBusy: CompanionSwitchOptions['whenBusy']): Promise<boolean> {
+ const busy = async () => !!(await input.host.isBotBusy?.(botId));
+ if (!(await busy())) return true;
+ if (!whenBusy) return false;
+ if (whenBusy === 'stop') await input.host.stopBotTurns?.(botId).catch(error => {
+ input.log?.warn('Companion turns could not be stopped before a move', { code: errorCode(error) });
+ });
+ const deadline = Date.now() + (whenBusy === 'stop' ? COMPANION_STOP_SETTLE_MS : COMPANION_BUSY_WAIT_MS);
+ while (Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, BUSY_POLL_MS));
+ if (!live()) return false;
+ if (!(await busy())) return true;
+ }
+ return false;
}
/** Everything the new home needs reaches the server, then the home moves and this copy is demoted. */
@@ -380,9 +556,7 @@ export function startCompanionCloud(input: {
try { await flush(actor.externalId); }
catch (error) {
input.log?.warn('Companion hand-over stopped: sync did not finish', { actorId: actor.id, code: errorCode(error) });
- const code = errorCode(error);
- return [COMPANION_VALUE_TOO_LARGE, 'COMPANION_STILL_CHANGING', 'INVALID_AVATAR', 'AVATAR_UPLOAD_FAILED'].includes(code)
- ? { ok: false, code: 'FAILED' } : actionFailure(error, 'OFFLINE');
+ return syncFailure(error);
}
// Checked again right before the move: a turn may have started during the flush.
if (await turnActive()) return { ok: false, code: 'BUSY' };
@@ -502,7 +676,7 @@ export function startCompanionCloud(input: {
.map(device => ({ deviceId: device.deviceId, name: device.name, online: device.online }));
},
- async transfer(botId, targetDeviceId) {
+ async transfer(botId, targetDeviceId, options) {
const self = input.selfDeviceId;
if (!self || !live()) return { ok: false, code: 'NOT_ENABLED' };
const actor = actorOf(botId);
@@ -513,17 +687,125 @@ export function startCompanionCloud(input: {
if (!target || (probe && !(await probe(targetDeviceId).catch(() => false)))) return { ok: false, code: 'TARGET_UNAVAILABLE' };
// No background cycle may write in between: one already in flight could carry older values
// past the flush, or past the move. Background sync resumes after the copy is demoted.
+ // Still working: wait for (or stop) the turn first, outside the sync lock so its reply keeps syncing.
+ if (!(await settleBusy(actor.externalId, options?.whenBusy))) return { ok: false, code: 'BUSY' };
return mirrors.exclusive(() => uploads.exclusive(() => handOver(actor, targetDeviceId)));
},
+ async homeChoices(botId) {
+ const self = input.selfDeviceId;
+ const actor = actorOf(botId);
+ const home = actor?.homeDeviceId ?? null;
+ if (!self || !live()) return { homeDeviceId: home, mode: 'unavailable', reason: 'NOT_ENABLED', targets: [] };
+ if (!actor) return { homeDeviceId: null, mode: 'unavailable', reason: 'NOT_FOUND', targets: [] };
+ const devices = await input.host.listDevices?.().catch(() => []) ?? [];
+ const homeName = (home && devices.find(device => device.deviceId === home)?.name) || '';
+ if (home === self) return { homeDeviceId: home, homeName, mode: 'local', targets: await runtime.transferTargets() };
+ const selfDevice = devices.find(device => device.deviceId === self);
+ const here: CompanionTransferTarget = { deviceId: self, name: selfDevice?.name ?? '', online: true, isSelf: true };
+ const homeDevice = home ? devices.find(device => device.deviceId === home) : undefined;
+ // Unreachable home (offline, or not controllable from here): only this computer can continue it.
+ const version = home && homeDevice?.online && input.host.homeLink
+ ? await input.host.homeLink.version(home).catch(() => 0) : 0;
+ if (!home || version === 0) return { homeDeviceId: home, homeName, mode: 'takeOver', targets: [here] };
+ if (version < REMOTE_HAND_OVER_VERSION) return { homeDeviceId: home, homeName, mode: 'unavailable', reason: 'HOME_OUTDATED', targets: [] };
+ // The home's own view: it decides which computers can receive the companion (this one included).
+ const targets = await input.host.homeLink!.targets(home);
+ return { homeDeviceId: home, homeName, mode: 'remote',
+ targets: targets.filter(target => target.deviceId !== home).map(target => target.deviceId === self
+ ? { ...target, name: target.name || here.name, isSelf: true } : { ...target, isSelf: false }) };
+ },
+
+ async switchHome(botId, targetDeviceId, options) {
+ const self = input.selfDeviceId;
+ if (!self || !live()) return { ok: false, code: 'NOT_ENABLED' };
+ const choices = await runtime.homeChoices(botId);
+ if (choices.homeDeviceId === targetDeviceId) return { ok: true };
+ if (choices.mode === 'unavailable') return { ok: false, code: choices.reason === 'HOME_OUTDATED' ? 'HOME_OUTDATED' : 'FAILED' };
+ if (!choices.targets.some(target => target.deviceId === targetDeviceId)) return { ok: false, code: 'TARGET_UNAVAILABLE' };
+ if (choices.mode === 'local') return runtime.transfer(botId, targetDeviceId, options);
+ if (choices.mode === 'takeOver') return runtime.takeOver(botId);
+ // The home hands it over itself (flush, busy check, compare-and-set), exactly as from its own settings.
+ let result: CompanionCloudActionResult;
+ try { result = await input.host.homeLink!.handOver(choices.homeDeviceId!, botId, targetDeviceId, options); }
+ catch (error) {
+ // A lost answer may still have moved it: show where it runs now.
+ await input.refresh?.().catch(() => undefined);
+ publish();
+ return actionFailure(error, 'OFFLINE');
+ }
+ // Moved here: re-read homes now so the automatic take-over starts without waiting for the push.
+ if (result.ok || result.code === 'HOME_CONFLICT') await input.refresh?.().catch(() => undefined);
+ publish();
+ return result;
+ },
+
async transcript(botId, before) {
const actor = actorOf(botId);
if (!actor) throw new Error('COMPANION_NOT_FOUND');
const roomId = await mirror.ensureRoom(actor.externalId, actor.id, actor.name);
- return readTranscriptPage(input.api, roomId, actor.id, before);
+ // The room orders by arrival (older history may be uploaded later): read it whole, show it
+ // by message time. The first page re-reads; older pages reuse that read.
+ const cached = transcripts.get(roomId);
+ const messages = before && cached && Date.now() - cached.at < TRANSCRIPT_CACHE_MS ? cached.messages
+ : await readAllRoomMessages(input.api, roomId, actor.id);
+ transcripts.set(roomId, { at: Date.now(), messages });
+ return transcriptPageOf(messages, before ? Number(before) : undefined);
},
+ async cindyCopies() {
+ if (!live()) return [];
+ const copies: CompanionCindyCopy[] = [];
+ for (const actor of input.actors?.() ?? []) {
+ if (actor.kind !== 'bot' || actor.disabled) continue;
+ const profile = await profileOf(actor.id).catch(() => null);
+ if (isCindyCompanion(actor.externalId, profile)) copies.push({ botId: actor.externalId, name: actor.name, homeDeviceId: actor.homeDeviceId ?? null });
+ }
+ return copies.length > 1 ? copies : [];
+ },
+
+ async mergeCindy(keepBotId, fromBotIds) {
+ const self = input.selfDeviceId;
+ if (!self || !live()) return { ok: false, code: 'NOT_ENABLED' };
+ const keep = actorOf(keepBotId);
+ if (!keep?.homeDeviceId) return { ok: false, code: 'FAILED' };
+ if (keep.homeDeviceId === self) return mergeHere(keepBotId, fromBotIds);
+ // The kept copy runs elsewhere: its home merges (it writes the companion's files).
+ const link = input.host.homeLink;
+ if (!link?.merge) return { ok: false, code: 'HOME_OUTDATED' };
+ const version = await link.version(keep.homeDeviceId).catch(() => 0);
+ if (version === 0) return { ok: false, code: 'OFFLINE' };
+ if (version < REMOTE_HAND_OVER_VERSION) return { ok: false, code: 'HOME_OUTDATED' };
+ try {
+ const result = await link.merge(keep.homeDeviceId, keepBotId, fromBotIds);
+ await input.refresh?.().catch(() => undefined);
+ publish();
+ return result;
+ } catch (error) {
+ await input.refresh?.().catch(() => undefined);
+ return actionFailure(error, 'OFFLINE') as CompanionMergeResult;
+ }
+ },
+
+ async mergeCindyHere(keepBotId, fromBotIds) {
+ if (!input.selfDeviceId || !live()) return { ok: false, code: 'NOT_ENABLED' };
+ if (actorOf(keepBotId)?.homeDeviceId !== input.selfDeviceId) return { ok: false, code: 'HOME_CONFLICT' };
+ return mergeHere(keepBotId, fromBotIds);
+ },
+
+ async flushHere(botId) {
+ if (!input.selfDeviceId || !live()) return { ok: false, code: 'NOT_ENABLED' };
+ return flushOwn(botId);
+ },
+
+ async attachment(botId, mediaId) {
+ const actor = actorOf(botId);
+ if (!actor || !input.media) throw new Error('COMPANION_NOT_FOUND');
+ const roomId = await mirror.ensureRoom(actor.externalId, actor.id, actor.name);
+ return input.media.download(roomId, mediaId);
+ },
+
async retire(botId) {
const self = input.selfDeviceId;
const actor = actorOf(botId);
diff --git a/apps/desktop/src/main/companion-cloud/state.ts b/apps/desktop/src/main/companion-cloud/state.ts
index d15dda5b56..6a33287e4b 100644
--- a/apps/desktop/src/main/companion-cloud/state.ts
+++ b/apps/desktop/src/main/companion-cloud/state.ts
@@ -26,6 +26,12 @@ const bot = z.object({
/** Recently imported local message ids, so the trailing re-scan does not re-send them. */
recent: z.array(z.string()).optional(),
}).optional(),
+ /**
+ * Older history of the Session (before the mirror cursor) uploaded so far, so the room holds the
+ * whole conversation, not only what happened since mirroring began. Rows strictly after it, up to
+ * the mirror cursor, are still to go; `done` once it reached the cursor.
+ */
+ backfill: z.object({ sessionId: z.string(), createdAt: z.number(), id: z.string(), done: z.boolean().optional() }).optional(),
prefs: z.record(z.string(), pref).default({}),
/** Revisions were read back from the server once (after a fresh or lost state file). */
prefsSeeded: z.boolean().optional(),
diff --git a/apps/desktop/src/main/companion-cloud/travel.ts b/apps/desktop/src/main/companion-cloud/travel.ts
new file mode 100644
index 0000000000..7b0199e3dc
--- /dev/null
+++ b/apps/desktop/src/main/companion-cloud/travel.ts
@@ -0,0 +1,18 @@
+/** What of a companion's todos moves with it to another computer (cloud-companions.md §2). */
+import type { TeammateTodo } from '@cindy/maker-shared/teammate-todo';
+
+/** Todos that travel: open ones, ones set aside for later, and those closed in the last month. */
+const TODO_RECENT_MS = 30 * 24 * 60 * 60_000;
+const TODO_MAX = 500;
+const TODO_HISTORY = 20;
+
+/** A todo as it travels: no delivery in flight (it belongs to this computer's queue), bounded history. */
+export function portableTodo(item: TeammateTodo): Record<string, unknown> {
+ const { action: _action, legacyId: _legacyId, legacyFingerprint: _fingerprint, legacyVerdict: _verdict, ...rest } = item;
+ return { ...rest, action: null, history: item.history.slice(-TODO_HISTORY) };
+}
+
+export function travellingTodos(items: readonly TeammateTodo[], now = Date.now()): TeammateTodo[] {
+ return items.filter((item) => item.status === 'open' || item.decision?.kind === 'later' || now - Date.parse(item.updatedAt) < TODO_RECENT_MS)
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, TODO_MAX);
+}
diff --git a/apps/desktop/src/main/companion-cloud/types.ts b/apps/desktop/src/main/companion-cloud/types.ts
index 9f10bfa820..2b47a91da3 100644
--- a/apps/desktop/src/main/companion-cloud/types.ts
+++ b/apps/desktop/src/main/companion-cloud/types.ts
@@ -21,3 +21,32 @@ export function chatRejection(error: unknown, status: number, code: string): Rec
export function errorCode(error: unknown): string {
return error instanceof Error ? error.message.slice(0, 80) : 'UNKNOWN';
}
+
+const TRANSPORT_CODES = /^(REQUEST_TIMEOUT|CHAT_ENDPOINT_UNAVAILABLE|ECONN\w*|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|EPIPE)$/;
+/** The server could not be reached (or is temporarily failing): retry later. */
+export function isUnreachable(error: unknown): boolean {
+ if (!(error instanceof Error)) return false;
+ const status = (error as { status?: unknown }).status;
+ if (typeof status === 'number') return status >= 500 || status === 408 || status === 429;
+ const code = (error as { code?: unknown }).code;
+ return TRANSPORT_CODES.test(error.message) || (typeof code === 'string' && TRANSPORT_CODES.test(code));
+}
+
+const TRANSIENT_ATTACHMENT = /^(MEDIA_DOWNLOAD_FAILED|OWNER_CHANGED|fetch failed|net::ERR_\w+)$/;
+/** The object store's own answer to a signed address (every try signs a fresh one). */
+const SIGNED_URL_FAILURE = /^MEDIA_(UPLOAD|DOWNLOAD)_FAILED$/;
+/**
+ * A file that may still come on a later try (network, a failing server or 5xx/408/429, an expired
+ * signed address, a download that ended without a status, the account changing): the step fails
+ * and is retried. Anything else (too large, gone, refused by the chat server) never will, and only
+ * then does the file stay a name.
+ */
+export function isTransientAttachmentFailure(error: unknown): boolean {
+ if (isUnreachable(error)) return true;
+ if (!(error instanceof Error)) return false;
+ const status = (error as { status?: unknown }).status;
+ // An expired signature (401/403 from the object store) is signed again on the retry; the chat
+ // server refusing the file, or the object being gone (404), never changes.
+ if (typeof status === 'number') return SIGNED_URL_FAILURE.test(error.message) && (status === 401 || status === 403);
+ return TRANSIENT_ATTACHMENT.test(error.message) || error.name === 'TimeoutError' || error.name === 'AbortError';
+}
diff --git a/apps/desktop/src/main/companion-cloud/uploader.ts b/apps/desktop/src/main/companion-cloud/uploader.ts
index 0bcfdadaad..63dfad7274 100644
--- a/apps/desktop/src/main/companion-cloud/uploader.ts
+++ b/apps/desktop/src/main/companion-cloud/uploader.ts
@@ -10,13 +10,27 @@ import { chatRejection, errorCode, type CompanionApi, type CompanionLog } from '
export const COMPANION_PROFILE_KEY = 'companion.profile.v1';
export const COMPANION_MEMORY_PREFIX = 'companion.memory.v1:';
export const COMPANION_SKILL_PREFIX = 'companion.skill.v1:';
-const OWNED_PREFIXES = [COMPANION_PROFILE_KEY, COMPANION_MEMORY_PREFIX, COMPANION_SKILL_PREFIX];
+/** One open (or recently closed) todo per key; the whole file would not fit one value. */
+export const COMPANION_TODO_PREFIX = 'companion.todo.v1:';
+/** One routine definition per key (run history stays on the computer it ran on). */
+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';
+const OWNED_PREFIXES = [COMPANION_PROFILE_KEY, COMPANION_MEMORY_PREFIX, COMPANION_SKILL_PREFIX,
+ COMPANION_TODO_PREFIX, COMPANION_ROUTINE_PREFIX, COMPANION_WORKBENCH_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). */
export const COMPANION_VALUE_TOO_LARGE = 'COMPANION_VALUE_TOO_LARGE';
-export interface CompanionPreferenceValue { key: string; value: unknown }
+/**
+ * One value to upload. `unread` marks a key prefix that could not be read this cycle (e.g. the
+ * routine engine is not ready): its server values stay as they are and nothing under it is
+ * tombstoned; a hand-over, which needs everything, fails instead.
+ */
+export interface CompanionPreferenceValue { key: string; value: unknown; unread?: boolean }
+/** A required part of the companion could not be read: the hand-over waits for the next try. */
+export const COMPANION_READ_INCOMPLETE = 'COMPANION_READ_INCOMPLETE';
const PROFILE_FIELDS = ['name', 'description', 'soul', 'systemPrompt', 'user'] as const;
export type CompanionProfileSnapshot = Record<(typeof PROFILE_FIELDS)[number], string>;
@@ -107,12 +121,17 @@ export function createCompanionUploader(deps: {
*/
async function syncBot(botId: string, actorId: string, budget = Number.POSITIVE_INFINITY,
options: { requireAll?: boolean } = {}): Promise<number> {
- const values = await deps.readValues(botId);
+ const read = await deps.readValues(botId);
+ const unread = read.filter(entry => entry.unread).map(entry => entry.key);
+ if (unread.length && options.requireAll) throw new Error(COMPANION_READ_INCOMPLETE);
+ const values = read.filter(entry => !entry.unread);
if (deps.state.bot(botId)?.actorId !== actorId || !deps.state.bot(botId)?.prefsSeeded) await seed(botId, actorId);
const desired = new Map<string, unknown>();
for (const { key, value } of values) desired.set(key, value);
- // Only keys this device itself had are tombstoned; never what merely exists on the server.
+ // Only keys this device itself had are tombstoned; never what merely exists on the server,
+ // nor anything under a part that could not be read this time.
for (const [key, entry] of Object.entries(deps.state.bot(botId)?.prefs ?? {})) {
+ if (unread.some(prefix => key.startsWith(prefix))) continue;
if (!desired.has(key) && entry.local && entry.hash !== TOMBSTONE_HASH) desired.set(key, null);
}
let writes = 0;
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 0faae1cd56..182c4d0f04 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -2209,12 +2209,14 @@ export function registerBotIpc(): void {
owner.assertCurrent();
return result;
});
- ipcMain.handle('local-db:bots:workbench:remove-directory', async (event, rawBotId: unknown, rawPath: unknown) => {
+ ipcMain.handle('local-db:bots:workbench:remove-directory', async (event, rawBotId: unknown, rawPath: unknown, rawDeviceId: unknown) => {
assertTrustedAppRendererEvent(event);
const botId = readText(rawBotId, 'botId', 128, true);
const dirPath = readText(rawPath, 'path', 4096, true);
+ // A folder on another computer (cloud companions) is named by that computer too.
+ const deviceId = readText(rawDeviceId, 'deviceId', 200) || undefined;
const owner = captureBotOperationOwner();
- await removeBotWorkbenchDirectory(owner.userDataDir, botId, dirPath);
+ await removeBotWorkbenchDirectory(owner.userDataDir, botId, dirPath, deviceId);
owner.assertCurrent();
broadcastBotWorkbenchChanged(botId);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
index 873df633bb..0c560fefa0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
@@ -347,6 +347,13 @@ describe('helper task workspace and SkillHub publication authorization', () => {
expect(getDesktopClaudeReadOnlyAllowedTools()).not.toContain('mcp__cindy_helper__call_tool');
});
+ it('lets the task permission mode decide moving a teammate to another computer, but not reading its home', () => {
+ const move = { name: 'move_teammate_home', args: { teammate_id: 'mia', target_device_id: 'laptop' } };
+ expect(policy('call_tool', move)).toBe('prompt-each-time');
+ expect(policy('move_teammate_home', move.args)).toBe('prompt-each-time');
+ expect(policy('call_tool', { name: 'get_teammate_home', args: { teammate_id: 'mia' } })).not.toBe('prompt-each-time');
+ });
+
it('does not infer a safe helper action from missing or malformed evidence', () => {
for (const params of [undefined, null, [], 'invalid JSON', {}, { name: '' }, { name: 42 }]) {
expect(policy('call_tool', params)).toBe('prompt-each-time');
diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
index 2f8b4ce087..8ab482f490 100644
--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
@@ -231,6 +231,8 @@ export function getDesktopMcpToolApprovalPolicy(
return 'prompt-each-time';
}
if (action === 'move_session' || action === 'publish_skill') return 'prompt-each-time';
+ // Moving a teammate hands its running to another computer: the task's permission mode decides.
+ if (action === 'move_teammate_home') return 'prompt-each-time';
// 发给另一台电脑上的任务:作用范围越出本机,交给当前任务的权限档,不走可信 server 的静默放行。
if (action === 'send_to_session' && targetsAnotherComputer(sessionIdDevice(args?.target_session_id))) {
return 'prompt-each-time';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
index d98b31fe0a..3e36a5db62 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
@@ -351,3 +351,54 @@ it('preserves valid suggested dates and local legacy evidence while rejecting in
).rejects.toThrow();
expect((await store.read()).items[0]).toEqual(saved);
});
+
+describe('todos moving with the companion', () => {
+ it('replaces items by id and removes tombstoned ones, keeping this computer\'s cursors', async () => {
+ const { file } = await fixture();
+ const store = createBotTodoStore(file, async () => ({}));
+ const keep = await store.patch({ ...p, key: 'keep' });
+ const gone = await store.patch({ ...p, key: 'gone' });
+ await store.ingest({ source: 'plugin:mail', sequence: 3, items: [] } as never).catch(() => undefined);
+ const before = await store.read();
+ const moved = { ...keep, title: '从另一台电脑来的标题', revision: 9 };
+ const arrived = { ...keep, id: 'todo:arrived', key: 'arrived', title: '新的' };
+ await store.importItems([moved, arrived], [gone.id]);
+ const after = await store.read();
+ expect(after.items.map((item) => item.id).sort()).toEqual(['todo:arrived', keep.id].sort());
+ expect(after.items.find((item) => item.id === keep.id)?.title).toBe('从另一台电脑来的标题');
+ expect(after.cursors).toEqual(before.cursors);
+ });
+
+ it('gives another companion\'s todo with a taken key a stable key of its own', async () => {
+ const { file } = await fixture();
+ const store = createBotTodoStore(file, async () => ({}));
+ const mine = await store.patch({ ...p, key: 'quote:1' });
+ const theirs = { ...mine, id: 'todo:theirs', title: '另一个 Cindy 的' };
+ await store.importItems([theirs], []);
+ await store.importItems([theirs], []);
+ const items = (await store.read()).items;
+ expect(items).toHaveLength(2);
+ const merged = items.find((item) => item.id === 'todo:theirs')!;
+ expect(merged.key).toMatch(/^quote:1~[0-9a-f]{10}$/);
+ expect(items.find((item) => item.id === mine.id)!.key).toBe('quote:1');
+ // Still a valid store for the next write.
+ await store.patch({ id: mine.id, expectedRevision: mine.revision, progress: '继续' });
+ });
+
+ it('links a travelled legacy todo back to its workbench entry instead of adding a twin', async () => {
+ const { file } = await fixture();
+ const j = { project: '/cindy', title: '旧工具创建', verdict: 'unfinished' as const, next: '准备草稿',
+ ref: 'https://example.test/legacy', updatedAt: '2026-10-01T00:00:00Z' };
+ // On the old computer: the legacy entry became a todo, which travels without its link.
+ const old = createBotTodoStore((await fixture()).file, async () => ({ 'idea:later': j }));
+ const original = (await old.read()).items[0]!;
+ const { legacyId: _id, legacyFingerprint: _fp, legacyVerdict: _v, ...travelled } = original;
+ const store = createBotTodoStore(file, async () => ({ 'idea:later': j }));
+ await store.importItems([{ ...travelled, title: '新电脑上看到的标题' } as typeof original], []);
+ const items = (await store.read()).items;
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ id: original.id, legacyId: 'idea:later', title: '新电脑上看到的标题' });
+ await store.patch({ id: items[0]!.id, expectedRevision: items[0]!.revision, progress: '继续' });
+ expect((await store.read()).items).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts
index 280218cd7e..8fc4d584eb 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts
@@ -18,6 +18,8 @@ import {
rekeyBotWorkbenchJudgment,
removeBotWorkbenchDirectory,
setBotWorkbenchJudgment,
+ mergeCompanionWorkbench,
+ readCompanionWorkbench,
} from '../botWorkbenchService.js';
let root: string | null = null;
@@ -235,3 +237,71 @@ describe('bot workbench directory removal normalization', () => {
expect((await readBotWorkbenchState(root, 'bot-1')).directories).toEqual([]);
});
});
+
+describe('workbench moving with the companion', () => {
+ it('names each folder\'s computer, keeps other computers\' folders out of the local scope, and brings portable judgments', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const here = path.join(root, 'here');
+ await mkdir(here);
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', here)).toEqual({ ok: true });
+ await mergeCompanionWorkbench(root, 'bot-1', 'desk', {
+ directories: [{ path: 'C:\\Users\\dash\\game', addedAt: '2026-10-01T00:00:00.000Z', deviceId: 'laptop' },
+ { path: '/Users/dash/back-home', addedAt: '2026-10-01T00:00:00.000Z', deviceId: 'desk' }],
+ tasks: {
+ 'pr:makecindy/cindy#1': { title: 'Review', verdict: 'unfinished', next: null, project: here, updatedAt: '2026-10-01T00:00:00.000Z' },
+ 'session:abc': { title: 'Local task', verdict: 'unfinished', next: null, project: here, updatedAt: '2026-10-01T00:00:00.000Z' },
+ },
+ });
+ const workbench = await readBotWorkbench(root, 'bot-1');
+ expect(workbench.directories.find((dir) => dir.deviceId === 'laptop')).toMatchObject({ name: 'game', exists: false });
+ // A folder that was on this computer comes back as local.
+ expect(workbench.directories.find((dir) => dir.path === '/Users/dash/back-home')?.deviceId).toBeUndefined();
+ expect((await readBotWorkbenchState(root, 'bot-1')).directories).not.toContain('C:\\Users\\dash\\game');
+ expect(Object.keys(workbench.tasks)).toEqual(['pr:makecindy/cindy#1']);
+ const travelling = await readCompanionWorkbench(root, 'bot-1', 'desk');
+ expect(travelling.directories.find((dir) => dir.path === here)?.deviceId).toBe('desk');
+ // By path, not by drive: on Windows this computer's own folder is on C: too.
+ expect(travelling.directories.find((dir) => dir.path !== here && dir.path.startsWith('C:'))?.deviceId).toBe('laptop');
+ });
+
+ it('lets the cloud replace a workbench this computer synced before, keeping judgments that never travel', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const here = path.join(root, 'here');
+ await mkdir(here);
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', here)).toEqual({ ok: true });
+ await setBotWorkbenchJudgment(root, 'bot-1', 'session:abc', { title: 'Local task', verdict: 'unfinished', next: null, project: here });
+ await setBotWorkbenchJudgment(root, 'bot-1', 'pr:makecindy/cindy#1', { title: 'Review', verdict: 'unfinished', next: null, project: here });
+ await mergeCompanionWorkbench(root, 'bot-1', 'desk', null, { replace: true });
+ const workbench = await readBotWorkbench(root, 'bot-1');
+ expect(workbench.directories).toEqual([]);
+ expect(Object.keys(workbench.tasks)).toEqual(['session:abc']);
+ });
+
+ it('reads a damaged workbench as unreadable for the cloud, never as an empty one', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ expect(await readCompanionWorkbench(root, 'bot-1', 'desk')).toEqual({ directories: [], tasks: {} });
+ await mkdir(botProfileDir(root, 'bot-1'), { recursive: true });
+ await writeFile(path.join(botProfileDir(root, 'bot-1'), 'workbench.json'), '{not json', 'utf8');
+ await expect(readCompanionWorkbench(root, 'bot-1', 'desk')).rejects.toThrow();
+ });
+
+ it('removes a folder by its computer and path, never another computer\'s same path, and never rewrites a foreign path', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const here = path.join(root, 'here');
+ await mkdir(here);
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', here)).toEqual({ ok: true });
+ const windows = 'C:\\work\\game';
+ await mergeCompanionWorkbench(root, 'bot-1', 'desk', { directories: [
+ { path: windows, addedAt: '2026-10-01T00:00:00.000Z', deviceId: 'pc' },
+ { path: here, addedAt: '2026-10-01T00:00:00.000Z', deviceId: 'laptop' }], tasks: {} });
+ const dir0 = root;
+ const listed = async () => (await readBotWorkbench(dir0, 'bot-1')).directories.map((dir) => `${dir.deviceId ?? 'here'}:${dir.path}`).sort();
+ expect(await listed()).toEqual([`here:${here}`, `laptop:${here}`, `pc:${windows}`].sort());
+ await removeBotWorkbenchDirectory(root, 'bot-1', windows, 'pc');
+ expect(await listed()).toEqual([`here:${here}`, `laptop:${here}`].sort());
+ await removeBotWorkbenchDirectory(root, 'bot-1', here);
+ expect(await listed()).toEqual([`laptop:${here}`]);
+ await removeBotWorkbenchDirectory(root, 'bot-1', here, 'laptop');
+ expect(await listed()).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
index 3b682338b2..804ba6cbfc 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -58,6 +58,14 @@ describe('chat private media', () => {
await expect(media.download('room', 'media')).rejects.toThrow('CONVERSATION_NOT_FOUND');
expect(api).toHaveBeenCalledTimes(2);
});
+ it('keeps the status of a failed download, so a file that is gone is told from a failing server', async () => {
+ const api = vi.fn(async () => ({ name: 'p.png', type: 'image/png', size: 3, url: 'https://download.example.test/signed' })) as unknown as ChatApi;
+ f.fetch.mockResolvedValueOnce(new Response('', { status: 404 }));
+ await expect(createChatMedia(api, () => true).download('room', 'gone')).rejects.toMatchObject({ message: 'MEDIA_DOWNLOAD_FAILED', status: 404 });
+ f.fetch.mockResolvedValueOnce(new Response('', { status: 503 }));
+ await expect(createChatMedia(api, () => true).download('room', 'later')).rejects.toMatchObject({ message: 'MEDIA_DOWNLOAD_FAILED', status: 503 });
+ });
+
it('uploads a send\'s files three at a time and keeps their order', async () => {
f.read.mockResolvedValue({ buffer: Buffer.from('png') });
f.fetch.mockResolvedValue(new Response('', { status: 200 }));
diff --git a/apps/desktop/src/main/maker-ipc/botTodoAccess.ts b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
index b3ed9c79d4..d9e9620683 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
@@ -58,6 +58,24 @@ export function configureBotTodoDispatch(value: Dispatch, inspect?: InspectRecei
dispatch = value;
inspectReceipts = inspect ?? null;
}
+/**
+ * The companion's todo file without the active-profile check: a companion moving to this
+ * computer is restored (and uploaded) while its local copy is not runnable yet.
+ */
+export function companionTodoStore(botId: string) {
+ const owner = activeOwnerScopeKey(),
+ root = ownerScopedUserDataPath();
+ const assertCurrent = () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner)
+ throw new TodoError('OWNER_SCOPE_CHANGED');
+ };
+ return createBotTodoStore(
+ path.join(botProfileDir(root, botId), 'todos.v1.json'),
+ async () => (await readBotWorkbenchState(root, botId)).tasks,
+ assertCurrent,
+ );
+}
+
export async function todoAccess(botId: string): Promise<BotTodoAccess> {
const owner = activeOwnerScopeKey(),
root = ownerScopedUserDataPath();
diff --git a/apps/desktop/src/main/maker-ipc/botTodoStore.ts b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
index 52880e89da..80704cb213 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
@@ -55,6 +55,12 @@ export interface BotTodoStore {
requestId: string,
result: { ok: boolean; uncertain?: boolean; error?: string },
): Promise<TeammateTodo | null>;
+ /**
+ * The companion moved to this computer (cloud-companions.md §2): its todos from the cloud
+ * replace the items with the same id, `remove` ids are deleted. Per-computer plugin cursors
+ * and receipts stay as they are.
+ */
+ importItems(items: TeammateTodo[], remove: string[]): Promise<void>;
}
/** A separate versioned affair store preserves the old task/project file unchanged. */
export function createBotTodoStore(
@@ -273,6 +279,15 @@ export function createBotTodoStore(
for (const [legacyId, j] of Object.entries(await legacy())) {
const imported = legacyItem(legacyId, j);
if (!imported) continue;
+ // A todo that travelled from another computer lost its link to the workbench entry: same
+ // stable id, so link it again (it already reflects that entry) instead of adding a twin.
+ const travelled = state.items.find((t) => t.legacyId === undefined && t.id === imported.id);
+ if (travelled) {
+ travelled.legacyId = legacyId;
+ travelled.legacyFingerprint = imported.legacyFingerprint;
+ travelled.legacyVerdict = j.verdict;
+ continue;
+ }
const old = state.items.find((t) => t.legacyId === legacyId);
if (!old) {
state.items.push(imported);
@@ -334,6 +349,24 @@ export function createBotTodoStore(
return {
read,
patch: (patch: TodoPatch) => mutate((s) => applyTodoPatch(s, patch, 'todo:' + randomUUID())),
+ importItems: (items: TeammateTodo[], remove: string[]) =>
+ mutate((s) => {
+ const replaced = new Set([...items.map((item) => item.id), ...remove]);
+ const kept = s.items.filter((item) => !replaced.has(item.id));
+ // Keys are unique in the store: a different todo (another companion merged in) with a key
+ // already taken gets a stable key of its own, the same on every rerun.
+ const keys = new Set(kept.map((item) => item.key));
+ const added = structuredClone(items).map((item) => {
+ let key = item.key;
+ for (let attempt = 0; keys.has(key); attempt += 1) {
+ const tag = createHash('sha256').update(item.id + (attempt ? '#' + attempt : '')).digest('hex').slice(0, 10);
+ key = item.key.slice(0, 500) + '~' + tag;
+ }
+ keys.add(key);
+ return key === item.key ? item : { ...item, key };
+ });
+ s.items = [...kept, ...added];
+ }),
ingest: (params: {
source: string;
sequence: number;
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
index 84e008b1ca..08c67bc383 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
@@ -32,6 +32,11 @@ const WORKBENCH_FILE = 'workbench.json';
interface StoredDirectory {
path: string;
addedAt: string;
+ /**
+ * The computer the folder is on when it is not this one (cloud-companions.md §2): the companion
+ * moved here and the folder stayed on its old computer. Never an authorization scope here.
+ */
+ deviceId?: string;
}
interface StoredWorkbench {
@@ -99,10 +104,15 @@ function normalizeDirectories(raw: unknown): StoredDirectory[] {
for (const entry of Array.isArray(raw) ? raw : []) {
if (out.length >= BOT_WORKBENCH_MAX_DIRECTORIES) break;
if (!entry || typeof entry !== 'object') continue;
- const dir = entry as { path?: unknown; addedAt?: unknown };
- if (typeof dir.path !== 'string' || !path.isAbsolute(dir.path) || seen.has(dir.path)) continue;
- seen.add(dir.path);
- out.push({ path: dir.path, addedAt: typeof dir.addedAt === 'string' ? dir.addedAt : new Date(0).toISOString() });
+ const dir = entry as { path?: unknown; addedAt?: unknown; deviceId?: unknown };
+ const deviceId = typeof dir.deviceId === 'string' && dir.deviceId && dir.deviceId.length <= 200 ? dir.deviceId : undefined;
+ // Another computer's path may use another platform's form; it is only shown, never opened here.
+ const valid = typeof dir.path === 'string' && (deviceId ? !!dir.path.trim() && dir.path.length <= 4096 : path.isAbsolute(dir.path));
+ const key = `${deviceId ?? ''}\0${String(dir.path)}`;
+ if (!valid || seen.has(key)) continue;
+ seen.add(key);
+ out.push({ path: dir.path as string, addedAt: typeof dir.addedAt === 'string' ? dir.addedAt : new Date(0).toISOString(),
+ ...(deviceId ? { deviceId } : {}) });
}
return out;
}
@@ -118,6 +128,20 @@ function workbenchPath(userDataDir: string, botId: string): string {
return path.join(botProfileDir(userDataDir, botId), WORKBENCH_FILE);
}
+/** Only a missing file is an empty workbench; an unreadable or damaged one throws. */
+async function readStoredStrict(userDataDir: string, botId: string): Promise<StoredWorkbench> {
+ let raw: string;
+ try {
+ raw = await fs.readFile(workbenchPath(userDataDir, botId), 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { directories: [], tasks: {} };
+ throw error;
+ }
+ const stored = normalizeWorkbench(JSON.parse(raw));
+ if (!stored) throw new Error('WORKBENCH_UNREADABLE');
+ return stored;
+}
+
async function readStored(userDataDir: string, botId: string): Promise<StoredWorkbench> {
const empty: StoredWorkbench = { directories: [], tasks: {} };
try {
@@ -169,6 +193,10 @@ function mutate<T>(
}
async function describeDirectory(dir: StoredDirectory): Promise<BotWorkbenchDirectory> {
+ // On another computer: shown as such, never looked up on this disk.
+ // Its path may use the other computer's separators.
+ if (dir.deviceId) return { path: dir.path, name: dir.path.split(/[\\/]/).filter(Boolean).at(-1) || dir.path,
+ addedAt: dir.addedAt, exists: false, deviceId: dir.deviceId };
let exists = false;
try {
exists = (await fs.stat(dir.path)).isDirectory();
@@ -192,7 +220,54 @@ export async function readBotWorkbenchState(
botId: string,
): Promise<{ directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> }> {
const stored = await readStored(userDataDir, botId);
- return { directories: stored.directories.map((dir) => dir.path), tasks: stored.tasks };
+ // Only this computer's folders are the companion's scope here.
+ return { directories: stored.directories.flatMap((dir) => (dir.deviceId ? [] : [dir.path])), tasks: stored.tasks };
+}
+
+/** Task judgments that mean the same on any computer (pull requests, issues, ideas). */
+const PORTABLE_JUDGMENT = /^(pr|issue|idea):/;
+
+/**
+ * The workbench as it travels with the companion (cloud-companions.md §2): every folder with the
+ * computer it is on, and the portable judgments. `selfDeviceId` names this computer's folders.
+ */
+export async function readCompanionWorkbench(userDataDir: string, botId: string, selfDeviceId: string): Promise<{
+ directories: Array<{ path: string; addedAt: string; deviceId: string }>;
+ tasks: Record<string, WorkbenchTaskJudgment>;
+}> {
+ // Strict: a damaged file must not read as "no workbench" (the cloud copy would be tombstoned).
+ const stored = await readStoredStrict(userDataDir, botId);
+ return {
+ directories: stored.directories.map((dir) => ({ path: dir.path, addedAt: dir.addedAt, deviceId: dir.deviceId ?? selfDeviceId })),
+ tasks: Object.fromEntries(Object.entries(stored.tasks).filter(([key]) => PORTABLE_JUDGMENT.test(key))),
+ };
+}
+
+/**
+ * The companion moved here: its folders (this computer's become local again, others stay on
+ * their computer) and portable judgments from the cloud join what is here; the cloud wins. With
+ * `replace` (this computer synced them before) they take the place of what is here, so what was
+ * removed meanwhile stays removed; judgments that never travel stay.
+ */
+export async function mergeCompanionWorkbench(userDataDir: string, botId: string, selfDeviceId: string, cloud: unknown,
+ options: { replace?: boolean } = {}): Promise<void> {
+ const value = cloud && typeof cloud === 'object' ? cloud as { directories?: unknown; tasks?: unknown } : {};
+ const incoming = normalizeDirectories((Array.isArray(value.directories) ? value.directories : []).map((dir) => {
+ const entry = dir && typeof dir === 'object' ? dir as Record<string, unknown> : {};
+ return { ...entry, deviceId: entry.deviceId === selfDeviceId ? undefined : entry.deviceId };
+ }));
+ const tasks = Object.fromEntries(Object.entries(normalizeTasks(value.tasks)).filter(([key]) => PORTABLE_JUDGMENT.test(key)));
+ await mutate(userDataDir, botId, (stored) => {
+ const key = (dir: StoredDirectory) => `${dir.deviceId ?? ''}\0${dir.path}`;
+ if (options.replace) {
+ const local = Object.fromEntries(Object.entries(stored.tasks).filter(([taskId]) => !PORTABLE_JUDGMENT.test(taskId)));
+ return { next: { directories: incoming.slice(0, BOT_WORKBENCH_MAX_DIRECTORIES), tasks: boundJudgments({ ...local, ...tasks }) }, result: undefined };
+ }
+ const known = new Set(stored.directories.map(key));
+ const directories = [...stored.directories, ...incoming.filter((dir) => !known.has(key(dir)))].slice(0, BOT_WORKBENCH_MAX_DIRECTORIES);
+ return { next: { directories, tasks: boundJudgments({ ...stored.tasks, ...tasks }) }, result: undefined };
+ });
+ broadcastBotWorkbenchChanged(botId);
}
/** 整条替换一件任务的判断(上限与淘汰见 `boundJudgments`)。 */
@@ -268,13 +343,13 @@ export async function addBotWorkbenchDirectory(
});
}
-export async function removeBotWorkbenchDirectory(userDataDir: string, botId: string, dirPath: string): Promise<void> {
- // 与 add 同口径归一:add 存的是 path.resolve 后的路径, remove 若按原始串比较,
- // 等价但写法不同的路径(尾分隔符、./、../ 段)会静默漏删, 且广播后 UI 里项目
- // 仍在。resolve 后比较。
- const resolved = path.resolve(dirPath);
+export async function removeBotWorkbenchDirectory(userDataDir: string, botId: string, dirPath: string, deviceId?: string): Promise<void> {
+ // 目录的身份是「所在电脑 + 路径」。本机目录与 add 同口径归一:add 存的是 path.resolve 后的路径,
+ // remove 若按原始串比较,等价但写法不同的路径(尾分隔符、./、../ 段)会静默漏删。另一台电脑的目录
+ // 按原样比较(本机规则会改写别的平台的路径),且只删那台电脑的那一条,不连带同路径的本机目录。
+ const target = deviceId ? dirPath : path.resolve(dirPath);
await mutate(userDataDir, botId, (stored) => ({
- next: { ...stored, directories: stored.directories.filter((dir) => dir.path !== resolved) },
+ next: { ...stored, directories: stored.directories.filter((dir) => !((dir.deviceId ?? undefined) === (deviceId || undefined) && dir.path === target)) },
result: undefined,
}));
}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
index fdd5729315..3ea84c4879 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -556,7 +556,8 @@ export function removeBotWorkbenchProjectForCaller(params: { callerSessionId: st
const userDataDir = ownerScopedUserDataPath();
const caller = await resolveWorkbenchCaller(params.callerSessionId);
if (!caller.ok) return caller;
- const before = await readBotWorkbenchDirectoryPaths(userDataDir, caller.botId);
+ // A path names a folder on this computer; folders on other computers are removed from their row.
+ const before = (await readBotWorkbenchState(userDataDir, caller.botId)).directories;
const matched = await findHandedProject(params.path, before, {
homeDir: os.homedir(),
caseInsensitive: process.platform === 'darwin' || isCaseInsensitivePlatform(process.platform),
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 032021f845..9b37c3e518 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -817,12 +817,20 @@ export const MAKER_INVOKE = {
COMPANION_CLOUD_STATE: 'maker:companion-cloud:state',
/** Make this computer the companion's home (cloud-companions.md §3.1). */
COMPANION_CLOUD_TAKE_OVER: 'maker:companion-cloud:take-over',
- /** Hand the companion to another of the owner's computers. */
- COMPANION_CLOUD_TRANSFER: 'maker:companion-cloud:transfer',
+ /** Move the companion to another computer from any computer (hand over, ask its home, or take over). */
+ COMPANION_CLOUD_SWITCH_HOME: 'maker:companion-cloud:switch-home',
/** Read the companion's 1:1 room (works while its home is offline). */
COMPANION_CLOUD_TRANSCRIPT: 'maker:companion-cloud:transcript',
- /** Computers a companion can be handed to. */
- COMPANION_CLOUD_DEVICES: 'maker:companion-cloud:devices',
+ /** Where a companion can move, seen from this computer. */
+ COMPANION_CLOUD_HOME_CHOICES: 'maker:companion-cloud:home-choices',
+ /** The copies of Cindy in the cloud, when there are several to merge. */
+ COMPANION_CLOUD_CINDY_COPIES: 'maker:companion-cloud:cindy-copies',
+ /** Merge the other copies of Cindy into the kept one (on its home). */
+ 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',
+ /** 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/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index ef76c705ae..414422327f 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -9,7 +9,8 @@ import { readFile as readMedia } from '../cindy-media/blobStore.js';
import { getAccessToken, refresh } from '../authManager.js';
import { retryAfterDeadline } from '@cindy/auth-client';
import { parseChatInvitationToken } from '@cindy/device-link';
-import { existsSync, readFileSync } from 'node:fs';
+import { existsSync, readFileSync, promises as fsp } from 'node:fs';
+import { MIRROR_ATTACHMENT_MAX_BYTES } from '../companion-cloud/mirror.js';
import { request as httpRequest } from 'node:http';
import { request as httpsRequest } from 'node:https';
import { migrateLocalGroups, type ChatContentBlock } from './chatServerMigration.js';
@@ -751,7 +752,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
companion ??= startCompanionCloud({ api, host, endpoint: config.baseUrl, humanActorId: selfId, selfDeviceId: self, current, log: deps.log,
bots: () => actors.filter(a => a.kind === 'bot' && !a.disabled && a.homeDeviceId === self && localBot(a.id)?.status === 'active'
&& !companion?.isShadowed(a.externalId)).map(a => ({ botId: a.externalId, actorId: a.id, name: a.name })),
- actors: () => actors, refresh: refreshHomes, publish: publishHomes, syncProfile: syncActorProfiles });
+ paused: botId => profiles.find(p => p.id === botId)?.status === 'paused',
+ actors: () => actors, refresh: refreshHomes, publish: publishHomes, syncProfile: syncActorProfiles,
+ // The owner's attachments go with the conversation; other devices download them from the room.
+ media: { upload: async (room, source, files, author) => {
+ // The conversation mirror is not a file backup: large files stay a name in the room.
+ for (const file of files) if (file.path && (await fsp.stat(file.path)).size > MIRROR_ATTACHMENT_MAX_BYTES) throw new Error('ATTACHMENT_TOO_LARGE');
+ return media.upload(room, source, files, author);
+ }, download: (room, mediaId) => media.download(room, mediaId) } });
const runtime = companion;
await registerCompanionHomes({ api, selfDeviceId: self, actors, log: deps.log,
botIds: profiles.filter(p => p.status === 'active').map(p => p.id), isDemoted: botId => runtime.state.isDemoted(botId) });
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index e00c02fcfd..a7e69ea01b 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -101,7 +101,8 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
const root = ownerScopedUserDataPath();
const db = getDbClient().drizzle;
const response = await net.fetch(signedUrl(media.url), { redirect: 'error', signal: AbortSignal.timeout(60000) });
- if (!response.ok || !response.body) throw new Error('MEDIA_DOWNLOAD_FAILED');
+ // The status tells a file that is gone (4xx: never comes) from a failing server (retried).
+ if (!response.ok || !response.body) throw Object.assign(new Error('MEDIA_DOWNLOAD_FAILED'), response.ok ? {} : { status: response.status });
const chunks: Uint8Array[] = []; let received = 0;
const reader = response.body.getReader();
try {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 11963fb6ba..11f9891a5c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -239,6 +239,7 @@ import {
import { initGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';
import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
import { resolveSafe as resolveCindyMediaUrl } from '../cindy-media/blobStore.js';
+import { companionAvatarCache } from '../companion-cloud/avatarCacheHost.js';
import { ingestMedia } from '../cindy-media/ingest.js';
import { removeRefs as removeMediaRefs } from '../cindy-media/ledger.js';
import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
@@ -571,7 +572,7 @@ import { companionHomes, isCompanionShadowed } from '../companion-cloud/homes.js
import { createCompanionCloudHost } from '../companion-cloud/host.js';
import { activeCompanionCloud } from '../companion-cloud/runtime.js';
import { companionCloudView } from '../companion-cloud/view.js';
-import type { CompanionCloudActionResult } from '../../shared/companionCloud.js';
+import type { CompanionCloudActionResult, CompanionCloudFailureCode, CompanionHomeChoices, CompanionMergeResult, CompanionSwitchOptions } from '../../shared/companionCloud.js';
import { createBotGroupPlanDecider } from './botGroupPlanDecider.js';
import { botGroupMembersVisibleRemotely, registerBotGroupRemoteResourceProvider } from './botGroupRemoteResourceProvider.js';
import { broadcastBotGroupRemoteResourceChanged } from './botGroupRemoteResourceInvalidation.js';
@@ -977,7 +978,19 @@ import {
} from './orcaRemoteWorkerHost.js';
import { createOrcaRemoteWorkers, invokeDeviceValue, isExecutionDeviceCandidate, type OrcaRemoteWorkers } from './orcaRemoteWorkers.js';
import { getReceivedShares, providerShareAgentDeviceId } from '../device-link/providerShareGuest.js';
-import { ORCA_EXECUTION_DEVICES_CHANNEL, COMPANION_CLOUD_CAPS_CHANNEL, COMPANION_CLOUD_VERSION, isCompanionCloudCaps } from '@cindy/device-link';
+import {
+ ORCA_EXECUTION_DEVICES_CHANNEL,
+ COMPANION_CLOUD_CAPS_CHANNEL,
+ COMPANION_CLOUD_FLUSH_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ COMPANION_CLOUD_MERGE_CHANNEL,
+ COMPANION_CLOUD_RECEIVE_VERSION,
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+ COMPANION_CLOUD_VERSION,
+ companionCloudCapsVersion,
+ parseCompanionCloudRemoteActionResult,
+ parseCompanionCloudRemoteTargets,
+} from '@cindy/device-link';
import { INPUT_HANDOFF_LOCAL_CHANNEL, INPUT_HANDOFF_LOCAL_PICTURE_CHANNEL, type InputHandoffHolder, type InputHandoffSnapshot } from '@cindy/device-link';
import { getInputHandoffService, initInputHandoffService } from '../input-handoff/service.js';
import { closeInputHandoffAskpass, initInputHandoffAskpass } from '../input-handoff/askpass/index.js';
@@ -2666,6 +2679,43 @@ let botGroupChatServiceHolder: BotGroupChatService | null = null;
function settleCompanionOwner(): void { void botGroupChatServiceHolder?.chatServer; }
let unsubscribeCompanionCloudBroadcast: (() => void) | null = null;
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> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const value = await Promise.race([
+ invokeDeviceValue(invokeBotPeer, deviceId, COMPANION_CLOUD_CAPS_CHANNEL, []),
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('[INVOKE_TIMEOUT] caps probe timed out')), 5_000); }),
+ ]);
+ return companionCloudCapsVersion(value);
+ } catch { return 0; } finally { clearTimeout(timer); }
+}
+const COMPANION_FAILURE_CODES: ReadonlySet<CompanionCloudFailureCode> = new Set<CompanionCloudFailureCode>(
+ ['HOME_CONFLICT', 'OFFLINE', 'NOT_ENABLED', 'FAILED', 'TARGET_UNAVAILABLE', 'BUSY', 'HOME_OUTDATED', 'PAUSED']);
+/** Kept and merged Cindy ids from a request (local IPC or another computer). */
+function companionMergeIds(keepBotId: unknown, fromBotIds: unknown): { keep: string; from: string[] } {
+ if (typeof keepBotId !== 'string' || !keepBotId || keepBotId.length > 200) throwIpcError('INVALID_PARAMS', 'keepBotId required');
+ if (!Array.isArray(fromBotIds) || !fromBotIds.length || fromBotIds.length > 20
+ || fromBotIds.some(id => typeof id !== 'string' || !id || id.length > 200)) throwIpcError('INVALID_PARAMS', 'fromBotIds required');
+ return { keep: keepBotId, from: [...new Set(fromBotIds as string[])].filter(id => id !== keepBotId) };
+}
+/** A merge answered by another computer; anything malformed is a plain failure. */
+function companionMergeResult(value: unknown): CompanionMergeResult {
+ const record = value && typeof value === 'object' ? value as Record<string, unknown> : {};
+ const count = (key: string) => typeof record[key] === 'number' && Number.isFinite(record[key]) ? record[key] as number : 0;
+ if (record.ok === true) return { ok: true, merged: count('merged'), messages: count('messages'), memories: count('memories'), skills: count('skills'),
+ renamed: Array.isArray(record.renamed) ? record.renamed.filter((name): name is string => typeof name === 'string').slice(0, 200) : [] };
+ return { ok: false, code: companionFailureCode(typeof record.code === 'string' ? record.code : 'FAILED') };
+}
+/** What a move does while the companion is still working; anything else is the default (fail as busy). */
+function companionSwitchOptions(value: unknown): CompanionSwitchOptions | undefined {
+ const whenBusy = value && typeof value === 'object' ? (value as { whenBusy?: unknown }).whenBusy : undefined;
+ return whenBusy === 'wait' || whenBusy === 'stop' ? { whenBusy } : undefined;
+}
+/** A failure code answered by another computer; unknown codes (newer versions) are plain failures. */
+function companionFailureCode(code: string): CompanionCloudFailureCode {
+ return COMPANION_FAILURE_CODES.has(code as CompanionCloudFailureCode) ? code as CompanionCloudFailureCode : 'FAILED';
+}
const botRuntimeRestoreCoordinator = createBotRuntimeRestoreCoordinator({
readDbIdentity: () => {
@@ -9055,6 +9105,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
// Cloud companions: another computer asks before handing a companion here (read-only constant).
makerSessionRegistry.handle(COMPANION_CLOUD_CAPS_CHANNEL, () => ({ companionCloud: COMPANION_CLOUD_VERSION }));
+ // Another computer of this account changes where a companion runs: this computer (its home)
+ // lists the computers that can receive it and hands it over, exactly as from its own settings.
+ makerSessionRegistry.handle(COMPANION_CLOUD_TARGETS_CHANNEL, async () =>
+ (await activeCompanionCloud()?.transferTargets()) ?? []);
+ makerSessionRegistry.handle(COMPANION_CLOUD_MERGE_CHANNEL, async (_event: unknown, keepBotId: unknown, fromBotIds: unknown) => {
+ const keep = companionMergeIds(keepBotId, fromBotIds);
+ return (await activeCompanionCloud()?.mergeCindyHere(keep.keep, keep.from)) ?? { ok: false, code: 'NOT_ENABLED' };
+ });
+ // A merge on another computer reads the cloud: this computer (the copy's home) sends what it has not yet.
+ makerSessionRegistry.handle(COMPANION_CLOUD_FLUSH_CHANNEL, async (_event: unknown, botId: unknown) => {
+ if (typeof botId !== 'string' || !botId.trim() || botId.length > 200) throwIpcError('INVALID_PARAMS', 'botId required');
+ return (await activeCompanionCloud()?.flushHere(botId)) ?? { ok: false, code: 'NOT_ENABLED' };
+ });
+ makerSessionRegistry.handle(COMPANION_CLOUD_HAND_OVER_CHANNEL, async (_event: unknown, botId: unknown, targetDeviceId: unknown, options: unknown) => {
+ if (typeof botId !== 'string' || !botId.trim() || botId.length > 200) throwIpcError('INVALID_PARAMS', 'botId required');
+ if (typeof targetDeviceId !== 'string' || !targetDeviceId || targetDeviceId.length > 200) throwIpcError('INVALID_PARAMS', 'targetDeviceId required');
+ return (await activeCompanionCloud()?.transfer(botId, targetDeviceId, companionSwitchOptions(options))) ?? { ok: false, code: 'NOT_ENABLED' };
+ });
registerOrcaRemoteWorkerHandlers(makerSessionRegistry, createOrcaRemoteWorkerHost({
getCaller: () => {
const context = getDeviceLinkInvokeContext();
@@ -11881,17 +11949,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return 'rebuilt';
},
isTurnActive: companionTurnActive,
+ // Moving a companion that is still working, when the user chose to stop it first.
+ stopTurn: stopSessionTurnExplicitly,
listDevices: listCompanionDevices,
// Old clients answer CHANNEL_NOT_ALLOWED; unreachable ones time out. Neither may receive a companion.
- probeCompanionCloud: async (deviceId) => {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- const value = await Promise.race([
- invokeDeviceValue(invokeBotPeer, deviceId, COMPANION_CLOUD_CAPS_CHANNEL, []),
- new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('[INVOKE_TIMEOUT] caps probe timed out')), 5_000); }),
- ]);
- return isCompanionCloudCaps(value);
- } catch { return false; } finally { clearTimeout(timer); }
+ probeCompanionCloud: async (deviceId) => (await companionCloudPeerVersion(deviceId)) >= COMPANION_CLOUD_RECEIVE_VERSION,
+ selfDeviceId: getSelfDeviceId,
+ homeLink: {
+ version: companionCloudPeerVersion,
+ targets: async (deviceId) =>
+ parseCompanionCloudRemoteTargets(await invokeDeviceValue(invokeBotPeer, deviceId, COMPANION_CLOUD_TARGETS_CHANNEL, [])),
+ handOver: async (deviceId, botId, targetDeviceId, options) => {
+ const result = parseCompanionCloudRemoteActionResult(await invokeDeviceValue(invokeBotPeer, deviceId,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL, options?.whenBusy ? [botId, targetDeviceId, { whenBusy: options.whenBusy }] : [botId, targetDeviceId]));
+ return result.ok ? result : { ...result, code: companionFailureCode(result.code) };
+ },
+ merge: async (deviceId, keepBotId, fromBotIds) =>
+ companionMergeResult(await invokeDeviceValue(invokeBotPeer, deviceId, COMPANION_CLOUD_MERGE_CHANNEL, [keepBotId, fromBotIds])),
+ flush: async (deviceId, botId) => {
+ const result = parseCompanionCloudRemoteActionResult(await invokeDeviceValue(invokeBotPeer, deviceId, COMPANION_CLOUD_FLUSH_CHANNEL, [botId]));
+ return result.ok ? result : { ...result, code: companionFailureCode(result.code) };
+ },
},
// A message the owner wrote in the companion's room reaches its main task like any user input.
deliverToCanonical: async (botId, text, clientId) => {
@@ -12266,12 +12344,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
currentCompanionHomes();
return activeCompanionCloud()?.takeOver(id) ?? companionNotEnabled;
});
- ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_TRANSFER, async (event, botId: unknown, targetDeviceId: unknown) => {
+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_SWITCH_HOME, async (event, botId: unknown, targetDeviceId: unknown, options: unknown) => {
assertTrustedAppRendererEvent(event);
const id = companionBotId(botId);
if (typeof targetDeviceId !== 'string' || !targetDeviceId || targetDeviceId.length > 200) throwIpcError('INVALID_PARAMS', 'targetDeviceId required');
currentCompanionHomes();
- return activeCompanionCloud()?.transfer(id, targetDeviceId) ?? companionNotEnabled;
+ return activeCompanionCloud()?.switchHome(id, targetDeviceId, companionSwitchOptions(options)) ?? companionNotEnabled;
});
ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_TRANSCRIPT, async (event, botId: unknown, before: unknown) => {
assertTrustedAppRendererEvent(event);
@@ -12287,9 +12365,45 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('PRECONDITION_FAILED', 'Companion conversation is not available');
}
});
- ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_DEVICES, async (event) => {
+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_CINDY_COPIES, async (event) => {
+ assertTrustedAppRendererEvent(event);
+ currentCompanionHomes();
+ return (await activeCompanionCloud()?.cindyCopies()) ?? [];
+ });
+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_MERGE_CINDY, async (event, keepBotId: unknown, fromBotIds: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const ids = companionMergeIds(keepBotId, fromBotIds);
+ currentCompanionHomes();
+ return (await activeCompanionCloud()?.mergeCindy(ids.keep, ids.from)) ?? companionNotEnabled;
+ });
+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_ATTACHMENT, async (event, botId: unknown, mediaId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = companionBotId(botId);
+ if (typeof mediaId !== 'string' || !/^[0-9a-f-]{1,64}$/i.test(mediaId)) throwIpcError('INVALID_PARAMS', 'Invalid media id');
+ const runtime = activeCompanionCloud();
+ if (!runtime) throwIpcError('PRECONDITION_FAILED', 'Cloud companions are not available');
+ try {
+ return await runtime.attachment(id, mediaId);
+ } catch (error) {
+ log.warn('companion attachment read failed', { error: error instanceof Error ? error.message.slice(0, 80) : 'UNKNOWN' });
+ throwIpcError('PRECONDITION_FAILED', 'Companion attachment is not available');
+ }
+ });
+ ipcMain.handle(MAKER_INVOKE.COMPANION_AVATAR_RESOLVE, async (event, request: unknown) => {
assertTrustedAppRendererEvent(event);
- return (await activeCompanionCloud()?.transferTargets()) ?? [];
+ const input = request && typeof request === 'object' ? request as Record<string, unknown> : {};
+ const { avatar, deviceId, fetch } = input;
+ if (typeof avatar !== 'string' || !avatar || avatar.length > 2048) throwIpcError('INVALID_PARAMS', 'avatar required');
+ if (deviceId !== undefined && deviceId !== null && (typeof deviceId !== 'string' || deviceId.length > 200))
+ throwIpcError('INVALID_PARAMS', 'Invalid deviceId');
+ return companionAvatarCache.resolve({ avatar, deviceId: typeof deviceId === 'string' ? deviceId : null, fetch: fetch === true });
+ });
+ ipcMain.handle(MAKER_INVOKE.COMPANION_CLOUD_HOME_CHOICES, async (event, botId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = companionBotId(botId);
+ currentCompanionHomes();
+ const choices: CompanionHomeChoices = { homeDeviceId: null, mode: 'unavailable', reason: 'NOT_ENABLED', targets: [] };
+ return (await activeCompanionCloud()?.homeChoices(id)) ?? choices;
});
ipcMain.handle(MAKER_INVOKE.BOT_GROUP_PLAN_DISMISS, async (event, input: unknown) => {
assertTrustedAppRendererEvent(event);
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 1714794a7f..79908fdc50 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -1,4 +1,5 @@
import { todoForCaller } from '../maker-ipc/botTodoAccess.js';
+import { activeCompanionCloud } from '../companion-cloud/runtime.js';
import { TodoError, queryTodoItems, type TodoListQuery, type TodoPatch, type preflightTodoEvents } from '@cindy/maker-shared/teammate-todo';
import { t } from '../i18n.js';
import { executeTaskTags } from '../localDb/ipc/taskTags.js';
@@ -931,6 +932,25 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
return owned.botId;
},
},
+ // 伙伴的主力电脑:与界面同一条路径(本机交出 / 请主力电脑交出 / 在这台电脑继续)。
+ teammateHome: {
+ get: async ({ teammateId }) => {
+ const runtime = activeCompanionCloud();
+ if (!runtime) return { ok: false, errorCode: 'NOT_ENABLED', message: 'Cloud companions are not available on this server' };
+ const choices = await runtime.homeChoices(teammateId);
+ if (choices.reason === 'NOT_FOUND') return { ok: false, errorCode: 'NOT_FOUND', message: 'No such teammate in this account' };
+ return { ok: true, teammateId, mode: choices.mode, ...(choices.reason ? { reason: choices.reason } : {}),
+ home: choices.homeDeviceId ? { deviceId: choices.homeDeviceId, name: choices.homeName ?? '', isSelf: choices.mode === 'local' } : null,
+ choices: choices.targets.map(target => ({ deviceId: target.deviceId, name: target.name, isSelf: target.isSelf === true })) };
+ },
+ move: async ({ teammateId, targetDeviceId, whenBusy }) => {
+ const runtime = activeCompanionCloud();
+ if (!runtime) return { ok: false, errorCode: 'NOT_ENABLED', message: 'Cloud companions are not available on this server' };
+ const result = await runtime.switchHome(teammateId, targetDeviceId, whenBusy ? { whenBusy } : undefined);
+ return result.ok ? { ok: true, teammateId, homeDeviceId: targetDeviceId }
+ : { ok: false, errorCode: result.code, message: `The teammate did not move (${result.code})` };
+ },
+ },
botProfiles: {
create: async ({ callerSessionId, name, description, identitySource }) => {
const dbClient = tryGetDbClient();
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 889fc0a4a1..25865d848b 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -490,3 +490,40 @@ export async function relocateRoutinePluginSource(fromPart: string, toPart: stri
const next = rewriteRoutinePluginSource(state, fromPart, toPart);
if (next !== state) await store.save(next);
}
+
+/** A routine as it travels with its companion (cloud-companions.md §2); run history stays behind. */
+export interface CompanionRoutineValue {
+ id: string;
+ input: RoutineInput;
+ /** The computer the definition was saved on: its check command may only work there. */
+ originDeviceId: string | null;
+}
+
+export async function listCompanionRoutines(botId: string, selfDeviceId: string | null): Promise<CompanionRoutineValue[]> {
+ return (await routineTools.list(botId)).map((routine) => ({
+ id: routine.id,
+ input: { name: routine.name, prompt: routine.prompt, enabled: routine.enabled, triggers: routine.triggers,
+ ...(routine.silentWhenIdle !== undefined ? { silentWhenIdle: routine.silentWhenIdle } : {}),
+ ...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}) },
+ originDeviceId: selfDeviceId,
+ }));
+}
+
+/**
+ * The companion moved here: its routines from the cloud are created or updated with their ids;
+ * `remove` ids are deleted. Timers start from now (nothing missed is replayed). A routine whose
+ * check command came from another computer, or whose one-time trigger has passed, arrives turned
+ * off so it never runs a command this computer may not have.
+ */
+export async function importCompanionRoutines(botId: string, routines: CompanionRoutineValue[], remove: string[], selfDeviceId: string | null): Promise<void> {
+ const existing = new Set((await routineTools.list(botId)).map((routine) => routine.id));
+ const now = Date.now();
+ for (const routine of routines) {
+ const foreignHook = !!routine.input.preRunHook?.command?.trim() && routine.originDeviceId !== selfDeviceId;
+ const passed = routine.input.triggers.some((trigger) => trigger.kind === 'once' && trigger.at <= now);
+ const input: RoutineInput = { ...routine.input, enabled: routine.input.enabled && !foreignHook && !passed };
+ if (existing.has(routine.id)) await routineTools.save(botId, input, routine.id);
+ else await routineTools.createOnce(botId, input, routine.id);
+ }
+ for (const id of remove) if (existing.has(id)) await routineTools.remove(botId, id);
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 9c66d54dac..133a6ee233 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5640,8 +5640,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('local-db:bots:workbench:get', botId),
addDirectory: (botId: string, path: string): Promise<unknown> =>
ipcRenderer.invoke('local-db:bots:workbench:add-directory', botId, path),
- removeDirectory: (botId: string, path: string): Promise<void> =>
- ipcRenderer.invoke('local-db:bots:workbench:remove-directory', botId, path),
+ removeDirectory: (botId: string, path: string, deviceId?: string): Promise<void> =>
+ ipcRenderer.invoke('local-db:bots:workbench:remove-directory', botId, path, deviceId),
readTask: (botId: string, taskId: string): Promise<unknown> =>
ipcRenderer.invoke('local-db:bots:workbench:read-task', botId, taskId),
candidates: (botId: string): Promise<unknown> =>
@@ -6122,12 +6122,24 @@ contextBridge.exposeInMainWorld('electronAPI', {
onCompanionCloudChanged: fanOutCompanionCloudChanged,
takeOverCompanion: (botId: string): Promise<import('../shared/companionCloud').CompanionCloudActionResult> =>
ipcRenderer.invoke('maker:companion-cloud:take-over', botId),
- transferCompanion: (botId: string, targetDeviceId: string): Promise<import('../shared/companionCloud').CompanionCloudActionResult> =>
- ipcRenderer.invoke('maker:companion-cloud:transfer', botId, targetDeviceId),
+ switchCompanionHome: (
+ botId: string,
+ targetDeviceId: string,
+ options?: import('../shared/companionCloud').CompanionSwitchOptions,
+ ): Promise<import('../shared/companionCloud').CompanionCloudActionResult> =>
+ ipcRenderer.invoke('maker:companion-cloud:switch-home', botId, targetDeviceId, options),
getCompanionTranscript: (botId: string, before?: string): Promise<import('../shared/companionCloud').CompanionTranscriptPage> =>
ipcRenderer.invoke('maker:companion-cloud:transcript', botId, before),
- listCompanionTransferTargets: (): Promise<import('../shared/companionCloud').CompanionTransferTarget[]> =>
- ipcRenderer.invoke('maker:companion-cloud:devices'),
+ getCompanionHomeChoices: (botId: string): Promise<import('../shared/companionCloud').CompanionHomeChoices> =>
+ ipcRenderer.invoke('maker:companion-cloud:home-choices', botId),
+ listCindyCopies: (): Promise<import('../shared/companionCloud').CompanionCindyCopy[]> =>
+ ipcRenderer.invoke('maker:companion-cloud:cindy-copies'),
+ mergeCindy: (keepBotId: string, fromBotIds: string[]): Promise<import('../shared/companionCloud').CompanionMergeResult> =>
+ 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),
+ resolveCompanionAvatar: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }): Promise<string | null> =>
+ ipcRenderer.invoke('maker:companion-avatar:resolve', request),
onBotProfileChanged: fanOutBotProfileChanged,
onBotWorkbenchChanged: fanOutBotWorkbenchChanged,
runBotLifecycleAction: (
diff --git a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx
index a26a037b4f..8f76dee630 100644
--- a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx
+++ b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx
@@ -20,6 +20,8 @@ import { isBotGroupUnread, subscribeBotReadState, getBotLastReadAtMap } from '@/
import { useBotUnreadSync } from '@/features/bots/useBotUnreadSync';
import { useRemoteBotSync, useRemoteBots } from '@/features/bots/useRemoteBots';
import { isRemoteBotUnread } from '@/features/bots/remoteBotRoster';
+import { useCompanionCloud } from '@/features/bots/companionCloudStore';
+import { cloudRemoteBots, withoutShadowedBots } from '@/features/bots/companionCloudPresentation';
import { publishNavigationAttention } from '@/lib/navigationAttentionStore';
const readRevision = () => JSON.stringify(getBotLastReadAtMap());
const log = createLogger('AppBadgeAttentionSync');
@@ -29,10 +31,14 @@ export function AppBadgeAttentionSync() {
useAuth();
useBotUnreadSync();
useRemoteBotSync();
- const bots = useBotProfiles();
+ const cloud = useCompanionCloud();
+ // Count each companion once, where it runs (same rows as the teammate list).
+ const allBots = useBotProfiles();
+ const bots = useMemo(() => withoutShadowedBots(allBots, cloud), [allBots, cloud]);
const unread = useBotUnreadCounts();
const { groups } = useBotGroupList();
- const remoteBots = useRemoteBots();
+ const rosterRemoteBots = useRemoteBots();
+ const remoteBots = useMemo(() => cloudRemoteBots(cloud, rosterRemoteBots), [cloud, rosterRemoteBots]);
useSyncExternalStore(subscribeBotReadState, readRevision, readRevision);
const localTeammates = bots.filter(bot => bot.status !== 'archived' && bot.status !== 'deleting' && !bot.hiddenAt && (unread[bot.id] ?? 0) > 0).length
+ groups.filter(group => !group.archived && isBotGroupUnread(group)).length;
diff --git a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx b/apps/desktop/src/renderer/features/bots/BotAvatar.tsx
index 7f0a5d0e95..57f5cf15f6 100644
--- a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotAvatar.tsx
@@ -16,6 +16,10 @@
* bundled preset sentinel render as an `<img>`. Any unknown
* `cindy://avatar/…` sentinel is not a grapheme, so it falls back to the neutral
* initial instead of painting the raw sentinel string as text.
+ *
+ * A cloud companion's actor avatar (an `https://` public image, cloud-companions.md) also
+ * arrives in `avatar` when the row is built from the cloud (its main computer is offline):
+ * it renders as artwork too. Only a single grapheme is ever painted as text.
*/
import { rewriteToRemoteMediaOrigin } from '@/../shared/remoteMediaUrl';
import { useEffect, useState } from 'react';
@@ -25,8 +29,9 @@ import cindyPresetAvatar from '@/assets/bot-presets/cindy.png';
import dashPresetAvatar from '../../../../resources/legacy-teammate-avatars/dash.png';
import liziPresetAvatar from '../../../../resources/legacy-teammate-avatars/lizi.png';
import { cn } from '@/lib/utils';
-import { isManagedBotAvatarUrl } from '../../../shared/botAvatarValue';
+import { isManagedBotAvatarUrl, isSingleBotAvatarGrapheme } from '../../../shared/botAvatarValue';
import { CINDY_AVATAR_SCHEME_PREFIX, isCindyAvatarSentinel } from './botAvatarIdentity';
+import { useCachedCompanionAvatar, type CompanionAvatarSource } from './companionAvatarCache';
// The sentinel lives in an asset-free leaf module (see botAvatarIdentity.ts) but
// stays part of this module's public surface: UI code imports the avatar
@@ -146,16 +151,25 @@ export interface BotAvatarProps {
export function BotAvatar({ bot, size = 'md', className }: BotAvatarProps) {
const emoji = (bot.avatar ?? '').trim();
const bundledArtwork = BUNDLED_AVATAR_BY_SENTINEL[emoji.toLowerCase()] ?? null;
- const publicArtwork = bot.avatarUrl?.startsWith('https://') ? bot.avatarUrl : null;
- const artwork = publicArtwork ?? bundledArtwork ?? (isManagedBotAvatarUrl(emoji) ? rewriteToRemoteMediaOrigin(emoji, bot.deviceId ? { kind: 'device', deviceId: bot.deviceId } : undefined) : null);
- const [imageFailed, setImageFailed] = useState(false);
- useEffect(() => setImageFailed(false), [artwork]);
- const visibleArtwork = imageFailed ? null : artwork;
- // An unresolved sentinel (a preset only a newer client knows) is still not a
- // grapheme: fall through to the initial rather than paint `cindy://avatar/…`.
- const glyph = visibleArtwork || isCindyAvatarSentinel(emoji) || isManagedBotAvatarUrl(emoji)
- ? ''
- : emoji;
+ const publicArtwork = [bot.avatarUrl, emoji].find((value) => value?.startsWith('https://')) ?? null;
+ // Avatars held elsewhere (another computer, the cloud) are read from this computer's copy first.
+ const remoteManaged = !publicArtwork && !bundledArtwork && !!bot.deviceId && isManagedBotAvatarUrl(emoji);
+ const cacheSource: CompanionAvatarSource | null = publicArtwork ? { avatar: publicArtwork, deviceId: null }
+ : remoteManaged ? { avatar: emoji, deviceId: bot.deviceId! } : null;
+ const cached = useCachedCompanionAvatar(cacheSource);
+ const original = publicArtwork ?? bundledArtwork ?? (isManagedBotAvatarUrl(emoji) ? rewriteToRemoteMediaOrigin(emoji, bot.deviceId ? { kind: 'device', deviceId: bot.deviceId } : undefined) : null);
+ // While the local lookup runs, only the tint shows (no initial flashing before the image).
+ const waiting = cached === undefined;
+ // The local copy first; if it cannot load (e.g. recycled meanwhile), the original address.
+ const candidates = waiting ? [] : [...new Set([cached, original].filter((value): value is string => !!value))];
+ const candidateKey = candidates.join('\n');
+ const [failed, setFailed] = useState<readonly string[]>([]);
+ useEffect(() => setFailed([]), [candidateKey]);
+ const visibleArtwork = candidates.find((candidate) => !failed.includes(candidate)) ?? null;
+ // Anything that is not one grapheme (an unresolved sentinel, an address whose image failed)
+ // falls through to the initial rather than painting the raw string.
+ const glyph = !visibleArtwork && isSingleBotAvatarGrapheme(emoji) ? emoji : '';
+ const initial = waiting ? '' : botAvatarInitial(bot.name);
return (
<span
aria-hidden
@@ -174,13 +188,13 @@ export function BotAvatar({ bot, size = 'md', className }: BotAvatarProps) {
src={visibleArtwork}
alt=""
draggable={false}
- onError={() => setImageFailed(true)}
+ onError={() => setFailed((previous) => [...previous, visibleArtwork])}
className="pointer-events-none h-full w-full select-none rounded-full object-cover"
/>
) : glyph ? (
<span>{glyph}</span>
) : (
- <span className="font-medium text-[var(--text-primary)]">{botAvatarInitial(bot.name)}</span>
+ <span className="font-medium text-[var(--text-primary)]">{initial}</span>
)}
</span>
);
diff --git a/apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx b/apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx
index 12aa72c312..845b5525c9 100644
--- a/apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx
@@ -11,20 +11,23 @@ export function BotConnectionStatus({
connectionKnown,
deviceName,
inline = false,
- homeOffline = false,
+ quiet = false,
className,
}: {
online?: boolean | null;
connectionKnown?: boolean;
- /** The device is this companion's main computer (cloud companions): say so when offline. */
- homeOffline?: boolean;
+ /**
+ * A cloud companion (docs/product-rules/cloud-companions.md §3.1): like IM, its main computer
+ * being unreachable is not announced; only a message that cannot be delivered says so.
+ */
+ quiet?: boolean;
deviceName?: string;
inline?: boolean;
className?: string;
}) {
const { t } = useTranslation();
- const offline = isBotKnownOffline(online, connectionKnown);
- const status = offline ? t(homeOffline ? 'bots.cloud.homeOfflineShort' : 'bots.remote.offline') : '';
+ const offline = !quiet && isBotKnownOffline(online, connectionKnown);
+ const status = offline ? t('bots.remote.offline') : '';
const name = deviceName?.trim();
const label = [status, name].filter(Boolean).join(' · ');
if (inline) {
diff --git a/apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx b/apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx
index 830c276254..6b304ec6a2 100644
--- a/apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx
@@ -1,13 +1,15 @@
/**
- * 伙伴设置里的「主力电脑」一行(docs/product-rules/cloud-companions.md §3.1):本机是主力电脑时
- * 显示「这台电脑」,点开列出可接手的其他电脑;确认后交出去并打开那台电脑上的伙伴。
- * 服务器不支持云端伙伴时整行不出现。
+ * 伙伴的「主力电脑」入口(docs/product-rules/cloud-companions.md §3.1):伙伴设置里的一行,以及聊天
+ * 顶部「在 X 上运行」。任何一台电脑上都能看到伙伴在哪里运行,点开列出可以换去的电脑:
+ * 本机是主力电脑时由本机交出;主力电脑在线时请它交出;主力电脑连不上时只能在这台电脑继续。
+ * 确认后打开换过去的伙伴。服务器不支持云端伙伴时不出现。
*/
import { useRef, useState } from 'react';
-import { ChevronRight, Monitor } from 'lucide-react';
+import { ChevronDown, ChevronRight, Monitor } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import {
DropdownMenu,
@@ -15,75 +17,241 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
-import type { CompanionCloudFailureCode, CompanionTransferTarget } from '../../../shared/companionCloud';
-import { companionCloudApi, refreshCompanionCloud, useCompanionCloud } from './companionCloudStore';
+import type {
+ CompanionCloudFailureCode,
+ CompanionCloudSnapshot,
+ CompanionHomeChoices,
+ CompanionSwitchOptions,
+ CompanionTransferTarget,
+} from '../../../shared/companionCloud';
+import { ensureBotProfilesLoaded, useBotProfiles } from './botStore';
+import {
+ companionCloudApi,
+ getCompanionCloudSnapshot,
+ refreshCompanionCloud,
+ useCompanionCloud,
+} from './companionCloudStore';
-const TRANSFER_ERROR_KEYS: Record<CompanionCloudFailureCode, string> = {
- HOME_CONFLICT: 'bots.cloud.transferConflict',
- OFFLINE: 'bots.cloud.transferOffline',
+const SWITCH_ERROR_KEYS: Record<CompanionCloudFailureCode, string> = {
+ HOME_CONFLICT: 'bots.cloud.switchConflict',
+ OFFLINE: 'bots.cloud.switchOffline',
NOT_ENABLED: 'bots.cloud.notEnabled',
TARGET_UNAVAILABLE: 'bots.cloud.targetUnavailable',
- FAILED: 'bots.cloud.transferFailed',
+ FAILED: 'bots.cloud.switchFailed',
BUSY: 'bots.cloud.transferBusy',
+ HOME_OUTDATED: 'bots.cloud.homeOutdated',
+ PAUSED: 'bots.cloud.resumeToMove',
};
-export function BotHomeComputerSetting({ bot }: { bot: { id: string; name: string; status?: string } }) {
+/** How long a companion moved here from its online home may take to be built on this computer. */
+const ARRIVAL_TIMEOUT_MS = 2 * 60_000;
+const ARRIVAL_POLL_MS = 1_500;
+
+export interface CompanionHomeBot {
+ id: string;
+ name: string;
+ /** Local profile status; absent for companions read from another computer. */
+ status?: string;
+}
+
+/** This computer runs the companion now: home here, the local copy built and no longer demoted. */
+export function companionArrivedHere(cloud: CompanionCloudSnapshot, botId: string, localBotIds: readonly string[]): boolean {
+ if (!cloud.enabled || !cloud.selfDeviceId || cloud.demotedBotIds.includes(botId)) return false;
+ const actor = cloud.actors.find((candidate) => candidate.externalId === botId);
+ return actor?.homeDeviceId === cloud.selfDeviceId && localBotIds.includes(botId);
+}
+
+/** Wait until the automatic take-over here finished (or time out). */
+async function waitForArrival(botId: string, isCurrent: () => boolean): Promise<boolean> {
+ const deadline = Date.now() + ARRIVAL_TIMEOUT_MS;
+ while (isCurrent() && Date.now() < deadline) {
+ const profiles = await ensureBotProfilesLoaded(true).catch(() => []);
+ const local = profiles.filter((profile) => profile.status === 'active').map((profile) => profile.id);
+ if (companionArrivedHere(getCompanionCloudSnapshot(), botId, local)) return true;
+ refreshCompanionCloud();
+ await new Promise((resolve) => setTimeout(resolve, ARRIVAL_POLL_MS));
+ }
+ return false;
+}
+
+/** `inline`: the settings row shows failures under itself; `toast`: the header chip has no room. */
+function useCompanionHomeSwitch(bot: CompanionHomeBot, failures: 'inline' | 'toast') {
const { t } = useTranslation();
const navigate = useNavigate();
const cloud = useCompanionCloud();
- const [targets, setTargets] = useState<CompanionTransferTarget[] | null>(null);
- const [targetsFailed, setTargetsFailed] = useState(false);
+ const [choices, setChoices] = useState<CompanionHomeChoices | null>(null);
+ const [choicesFailed, setChoicesFailed] = useState(false);
const [pending, setPending] = useState<CompanionTransferTarget | null>(null);
+ /** The companion was still working when asked to move there: wait for it, or stop it. */
+ const [busyTarget, setBusyTarget] = useState<CompanionTransferTarget | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
+ const report = (message: string) => { if (failures === 'toast') toast.error(message); else setError(message); };
const actor = cloud.enabled ? cloud.actors.find((candidate) => candidate.externalId === bot.id) : undefined;
- if (!actor || !cloud.selfDeviceId || actor.homeDeviceId !== cloud.selfDeviceId) return null;
+ const home = actor?.homeDeviceId ?? null;
+ const homeHere = !!home && home === cloud.selfDeviceId;
+ const localStatus = useBotProfiles().find((profile) => profile.id === bot.id)?.status;
+ // Only a running companion syncs (and so can move); a paused one is resumed first.
+ const status = bot.status ?? (homeHere ? localStatus : undefined);
+ const movable = status === undefined || status === 'active';
+ const targetName = (target: CompanionTransferTarget) =>
+ target.isSelf ? t('bots.cloud.thisComputer') : target.name.trim() || t('bots.cloud.unknownDevice');
- // Only a running companion syncs (and so can be handed over); a paused one is resumed first.
- const movable = bot.status === undefined || bot.status === 'active';
- const loadTargets = () => {
+ const load = () => {
if (!movable) return;
- setTargets(null);
- setTargetsFailed(false);
+ setChoices(null);
+ setChoicesFailed(false);
const api = companionCloudApi();
- if (!api) { setTargetsFailed(true); return; }
- void api.listCompanionTransferTargets().then(setTargets, () => setTargetsFailed(true));
+ if (!api) { setChoicesFailed(true); return; }
+ const owner = getDataOwnerGeneration();
+ void api.getCompanionHomeChoices(bot.id).then(
+ (next) => { if (isDataOwnerGenerationCurrent(owner)) setChoices(next); },
+ () => { if (isDataOwnerGenerationCurrent(owner)) setChoicesFailed(true); },
+ );
};
- const transfer = async () => {
- if (!pending || inFlight.current) return;
+ const confirm = async (target: CompanionTransferTarget | null = pending, options?: CompanionSwitchOptions) => {
+ if (!target || inFlight.current) return;
const api = companionCloudApi();
if (!api) return;
inFlight.current = true;
setBusy(true);
setError(null);
- const target = pending;
+ const device = targetName(target);
+ const owner = getDataOwnerGeneration();
+ const current = () => isDataOwnerGenerationCurrent(owner);
try {
- const result = await api.transferCompanion(bot.id, target.deviceId);
- if (result.ok) {
- setPending(null);
- toast.info(t('bots.cloud.transferred', { name: bot.name, device: target.name }));
+ if (options?.whenBusy === 'wait') toast.info(t('bots.cloud.waitingForTurn', { name: bot.name, device }));
+ const result = await api.switchCompanionHome(bot.id, target.deviceId, options);
+ if (!current()) return;
+ setPending(null);
+ setBusyTarget(null);
+ // Still working and nothing chosen yet: offer to wait for the turn or stop it.
+ if (!result.ok && result.code === 'BUSY' && !options?.whenBusy) {
+ setBusyTarget(target);
+ return;
+ }
+ if (!result.ok) {
+ report(t(SWITCH_ERROR_KEYS[result.code] ?? 'bots.cloud.switchFailed', { name: bot.name, device }));
+ refreshCompanionCloud();
+ return;
+ }
+ if (!target.isSelf) {
+ toast.info(t('bots.cloud.switched', { name: bot.name, device }));
navigate(`/bots/remote/${encodeURIComponent(target.deviceId)}/${encodeURIComponent(bot.id)}`);
return;
}
- setPending(null);
- setError(t(TRANSFER_ERROR_KEYS[result.code], { name: bot.name, device: target.name }));
- if (result.code === 'HOME_CONFLICT') refreshCompanionCloud();
+ // Asked from another computer: this one builds the companion once the move reaches it.
+ if (choices?.mode === 'remote') {
+ toast.info(t('bots.cloud.takingOver', { name: bot.name }));
+ if (!(await waitForArrival(bot.id, current))) {
+ if (current()) toast.info(t('bots.cloud.arrivingLater', { name: bot.name }));
+ return;
+ }
+ } else {
+ await ensureBotProfilesLoaded(true).catch(() => undefined);
+ }
+ if (!current()) return;
+ refreshCompanionCloud();
+ navigate(`/bots/${encodeURIComponent(bot.id)}`);
} catch {
+ if (!current()) return;
setPending(null);
- setError(t('bots.cloud.transferFailed', { name: bot.name, device: target.name }));
+ setBusyTarget(null);
+ report(t('bots.cloud.switchFailed', { name: bot.name, device }));
} finally {
inFlight.current = false;
setBusy(false);
}
};
+ const homeName = homeHere
+ ? t('bots.cloud.thisComputer')
+ : actor?.homeDevice?.name?.trim() || t('bots.cloud.unknownDevice');
+ return { actor, home, homeHere, homeName, movable, choices, choicesFailed, pending, setPending, busyTarget, setBusyTarget, busy,
+ error, setError, inFlight, load, confirm, targetName };
+}
+
+type HomeSwitch = ReturnType<typeof useCompanionHomeSwitch>;
+
+function HomeMenuItems({ bot, state }: { bot: CompanionHomeBot; state: HomeSwitch }) {
+ const { t } = useTranslation();
+ const { choices } = state;
+ if (!state.movable)
+ return <DropdownMenuItem disabled className="whitespace-normal">{t('bots.cloud.resumeToMove', { name: bot.name })}</DropdownMenuItem>;
+ if (state.choicesFailed) return <DropdownMenuItem disabled>{t('bots.cloud.devicesFailed')}</DropdownMenuItem>;
+ if (choices === null) return <DropdownMenuItem disabled>{t('bots.cloud.loadingDevices')}</DropdownMenuItem>;
+ if (choices.mode === 'unavailable')
+ return (
+ <DropdownMenuItem disabled className="whitespace-normal">
+ {choices.reason === 'HOME_OUTDATED'
+ ? t('bots.cloud.homeOutdated', { name: bot.name, device: state.homeName })
+ : t('bots.cloud.notEnabled')}
+ </DropdownMenuItem>
+ );
+ if (choices.targets.length === 0)
+ return <DropdownMenuItem disabled className="whitespace-normal">{t('bots.cloud.noTargets')}</DropdownMenuItem>;
return (
- <div className="mt-3">
+ <>
+ {choices.targets.map((target) => (
+ <DropdownMenuItem key={target.deviceId} onSelect={() => { state.setError(null); state.setPending(target); }}>
+ <span className="min-w-0 truncate">
+ {target.isSelf ? t('bots.cloud.switchHere') : t('bots.cloud.switchTo', { device: state.targetName(target) })}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </>
+ );
+}
+
+function HomeSwitchConfirm({ bot, state }: { bot: CompanionHomeBot; state: HomeSwitch }) {
+ const { t } = useTranslation();
+ const device = state.pending ? state.targetName(state.pending) : '';
+ const busyDevice = state.busyTarget ? state.targetName(state.busyTarget) : '';
+ return (
+ <>
+ <ConfirmDialog
+ open={state.busyTarget !== null}
+ presentation="standard"
+ cancelFirst
+ onOpenChange={(open) => { if (!open && !state.inFlight.current) state.setBusyTarget(null); }}
+ title={t('bots.cloud.busyTitle', { name: bot.name })}
+ description={t('bots.cloud.busyDescription', { name: bot.name, device: busyDevice })}
+ confirmText={t('bots.cloud.busyWait')}
+ tertiaryText={t('bots.cloud.busyStop')}
+ cancelText={t('bots.cancel')}
+ loading={state.busy}
+ onConfirm={() => void state.confirm(state.busyTarget, { whenBusy: 'wait' })}
+ onTertiary={() => void state.confirm(state.busyTarget, { whenBusy: 'stop' })}
+ />
+ <ConfirmDialog
+ open={state.pending !== null}
+ presentation="standard"
+ cancelFirst
+ onOpenChange={(open) => { if (!open && !state.inFlight.current) state.setPending(null); }}
+ title={t('bots.cloud.switchTitle', { name: bot.name, device })}
+ description={t('bots.cloud.switchDescription', { name: bot.name, device })}
+ confirmText={t('bots.cloud.switchAction', { device })}
+ cancelText={t('bots.cancel')}
+ loading={state.busy}
+ onConfirm={() => void state.confirm()}
+ />
+ </>
+ );
+}
+
+/** The 「主力电脑」 row in a companion's settings, on any computer. */
+export function BotHomeComputerSetting({ bot, className = 'mt-3' }: { bot: CompanionHomeBot; className?: string }) {
+ const { t } = useTranslation();
+ const state = useCompanionHomeSwitch(bot, 'inline');
+ if (!state.actor || !state.home) return null;
+ return (
+ <div className={className}>
<div className="overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
- <DropdownMenu onOpenChange={(open) => { if (open) loadTargets(); }}>
+ <DropdownMenu onOpenChange={(open) => { if (open) state.load(); }}>
<DropdownMenuTrigger asChild>
<button
type="button"
@@ -92,44 +260,49 @@ export function BotHomeComputerSetting({ bot }: { bot: { id: string; name: strin
>
<Monitor size={18} className="shrink-0 text-[var(--text-secondary)]" />
<span className="min-w-0 flex-1">{t('bots.cloud.homeLabel')}</span>
- <span className="shrink-0 text-13 text-[var(--text-secondary)]">{t('bots.cloud.thisComputer')}</span>
+ <span className="min-w-0 max-w-48 truncate text-13 text-[var(--text-secondary)]">{state.homeName}</span>
<ChevronRight size={14} className="shrink-0 text-[var(--text-tertiary)]" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-56 max-w-80">
- {!movable ? (
- <DropdownMenuItem disabled className="whitespace-normal">{t('bots.cloud.resumeToMove', { name: bot.name })}</DropdownMenuItem>
- ) : targetsFailed ? (
- <DropdownMenuItem disabled>{t('bots.cloud.devicesFailed')}</DropdownMenuItem>
- ) : targets === null ? (
- <DropdownMenuItem disabled>{t('bots.cloud.loadingDevices')}</DropdownMenuItem>
- ) : targets.length === 0 ? (
- <DropdownMenuItem disabled className="whitespace-normal">{t('bots.cloud.noTargets')}</DropdownMenuItem>
- ) : (
- targets.map((target) => (
- <DropdownMenuItem key={target.deviceId} onSelect={() => { setError(null); setPending(target); }}>
- <span className="min-w-0 truncate">{t('bots.cloud.moveTo', { device: target.name })}</span>
- </DropdownMenuItem>
- ))
- )}
+ <HomeMenuItems bot={bot} state={state} />
</DropdownMenuContent>
</DropdownMenu>
</div>
- {error ? (
- <p role="alert" className="mt-2 px-1 text-12 text-[var(--text-danger)]">{error}</p>
+ {state.error ? (
+ <p role="alert" className="mt-2 px-1 text-12 text-[var(--text-danger)]">{state.error}</p>
) : null}
- <ConfirmDialog
- open={pending !== null}
- presentation="standard"
- cancelFirst
- onOpenChange={(open) => { if (!open && !inFlight.current) setPending(null); }}
- title={t('bots.cloud.transferTitle', { name: bot.name, device: pending?.name ?? '' })}
- description={t('bots.cloud.transferDescription', { name: bot.name, device: pending?.name ?? '' })}
- confirmText={t('bots.cloud.transferAction', { device: pending?.name ?? '' })}
- cancelText={t('bots.cancel')}
- loading={busy}
- onConfirm={() => void transfer()}
- />
+ <HomeSwitchConfirm bot={bot} state={state} />
</div>
);
}
+
+/** 「在 X 上运行」 in the chat header; null when the companion has no known home. */
+export function CompanionHomeChip({ bot }: { bot: CompanionHomeBot }) {
+ const { t } = useTranslation();
+ const state = useCompanionHomeSwitch(bot, 'toast');
+ if (!state.actor || !state.home) return null;
+ const label = state.homeHere ? t('bots.cloud.runsHere') : t('bots.cloud.runsOn', { device: state.homeName });
+ return (
+ <>
+ <DropdownMenu onOpenChange={(open) => { if (open) state.load(); }}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ data-testid="bot-home-computer-chip"
+ title={t('bots.cloud.switchHint', { name: bot.name })}
+ className="flex min-w-0 max-w-56 shrink items-center gap-1 rounded-full px-2 py-1 text-12 text-[var(--text-tertiary)] outline-none hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <span className="min-w-0 truncate">{label}</span>
+ <ChevronDown size={12} className="shrink-0" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-56 max-w-80">
+ <HomeMenuItems bot={bot} state={state} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <HomeSwitchConfirm bot={bot} state={state} />
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx b/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
index 6fd1c6082a..b55c781651 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
@@ -23,6 +23,8 @@ import { BotAddToGroupMenu } from './BotAddToGroupMenu';
import { BotAvatar } from './BotAvatar';
import { isCindyDeviceBot } from './cindyDeviceRoster';
import { CindyHeaderDevicePicker } from './CindyDevicePicker';
+import { CompanionHomeChip } from './BotHomeComputerSetting';
+import { useCompanionCloud } from './companionCloudStore';
export interface BotChatIdentity {
id: string;
@@ -42,7 +44,13 @@ export function BotSessionContentHeader({ bot }: { bot: BotChatIdentity }) {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
- const isCindy = isCindyDeviceBot(bot);
+ const cloud = useCompanionCloud();
+ // A cloud companion is one teammate wherever it runs: the header names its main computer and
+ // switches it, instead of listing per-computer copies (the older Cindy device picker).
+ const homeKnown =
+ cloud.enabled &&
+ cloud.actors.some((actor) => actor.externalId === bot.id && !!actor.homeDeviceId);
+ const isCindy = !homeKnown && isCindyDeviceBot(bot);
const openSettings = () => {
const search = new URLSearchParams(location.search);
search.set('settings', '1');
@@ -64,9 +72,10 @@ export function BotSessionContentHeader({ bot }: { bot: BotChatIdentity }) {
<BotAvatar bot={bot} size="xs" />
<span className="min-w-0 truncate">{bot.name}</span>
</button>
+ {homeKnown ? <CompanionHomeChip bot={{ id: bot.id, name: bot.name }} /> : null}
{isCindy ? <CindyHeaderDevicePicker bot={bot} /> : null}
<div className="ml-auto flex shrink-0 items-center gap-1">
- {bot.deviceId && !isCindy ? (
+ {bot.deviceId && !isCindy && !homeKnown ? (
<span className="max-w-32 truncate text-12 text-[var(--text-tertiary)]">
{bot.deviceName}
</span>
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index ec2999eda0..1e5a2bad47 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -71,6 +71,7 @@ import {
import { useBotDelegations } from './botDelegationLive';
import { isBotPrimaryGeneratedFile } from './botGeneratedArtifacts';
import { useBotProfiles } from './botStore';
+import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
import {
buildWorkbenchProjectOptions,
buildWorkbenchTiles,
@@ -972,8 +973,8 @@ function ProjectCapsules({
}) {
const { t } = useTranslation();
const remove = useCallback(
- (dirPath: string) => {
- void window.electronAPI?.localDb?.bots?.workbench?.removeDirectory(botId, dirPath).catch(() => {});
+ (dirPath: string, deviceId?: string) => {
+ void window.electronAPI?.localDb?.bots?.workbench?.removeDirectory(botId, dirPath, deviceId).catch(() => {});
},
[botId],
);
@@ -981,19 +982,20 @@ function ProjectCapsules({
<div className="flex flex-wrap items-center gap-2 px-5 pt-3">
{directories.map((dir) => (
<span
- key={dir.path}
- title={dir.exists ? dir.path : t('bots.workbench.dirMissing')}
+ key={`${dir.deviceId ?? ''}:${dir.path}`}
+ title={dir.deviceId ? dir.path : dir.exists ? dir.path : t('bots.workbench.dirMissing')}
className={cn(
'inline-flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full bg-[var(--surface-chip)] pl-3 pr-1 text-13',
- dir.exists ? 'text-[var(--text-primary)]' : 'text-[var(--text-danger)]',
+ dir.deviceId ? 'text-[var(--text-secondary)]' : dir.exists ? 'text-[var(--text-primary)]' : 'text-[var(--text-danger)]',
)}
>
<Folder size={14} strokeWidth={1.8} aria-hidden className="shrink-0" />
<span className="min-w-0 truncate">{dir.name}</span>
+ {dir.deviceId ? <DirectoryElsewhere deviceId={dir.deviceId} /> : null}
<Tip text={t('bots.workbench.removeProject', { name: botName, project: dir.name })}>
<button
type="button"
- onClick={() => remove(dir.path)}
+ onClick={() => remove(dir.path, dir.deviceId)}
aria-label={t('bots.workbench.removeProject', { name: botName, project: dir.name })}
className={cn(ICON_BUTTON_CLASS, 'size-6 text-[var(--text-tertiary)]')}
>
@@ -1836,3 +1838,12 @@ function TaskDetail({
</div>
);
}
+
+/** A folder that stayed on the companion's previous computer: reachable there, not here. */
+function DirectoryElsewhere({ deviceId }: { deviceId: string }) {
+ const { t } = useTranslation();
+ const devices = useDeviceLinkDeviceList();
+ const device = devices?.find((candidate) => candidate.deviceId === deviceId)?.name?.trim() || t('bots.cloud.unknownDevice');
+ return <span className="shrink-0 text-12 text-[var(--text-tertiary)]">{t('bots.workbench.dirElsewhere', { device })}</span>;
+}
+
diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
index 1181c42cf3..d817999ece 100644
--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
@@ -58,6 +58,7 @@ import {
import { useCompanionCloud } from './companionCloudStore';
import { withoutShadowedBots } from './companionCloudPresentation';
import { BotHomeComputerSetting } from './BotHomeComputerSetting';
+import { CindyMergeSetting } from './CindyMergeSetting';
import { BotLifecycleSettings } from './BotLifecycleSettings';
import { BotInvitationWelcome } from './BotInvitationWelcome';
import { BotModelChainEditor } from './BotModelChainEditor';
@@ -516,6 +517,7 @@ export function BotSettings({
))}
</div>
<BotHomeComputerSetting bot={bot} />
+ <CindyMergeSetting bot={bot} />
<div className="mt-6">
<BotLifecycleSettings
bot={bot}
diff --git a/apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx b/apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx
index 6728ec2aa8..9ea9ebd0d2 100644
--- a/apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx
+++ b/apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx
@@ -6,7 +6,7 @@ import { cn } from '@/lib/utils';
import { useBotProfiles, useBotUnreadCounts } from './botStore';
import { useRemoteBots } from './useRemoteBots';
import { useCompanionCloud } from './companionCloudStore';
-import { cloudRemoteBots, withoutShadowedBots } from './companionCloudPresentation';
+import { cloudRemoteBots, withoutCloudCompanions, withoutShadowedBots } from './companionCloudPresentation';
import { cindyDeviceKey, cindyDeviceOptions, type CindyDeviceOption } from './cindyDeviceRoster';
import { formatBotUnreadBadge } from './botListDisplay';
import { isBotKnownOffline } from './BotConnectionStatus';
@@ -90,9 +90,9 @@ export function CindyHeaderDevicePicker({ bot }: { bot: BotChatIdentity }) {
const navigate = useNavigate();
const cloud = useCompanionCloud();
// A demoted local Cindy is not the "local" option: she runs on her main computer.
- const bots = withoutShadowedBots(useBotProfiles(), cloud);
+ const bots = withoutCloudCompanions(withoutShadowedBots(useBotProfiles(), cloud), cloud);
// Copies other computers still list for a Cindy that runs elsewhere are not choices either.
- const remoteBots = cloudRemoteBots(cloud, useRemoteBots());
+ const remoteBots = withoutCloudCompanions(cloudRemoteBots(cloud, useRemoteBots()), cloud);
const devices = useDeviceLinkDeviceList();
const unread = useBotUnreadCounts();
const options = cindyDeviceOptions(
diff --git a/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx b/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx
new file mode 100644
index 0000000000..64f84beca1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx
@@ -0,0 +1,150 @@
+/**
+ * 把多台电脑上各自长出来的 Cindy 合成一个(docs/product-rules/cloud-companions.md,2026-10-16 裁决 2)。
+ * Cindy 的设置里一行「合并重复的 Cindy」:只在云端有两个以上 Cindy 时出现。用户选一个作为资料基准,
+ * 其余的聊天、记忆、技能、待办和例行任务并进来,同名内容另存一份不覆盖,原来的 Cindy 停用。
+ */
+import { useEffect, useRef, useState } from 'react';
+import { Check, Layers } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import type { CompanionCindyCopy, CompanionCloudFailureCode } from '../../../shared/companionCloud';
+import { ensureBotProfilesLoaded } from './botStore';
+import { companionCloudApi, refreshCompanionCloud, useCompanionCloud } from './companionCloudStore';
+
+const MERGE_ERROR_KEYS: Partial<Record<CompanionCloudFailureCode, string>> = {
+ BUSY: 'bots.cloud.mergeBusy',
+ PAUSED: 'bots.cloud.mergePaused',
+ OFFLINE: 'bots.cloud.mergeOffline',
+ HOME_OUTDATED: 'bots.cloud.mergeOutdated',
+};
+
+export function CindyMergeSetting({ bot, className = 'mt-3' }: { bot: { id: string; name: string }; className?: string }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const cloud = useCompanionCloud();
+ const [copies, setCopies] = useState<CompanionCindyCopy[]>([]);
+ const [open, setOpen] = useState(false);
+ const [keep, setKeep] = useState(bot.id);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const inFlight = useRef(false);
+ const actorsKey = cloud.actors.map((actor) => `${actor.externalId}:${actor.homeDeviceId ?? ''}`).join(',');
+
+ useEffect(() => {
+ const api = companionCloudApi();
+ if (!cloud.enabled || !api || typeof api.listCindyCopies !== 'function') { setCopies([]); return; }
+ let live = true;
+ const owner = getDataOwnerGeneration();
+ void api.listCindyCopies().then((next) => { if (live && isDataOwnerGenerationCurrent(owner)) setCopies(next); }, () => undefined);
+ return () => { live = false; };
+ }, [cloud.enabled, actorsKey]);
+
+ if (!copies.some((copy) => copy.botId === bot.id)) return null;
+ const deviceName = (copy: CompanionCindyCopy) => {
+ const actor = cloud.actors.find((candidate) => candidate.externalId === copy.botId);
+ if (copy.homeDeviceId && copy.homeDeviceId === cloud.selfDeviceId) return t('bots.cloud.thisComputer');
+ return actor?.homeDevice?.name?.trim() || t('bots.cloud.unknownDevice');
+ };
+ const devices = copies.map(deviceName).join('、');
+ const kept = copies.find((copy) => copy.botId === keep) ?? copies[0]!;
+
+ const merge = async () => {
+ const api = companionCloudApi();
+ if (!api || inFlight.current) return;
+ inFlight.current = true;
+ setBusy(true);
+ setError(null);
+ const owner = getDataOwnerGeneration();
+ try {
+ const result = await api.mergeCindy(kept.botId, copies.filter((copy) => copy.botId !== kept.botId).map((copy) => copy.botId));
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ refreshCompanionCloud();
+ if (!result.ok) {
+ setError(t(MERGE_ERROR_KEYS[result.code] ?? 'bots.cloud.mergeFailed', { device: deviceName(kept) }));
+ return;
+ }
+ setOpen(false);
+ setCopies([]);
+ toast.info(result.renamed.length
+ ? t('bots.cloud.mergedRenamed', { count: result.merged + 1, messages: result.messages, renamed: result.renamed.join('、') })
+ : t('bots.cloud.merged', { count: result.merged + 1, messages: result.messages }));
+ await ensureBotProfilesLoaded(true).catch(() => undefined);
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ // Open the one Cindy that is left, where it runs.
+ if (kept.botId !== bot.id || kept.homeDeviceId !== cloud.selfDeviceId) {
+ navigate(kept.homeDeviceId && kept.homeDeviceId !== cloud.selfDeviceId
+ ? `/bots/remote/${encodeURIComponent(kept.homeDeviceId)}/${encodeURIComponent(kept.botId)}`
+ : `/bots/${encodeURIComponent(kept.botId)}`);
+ }
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) setError(t('bots.cloud.mergeFailed', { device: deviceName(kept) }));
+ } finally {
+ inFlight.current = false;
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div className={className}>
+ <div className="overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
+ <button
+ type="button"
+ data-testid="cindy-merge-row"
+ onClick={() => { setKeep(bot.id); setError(null); setOpen(true); }}
+ className="flex min-h-12 w-full items-center gap-3 px-4 py-3 text-left text-14 text-[var(--text-primary)] outline-none hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
+ >
+ <Layers size={18} className="shrink-0 text-[var(--text-secondary)]" />
+ <span className="min-w-0 flex-1">
+ <span className="block">{t('bots.cloud.mergeLabel')}</span>
+ <span className="block truncate text-12 text-[var(--text-secondary)]">{t('bots.cloud.mergeHint', { count: copies.length, devices })}</span>
+ </span>
+ </button>
+ </div>
+ <ConfirmDialog
+ open={open}
+ presentation="standard"
+ cancelFirst
+ onOpenChange={(next) => { if (!next && !inFlight.current) setOpen(false); }}
+ title={t('bots.cloud.mergeTitle', { count: copies.length })}
+ description={t('bots.cloud.mergeDescription')}
+ content={(
+ <div className="flex flex-col gap-2" role="radiogroup" aria-label={t('bots.cloud.mergeKeep')}>
+ <p className="text-13 text-[var(--text-secondary)]">{t('bots.cloud.mergeKeep')}</p>
+ {copies.map((copy) => {
+ const selected = copy.botId === kept.botId;
+ return (
+ <button
+ key={copy.botId}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => setKeep(copy.botId)}
+ className={cn(
+ 'flex min-h-11 items-center gap-3 rounded-lg border border-[var(--border-default)] px-3 py-2 text-left text-14 outline-none hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ selected && 'bg-[var(--surface-hover)]',
+ )}
+ >
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[var(--text-primary)]">{copy.name}</span>
+ <span className="block truncate text-12 text-[var(--text-secondary)]">{t('bots.cloud.runsOn', { device: deviceName(copy) })}</span>
+ </span>
+ {selected ? <Check size={16} className="shrink-0 text-[var(--text-primary)]" /> : null}
+ </button>
+ );
+ })}
+ {error ? <p role="alert" className="text-12 text-[var(--text-danger)]">{error}</p> : null}
+ </div>
+ )}
+ confirmText={t('bots.cloud.mergeAction')}
+ cancelText={t('bots.cancel')}
+ loading={busy}
+ onConfirm={() => void merge()}
+ />
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
index 35a2317610..00425541f0 100644
--- a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
+++ b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
@@ -14,7 +14,9 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
import { toast } from '@/lib/toast';
import type { CompanionTranscriptMessage } from '../../../shared/companionCloud';
+import type { BotGroupAttachment } from '../../../shared/botGroupChat';
import { BotAvatar } from './BotAvatar';
+import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
import { BotSessionContentHeaderRegistration, type BotChatIdentity } from './BotSessionContentHeader';
import { ensureBotProfilesLoaded } from './botStore';
import { companionCloudApi, refreshCompanionCloud } from './companionCloudStore';
@@ -182,14 +184,18 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata
<p className="text-center text-13 text-[var(--text-tertiary)]">{t('bots.cloud.empty')}</p>
) : null}
{messages.map((message) => message.role === 'user' ? (
- <article key={message.id} className="flex justify-end">
- <div className={`max-w-[72%] whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-[var(--msg-user-text)] ${CHAT_BODY_CLASS}`}>
- {message.text}
- </div>
+ <article key={message.id} className="flex flex-col items-end gap-2">
+ {message.text ? (
+ <div className={`max-w-[72%] whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-[var(--msg-user-text)] ${CHAT_BODY_CLASS}`}>
+ {message.text}
+ </div>
+ ) : null}
+ {message.attachments?.length ? <CloudMessageAttachments botId={botId} files={message.attachments} align="end" /> : null}
</article>
) : (
- <article key={message.id} className={`min-w-0 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}>
- <MarkdownRenderer workingDir="" content={message.text} allowPrivilegedLinks={false} />
+ <article key={message.id} className={`flex min-w-0 flex-col gap-2 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}>
+ {message.text ? <MarkdownRenderer workingDir="" content={message.text} allowPrivilegedLinks={false} /> : null}
+ {message.attachments?.length ? <CloudMessageAttachments botId={botId} files={message.attachments} align="start" /> : null}
</article>
))}
</div>
@@ -200,3 +206,72 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata
</main>
);
}
+
+/** At most this many room files come down at once (each can be up to 25 MB). */
+export const CLOUD_ATTACHMENT_LOADS = 2;
+let attachmentLoads = 0;
+const attachmentQueue: Array<() => void> = [];
+
+/** Run `load` when a slot is free; a load whose message left the view before its turn is skipped. */
+function queuedAttachmentLoad(load: () => Promise<void>, wanted: () => boolean): void {
+ const start = () => {
+ if (!wanted()) { attachmentQueue.shift()?.(); return; }
+ attachmentLoads += 1;
+ void load().finally(() => { attachmentLoads -= 1; attachmentQueue.shift()?.(); });
+ };
+ if (attachmentLoads < CLOUD_ATTACHMENT_LOADS) start();
+ else attachmentQueue.push(start);
+}
+
+/** True once the element is near the visible part of the conversation (always, without an observer). */
+function useNearView(ref: { current: Element | null }): boolean {
+ const [near, setNear] = useState(() => typeof IntersectionObserver === 'undefined');
+ useEffect(() => {
+ if (near || !ref.current || typeof IntersectionObserver === 'undefined') return;
+ const observer = new IntersectionObserver((entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) setNear(true);
+ }, { rootMargin: '600px 0px' });
+ observer.observe(ref.current);
+ return () => observer.disconnect();
+ }, [near, ref]);
+ return near;
+}
+
+/**
+ * Files of a cloud message, brought to this computer from the companion's room once the message
+ * is near the view, a few at a time: opening a long conversation never starts every download.
+ */
+function CloudMessageAttachments({ botId, files, align }: {
+ botId: string;
+ files: ReadonlyArray<{ mediaId: string; name: string }>;
+ align: 'start' | 'end';
+}) {
+ const [loaded, setLoaded] = useState<Record<string, BotGroupAttachment | 'unavailable'>>({});
+ const key = files.map((file) => file.mediaId).join(',');
+ const box = useRef<HTMLDivElement | null>(null);
+ const near = useNearView(box);
+ useEffect(() => {
+ if (!near) return;
+ const api = companionCloudApi();
+ let live = true;
+ const owner = getDataOwnerGeneration();
+ for (const file of files) {
+ const settle = (value: BotGroupAttachment | 'unavailable') => {
+ if (live && isDataOwnerGenerationCurrent(owner)) setLoaded((current) => ({ ...current, [file.mediaId]: value }));
+ };
+ if (!api || typeof api.getCompanionAttachment !== 'function') { settle('unavailable'); continue; }
+ queuedAttachmentLoad(() => api.getCompanionAttachment(botId, file.mediaId)
+ .then((value) => settle({ ...value, id: file.mediaId }), () => settle('unavailable')),
+ () => live && isDataOwnerGenerationCurrent(owner));
+ }
+ return () => { live = false; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the files' ids
+ }, [botId, key, near]);
+ const attachments: BotGroupAttachment[] = files.map((file) => {
+ const value = loaded[file.mediaId];
+ if (value && value !== 'unavailable') return value;
+ return { id: file.mediaId, name: file.name, category: 'file', mimeType: '', size: 0, url: null, path: null,
+ state: value === 'unavailable' ? 'unavailable' : 'loading' };
+ });
+ return <div ref={box} className="min-w-0 max-w-full"><BotGroupMessageAttachments attachments={attachments} align={align} /></div>;
+}
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index a466c45340..e84be92a12 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@ -13,10 +13,14 @@ import { parseRemoteBots, type RemoteBot } from './remoteBotRoster';
import { markRemoteBotRead, useRemoteBots } from './useRemoteBots';
import { useCompanionCloud } from './companionCloudStore';
import { cloudCompanionAt } from './companionCloudPresentation';
+import { useDelayedFlag } from '@/features/cc-agent/workdir-browse/hooks/useDelayedFlag';
// Loaded only when a main computer is offline; keeps the live remote path light.
const CloudCompanionOfflineView = lazy(() => import('./CloudCompanionOfflineView')
.then((module) => ({ default: module.CloudCompanionOfflineView })));
+/** How long an open chat stays in place while its main computer cannot be reached. */
+export const CLOUD_HOME_GRACE_MS = 15_000;
+
/** The session id comes from the host's collection, never from an arbitrary URL. */
export function RemoteBotSessionView() {
const { deviceId, botId } = useParams();
@@ -94,10 +98,14 @@ export function RemoteBotSessionView() {
}
}, [bot, failed, ready, validatedSessionId]);
+ const liveChat = !!bot && !failed && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
+ const homeAway = !!cloudActor && !!deviceId && !!botId && cloudActor.homeDeviceId !== cloud.selfDeviceId
+ && (!bot || (!bot.online && bot.connectionKnown !== false));
+ // Like IM, a brief drop keeps the open chat in place (cloud-companions.md §3.1).
+ const homeAwayLong = useDelayedFlag(homeAway && liveChat, CLOUD_HOME_GRACE_MS);
// Its main computer is offline (or never reachable here): read the cloud conversation
// and offer to continue on this computer instead of a stale read-only mirror.
- if (cloudActor && deviceId && botId && cloudActor.homeDeviceId !== cloud.selfDeviceId
- && (!bot || (!bot.online && bot.connectionKnown !== false))) {
+ if (cloudActor && deviceId && botId && homeAway && (!liveChat || homeAwayLong)) {
return (
<Suspense fallback={<main className="flex h-full items-center justify-center bg-[var(--surface)]"><Spinner size={18} /></main>}>
<CloudCompanionOfflineView
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
index 4c652a34ab..8065e82467 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
@@ -30,6 +30,8 @@ import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
import type { RemoteBot } from './remoteBotRoster';
import { useCompanionCloud } from './companionCloudStore';
import { cloudCompanionAt } from './companionCloudPresentation';
+import { BotHomeComputerSetting } from './BotHomeComputerSetting';
+import { CindyMergeSetting } from './CindyMergeSetting';
import {
readRemoteBotSettings,
readRemoteBotModelChain,
@@ -58,7 +60,7 @@ export function RemoteBotSettings(props: Props) {
}
function RemoteBotSettingsContent({ bot, beforeCloseRef, onDeleted, initialPage = 'home' }: Props) {
const { t, i18n } = useTranslation();
- // Read-only here: the main computer is changed from that computer's own settings.
+ // The main computer can be changed from here too (it is asked to hand the companion over).
const homeActor = cloudCompanionAt(useCompanionCloud(), bot.deviceId, bot.id);
const { confirm } = useConfirmDialog();
const [data, setData] = useState<RemoteBotSettingsData | null>(null);
@@ -578,9 +580,14 @@ function RemoteBotSettingsContent({ bot, beforeCloseRef, onDeleted, initialPage
const panels = data?.panels ?? [];
return (
<div className="min-h-0 flex-1 overflow-y-auto p-5 text-[var(--text-primary)]">
- <p className="mb-4 truncate text-12 text-[var(--text-tertiary)]">
- {homeActor ? t('bots.cloud.homeReadOnly', { device: homeActor.homeDevice?.name?.trim() || bot.deviceName }) : bot.deviceName}
- </p>
+ {homeActor ? (
+ <>
+ <BotHomeComputerSetting bot={{ id: bot.id, name: bot.name }} className="mb-4" />
+ <CindyMergeSetting bot={{ id: bot.id, name: bot.name }} className="mb-4" />
+ </>
+ ) : (
+ <p className="mb-4 truncate text-12 text-[var(--text-tertiary)]">{bot.deviceName}</p>
+ )}
{page || resourceId !== bot.id ? (
<Button
variant="secondary"
diff --git a/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx b/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
index d4043ebe86..7fe0e44789 100644
--- a/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
+++ b/apps/desktop/src/renderer/features/bots/TeammatesSection.tsx
@@ -35,7 +35,7 @@ import {
import { useAgentIslandActivityMap } from '@/state/agentIslandActivity';
import { useRemoteBots } from './useRemoteBots';
import { useCompanionCloud } from './companionCloudStore';
-import { cloudRemoteBots, isCloudHomeOffline, withoutShadowedBots } from './companionCloudPresentation';
+import { cloudRemoteBots, isCloudCompanionRemote, withoutCloudCompanions, withoutShadowedBots } from './companionCloudPresentation';
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
import { remoteBotKey, isRemoteBotUnread } from './remoteBotRoster';
import { BotConnectionStatus } from './BotConnectionStatus';
@@ -230,7 +230,9 @@ export function TeammatesSection() {
};
// 伙伴搜索并入侧栏总搜索(TeammateSearchResults),段内不再单独筛选。
const roster = partitionBotRoster(rosterBots, { query: '', showHidden });
- const cindyOptions = cindyDeviceOptions(bots, remoteBots, devices ?? [], unreadByBotId, t('bots.devicePicker.local'));
+ // A cloud companion is one row wherever it runs; only per-computer Cindys still merge into one entry.
+ const cindyOptions = cindyDeviceOptions(withoutCloudCompanions(bots, cloud), withoutCloudCompanions(remoteBots, cloud),
+ devices ?? [], unreadByBotId, t('bots.devicePicker.local'));
const hasMultipleCindys = cindyOptions.length > 1;
const routeCindy = cindyOptions.find(option => option.key === cindyDeviceKey({ id: botId ?? '', deviceId }));
// Follow the open Cindy chat; otherwise the local-first roster is the default.
@@ -617,11 +619,11 @@ export function TeammatesSection() {
<button key={remoteBotKey(bot)} type="button" aria-current={selected ? 'page' : undefined}
onClick={() => navigate(`/bots/remote/${encodeURIComponent(bot.deviceId)}/${encodeURIComponent(bot.id)}`)}
className={cn('flex w-full min-w-0 items-center gap-2.5 rounded-xl px-2.5 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring', selected ? 'bg-sidebar-item-active text-sidebar-item-active-foreground' : 'text-[var(--sidebar-nav-text)] hover:bg-sidebar-item-hover')}>
- <span className="relative shrink-0"><BotAvatar bot={bot} size="md" /><BotConnectionStatus online={bot.online} connectionKnown={bot.connectionKnown} deviceName={deviceName} homeOffline={isCloudHomeOffline(cloud, bot)} /></span>
+ <span className="relative shrink-0"><BotAvatar bot={bot} size="md" /><BotConnectionStatus online={bot.online} connectionKnown={bot.connectionKnown} deviceName={deviceName} quiet={isCloudCompanionRemote(cloud, bot)} /></span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="flex min-w-0 items-baseline gap-2">
<span className="min-w-0 truncate text-14 leading-5">{bot.name}</span>
- <BotConnectionStatus inline online={bot.online} connectionKnown={bot.connectionKnown} deviceName={deviceName} homeOffline={isCloudHomeOffline(cloud, bot)} className={selected ? 'opacity-70' : 'text-[var(--sidebar-list-muted)]'} />
+ <BotConnectionStatus inline online={bot.online} connectionKnown={bot.connectionKnown} deviceName={deviceName} quiet={isCloudCompanionRemote(cloud, bot)} className={selected ? 'opacity-70' : 'text-[var(--sidebar-list-muted)]'} />
</span>
<span className={cn('truncate text-12 leading-4', selected ? 'opacity-70' : 'text-[var(--sidebar-list-muted)]')}>{bot.online && bot.generation ? <BotGenerationLabel sessionId={bot.sessionId ?? undefined} {...bot.generation} remote={{ deviceId: bot.deviceId, botId: bot.id }} /> : bot.preview || bot.description || t('bots.list.startChat')}</span>
</span>
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botAvatar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botAvatar.test.tsx
index 7c6bbb8727..3c1a36835e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botAvatar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botAvatar.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
vi_mock_react_i18next();
function vi_mock_react_i18next() {
@@ -17,8 +17,13 @@ import {
isCindyAvatarSentinel,
normalizeBotAvatarHue,
} from '../BotAvatar';
+import { resetCompanionAvatarCacheForTests } from '../companionAvatarCache';
-afterEach(() => cleanup());
+afterEach(() => {
+ cleanup();
+ resetCompanionAvatarCacheForTests();
+ delete (window as { electronAPI?: unknown }).electronAPI;
+});
describe('Bot avatar hue family', () => {
it('resolves every hue to a registered bot-avatar token', () => {
@@ -90,6 +95,34 @@ describe('Managed Bot avatar images', () => {
});
});
+describe('Cloud companion avatar addresses', () => {
+ const cloud = 'https://cdn.example.com/cindy/public/avatar/owner/793983c0-7ed4-47aa-9c00-000000000000.png';
+
+ it('renders a public image address in avatar as artwork, never as text', () => {
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(cloud);
+ expect(container.textContent).toBe('');
+ });
+
+ it('falls back to the initial when the image cannot load', () => {
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ fireEvent.error(container.querySelector('img')!);
+ expect(container.querySelector('img')).toBeNull();
+ expect(container.textContent).toBe('M');
+ });
+
+ it('paints only a single grapheme as text', () => {
+ for (const value of ['http://insecure.example/a.png', 'data:image/png;base64,AAAA', 'not an emoji']) {
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: value, avatarColor: 'violet' }} />);
+ expect(container.querySelector('img')).toBeNull();
+ expect(container.textContent).toBe('M');
+ cleanup();
+ }
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: '🦊', avatarColor: 'violet' }} />);
+ expect(container.textContent).toBe('🦊');
+ });
+});
+
describe('Reserved Cindy avatar sentinel', () => {
it('recognizes the whole cindy://avatar/ namespace, case- and padding-insensitively', () => {
for (const value of [
@@ -162,3 +195,62 @@ describe('BotAvatar rendering', () => {
}
});
});
+
+describe('Local copies of avatars held elsewhere', () => {
+ const cloud = 'https://cdn.example.com/cindy/public/avatar/owner/793983c0.png';
+ const copy = `cindy-media://blobs/${'c'.repeat(64)}.png`;
+ const install = (resolve: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }) => Promise<string | null>) => {
+ const fn = vi.fn(resolve);
+ Object.defineProperty(window, 'electronAPI', { configurable: true, writable: true, value: { maker: { resolveCompanionAvatar: fn } } });
+ return fn;
+ };
+
+ it('shows the local copy first', async () => {
+ install(async () => copy);
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ // Lookup in progress: the tint only, no initial flashing before the image.
+ expect(container.textContent).toBe('');
+ await vi.waitFor(() => expect(container.querySelector('img')?.getAttribute('src')).toBe(copy));
+ });
+
+ it('shows the original when nothing is cached yet and keeps a copy for next time', async () => {
+ const resolve = install(async (request) => (request.fetch ? copy : null));
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ await vi.waitFor(() => expect(container.querySelector('img')?.getAttribute('src')).toBe(cloud));
+ await vi.waitFor(() => expect(resolve).toHaveBeenCalledWith({ avatar: cloud, deviceId: null, fetch: true }));
+ cleanup();
+ // The next avatar of the same companion comes from this computer.
+ const next = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ expect(next.container.querySelector('img')?.getAttribute('src')).toBe(copy);
+ });
+
+ it('asks again on a later display when keeping a copy failed', async () => {
+ let online = false;
+ const resolve = install(async (request) => (request.fetch && online ? copy : null));
+ render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ await vi.waitFor(() => expect(resolve).toHaveBeenCalledWith({ avatar: cloud, deviceId: null, fetch: true }));
+ await vi.waitFor(() => expect(resolve.mock.results.length).toBe(2));
+ await resolve.mock.results[1]!.value;
+ cleanup();
+ online = true;
+ render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ await vi.waitFor(() => expect(resolve.mock.calls.filter(([request]) => request.fetch)).toHaveLength(2));
+ });
+
+ it('falls back to the original address when the local copy cannot load', async () => {
+ install(async () => copy);
+ const { container } = render(<BotAvatar bot={{ name: 'Miao', avatar: cloud, avatarColor: 'violet' }} />);
+ await vi.waitFor(() => expect(container.querySelector('img')?.getAttribute('src')).toBe(copy));
+ fireEvent.error(container.querySelector('img')!);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(cloud);
+ fireEvent.error(container.querySelector('img')!);
+ expect(container.textContent).toBe('M');
+ });
+
+ it('asks for another computer\'s managed avatar with that computer', async () => {
+ const managed = `cindy-media://blobs/${'d'.repeat(64)}.webp`;
+ const resolve = install(async () => copy);
+ render(<BotAvatar bot={{ name: 'Miao', avatar: managed, deviceId: 'laptop', avatarColor: 'violet' }} />);
+ await vi.waitFor(() => expect(resolve).toHaveBeenCalledWith({ avatar: managed, deviceId: 'laptop' }));
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionContentHeader.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionContentHeader.test.tsx
index 9d253c3f8c..cf2c28759a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionContentHeader.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionContentHeader.test.tsx
@@ -32,6 +32,7 @@ vi.mock('../feature-context', () => ({ useRegisterContentHeader: () => undefined
vi.mock('../BotAvatar', () => ({ BotAvatar: () => <span data-testid="bot-avatar" /> }));
const { BotSessionContentHeader } = await import('../BotSessionContentHeader');
+const { resetCompanionCloudStoreForTests } = await import('../companionCloudStore');
const bot = { id: 'bot-1', name: '小可' };
const localCindy = { id: 'local-cindy', name: 'Cindy', templateId: 'cindy', status: 'active' } as import('../botStore').BotProfile;
@@ -46,6 +47,7 @@ function appRegionOf(element: HTMLElement): string {
afterEach(() => {
cleanup();
+ resetCompanionCloudStoreForTests();
navigate.mockClear();
deviceData.local = [];
deviceData.remote = [];
@@ -150,4 +152,16 @@ describe('BotSessionContentHeader', () => {
expect(className).not.toMatch(/shadow|gradient/);
expect(className).toMatch(/rounded-full/);
});
+
+ it('names the main computer of a cloud companion instead of listing per-computer copies', () => {
+ resetCompanionCloudStoreForTests({ enabled: true, selfDeviceId: 'desk', humanActorId: 'human', demotedBotIds: [],
+ actors: [{ id: 'a-cindy', externalId: 'cindy-default', name: 'Cindy', avatar: null, homeDeviceId: 'cloud',
+ homeDevice: { deviceId: 'cloud', name: 'Cloud', online: true, isSelf: false } }] });
+ deviceData.local = [localCindy];
+ deviceData.remote = [remoteCindy];
+ render(<BotSessionContentHeader bot={remoteCindy} />);
+ expect(screen.getByTestId('bot-home-computer-chip').textContent).toContain('bots.cloud.runsOn');
+ expect(screen.queryByRole('combobox', { name: 'bots.devicePicker.switchDevice' })).toBeNull();
+ expect(screen.queryByText('Cloud')).toBeNull();
+ });
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx
new file mode 100644
index 0000000000..3c8a71d9de
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CompanionCloudSnapshot } from '../../../../shared/companionCloud';
+
+const h = vi.hoisted(() => ({ navigate: vi.fn(), toast: vi.fn(), ensureLoaded: vi.fn(async () => []) }));
+vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string, opts?: Record<string, unknown>) => opts ? `${key}:${JSON.stringify(opts)}` : key }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { info: h.toast, error: h.toast } }));
+vi.mock('../botStore', () => ({ ensureBotProfilesLoaded: h.ensureLoaded }));
+
+import { CindyMergeSetting } from '../CindyMergeSetting';
+import { resetCompanionCloudStoreForTests } from '../companionCloudStore';
+
+const maker = {
+ getCompanionCloudState: vi.fn(),
+ onCompanionCloudChanged: vi.fn(() => () => undefined),
+ listCindyCopies: vi.fn(),
+ mergeCindy: vi.fn(),
+};
+const cloud: CompanionCloudSnapshot = {
+ enabled: true, selfDeviceId: 'desk', humanActorId: 'human', demotedBotIds: [],
+ actors: [
+ { id: 'a1', externalId: 'cindy-default', name: 'Cindy', avatar: null, homeDeviceId: 'desk', homeDevice: { deviceId: 'desk', name: 'Desk', online: true, isSelf: true } },
+ { id: 'a2', externalId: 'bot_laptop', name: 'Cindy', avatar: null, homeDeviceId: 'laptop', homeDevice: { deviceId: 'laptop', name: 'Laptop', online: true, isSelf: false } },
+ ],
+};
+const copies = [{ botId: 'cindy-default', name: 'Cindy', homeDeviceId: 'desk' }, { botId: 'bot_laptop', name: 'Cindy', homeDeviceId: 'laptop' }];
+
+beforeEach(() => {
+ for (const fn of Object.values(maker)) fn.mockReset();
+ maker.onCompanionCloudChanged.mockImplementation(() => () => undefined);
+ maker.getCompanionCloudState.mockResolvedValue(cloud);
+ h.navigate.mockReset(); h.toast.mockReset();
+ Object.defineProperty(window, 'electronAPI', { configurable: true, writable: true, value: { maker } });
+ resetCompanionCloudStoreForTests(cloud);
+});
+afterEach(() => { cleanup(); });
+
+describe('CindyMergeSetting', () => {
+ it('is hidden while there is only one Cindy', async () => {
+ maker.listCindyCopies.mockResolvedValue([]);
+ render(<CindyMergeSetting bot={{ id: 'cindy-default', name: 'Cindy' }} />);
+ await waitFor(() => expect(maker.listCindyCopies).toHaveBeenCalled());
+ expect(screen.queryByTestId('cindy-merge-row')).toBeNull();
+ });
+
+ it('lets the user choose which Cindy to keep and merges the others into it', async () => {
+ maker.listCindyCopies.mockResolvedValue(copies);
+ maker.mergeCindy.mockResolvedValue({ ok: true, merged: 1, messages: 12, memories: 3, skills: 0, renamed: [] });
+ render(<CindyMergeSetting bot={{ id: 'cindy-default', name: 'Cindy' }} />);
+ fireEvent.click(await screen.findByTestId('cindy-merge-row'));
+ // Keep the one on the laptop instead.
+ fireEvent.click(screen.getByText('bots.cloud.runsOn:{"device":"Laptop"}'));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.cloud.mergeAction' }));
+ await waitFor(() => expect(maker.mergeCindy).toHaveBeenCalledWith('bot_laptop', ['cindy-default']));
+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/bots/remote/laptop/bot_laptop'));
+ expect(h.toast).toHaveBeenCalledWith('bots.cloud.merged:{"count":2,"messages":12}');
+ });
+
+ it('explains when the kept Cindy\'s computer cannot be reached', async () => {
+ maker.listCindyCopies.mockResolvedValue(copies);
+ maker.mergeCindy.mockResolvedValue({ ok: false, code: 'OFFLINE' });
+ render(<CindyMergeSetting bot={{ id: 'bot_laptop', name: 'Cindy' }} />);
+ fireEvent.click(await screen.findByTestId('cindy-merge-row'));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.cloud.mergeAction' }));
+ expect(await screen.findByRole('alert')).toHaveProperty('textContent', 'bots.cloud.mergeOffline:{"device":"Laptop"}');
+ expect(h.navigate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
index bd43237906..628c5b4b95 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
@@ -6,7 +6,8 @@ import type { CompanionCloudSnapshot } from '../../../../shared/companionCloud';
const h = vi.hoisted(() => ({
navigate: vi.fn(),
toast: vi.fn(),
- ensureLoaded: vi.fn(async () => []),
+ ensureLoaded: vi.fn(async (): Promise<Array<{ id: string; status: string }>> => []),
+ profiles: [] as Array<{ id: string; status: string }>,
devices: [{ deviceId: 'tablet', name: 'Tablet', isSelf: false }],
}));
vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));
@@ -16,23 +17,28 @@ vi.mock('react-i18next', () => ({
vi.mock('@/components/chat/MarkdownRenderer', () => ({ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div> }));
vi.mock('../BotSessionContentHeader', () => ({ BotSessionContentHeaderRegistration: () => null }));
vi.mock('../BotAvatar', () => ({ BotAvatar: () => <span /> }));
-vi.mock('../botStore', () => ({ ensureBotProfilesLoaded: h.ensureLoaded }));
+vi.mock('../BotGroupMessageAttachments', () => ({
+ BotGroupMessageAttachments: ({ attachments }: { attachments: Array<{ name: string; state?: string; url?: string | null }> }) =>
+ <ul>{attachments.map((file) => <li key={file.name}>{`${file.name}:${file.state ?? file.url}`}</li>)}</ul>,
+}));
+vi.mock('../botStore', () => ({ ensureBotProfilesLoaded: h.ensureLoaded, useBotProfiles: () => h.profiles }));
vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({ useDeviceLinkDeviceList: () => h.devices }));
vi.mock('@/lib/toast', () => ({ toast: { info: h.toast, error: h.toast } }));
-import { CloudCompanionOfflineView } from '../CloudCompanionOfflineView';
-import { BotHomeComputerSetting } from '../BotHomeComputerSetting';
+import { CLOUD_ATTACHMENT_LOADS, CloudCompanionOfflineView } from '../CloudCompanionOfflineView';
+import { BotHomeComputerSetting, companionArrivedHere } from '../BotHomeComputerSetting';
import { resetCompanionCloudStoreForTests, useCompanionCloud } from '../companionCloudStore';
-import { cloudOnlyRemoteBots, cloudRemoteBots, isCloudHomeOffline, withoutShadowedBots } from '../companionCloudPresentation';
+import { cloudOnlyRemoteBots, cloudRemoteBots, isCloudCompanionRemote, withoutCloudCompanions, withoutShadowedBots } from '../companionCloudPresentation';
import { BotConnectionStatus } from '../BotConnectionStatus';
const maker = {
getCompanionCloudState: vi.fn(),
onCompanionCloudChanged: vi.fn(() => () => undefined),
getCompanionTranscript: vi.fn(),
+ getCompanionAttachment: vi.fn(),
takeOverCompanion: vi.fn(),
- listCompanionTransferTargets: vi.fn(),
- transferCompanion: vi.fn(),
+ getCompanionHomeChoices: vi.fn(),
+ switchCompanionHome: vi.fn(),
};
const snapshot = (home: string | null, enabled = true): CompanionCloudSnapshot => ({
@@ -59,9 +65,22 @@ describe('presentation helpers', () => {
const extra = cloudOnlyRemoteBots(cloud, []);
expect(extra).toMatchObject([{ id: 'mia', deviceId: 'laptop', deviceName: 'Laptop', online: false }]);
expect(cloudOnlyRemoteBots(cloud, extra)).toEqual([]);
- expect(isCloudHomeOffline(cloud, extra[0])).toBe(true);
- expect(isCloudHomeOffline(cloud, { ...extra[0]!, online: true })).toBe(false);
- expect(isCloudHomeOffline(snapshot('desk'), { id: 'mia', deviceId: 'desk', online: false })).toBe(false);
+ expect(isCloudCompanionRemote(cloud, extra[0]!)).toBe(true);
+ expect(isCloudCompanionRemote(cloud, { id: 'mia', deviceId: 'elsewhere' })).toBe(false);
+ expect(isCloudCompanionRemote(snapshot('desk'), { id: 'mia', deviceId: 'desk' })).toBe(false);
+ });
+
+ it('hides a local copy as soon as its main computer is known to be elsewhere', () => {
+ expect(withoutShadowedBots([{ id: 'mia' }, { id: 'ada' }], snapshot('laptop'))).toEqual([{ id: 'ada' }]);
+ expect(withoutShadowedBots([{ id: 'mia' }], snapshot('desk'))).toEqual([{ id: 'mia' }]);
+ expect(withoutShadowedBots([{ id: 'mia' }], snapshot(null))).toEqual([{ id: 'mia' }]);
+ // Feature off: per-computer behaviour unchanged.
+ expect(withoutShadowedBots([{ id: 'mia' }], snapshot('laptop', false))).toEqual([{ id: 'mia' }]);
+ });
+
+ it('keeps cloud companions out of the per-computer Cindy merge', () => {
+ expect(withoutCloudCompanions([{ id: 'mia' }, { id: 'ada' }], snapshot('laptop'))).toEqual([{ id: 'ada' }]);
+ expect(withoutCloudCompanions([{ id: 'mia' }], snapshot('laptop', false))).toEqual([{ id: 'mia' }]);
});
it('lists a companion once, on its main computer, dropping old computers\' cached copies', () => {
@@ -76,9 +95,11 @@ describe('presentation helpers', () => {
expect(cloudRemoteBots(snapshot('laptop', false), [row('old-mac')])).toHaveLength(1);
});
- it('labels an offline main computer in the row status', () => {
- render(<BotConnectionStatus inline online={false} homeOffline deviceName="Laptop" />);
- expect(screen.getByText('bots.cloud.homeOfflineShort · Laptop')).toBeTruthy();
+ it('does not announce an unreachable main computer in the row status, like IM', () => {
+ const { container } = render(<><BotConnectionStatus inline online={false} quiet deviceName="Laptop" /><BotConnectionStatus online={false} quiet /></>);
+ expect(container.textContent).toBe('Laptop');
+ expect(container.querySelector('[title]')?.getAttribute('title')).toBe('Laptop');
+ expect(container.querySelectorAll('span')).toHaveLength(1);
});
});
@@ -100,6 +121,33 @@ describe('CloudCompanionOfflineView', () => {
expect(screen.getByText('bots.cloud.readOnlyNote')).toBeTruthy();
});
+ it('shows the files of a cloud message, brought from the room', async () => {
+ maker.getCompanionTranscript.mockResolvedValue({ messages: [
+ { id: 'm1', seq: '1', role: 'user', text: '', createdAt: 1, attachments: [{ mediaId: 'media-1', name: 'cat.png' }] }] });
+ maker.getCompanionAttachment.mockResolvedValue({ id: 'media-1', name: 'cat.png', category: 'image', mimeType: 'image/png', size: 3,
+ url: 'cindy-media://blobs/a.png', path: null });
+ renderView();
+ expect(await screen.findByText('cat.png:loading')).toBeTruthy();
+ expect(await screen.findByText('cat.png:cindy-media://blobs/a.png')).toBeTruthy();
+ expect(maker.getCompanionAttachment).toHaveBeenCalledWith('mia', 'media-1');
+ });
+
+ it('brings a long conversation\'s files down a few at a time, never all at once', async () => {
+ const files = Array.from({ length: 5 }, (_, i) => ({ mediaId: `media-${i}`, name: `f${i}.txt` }));
+ maker.getCompanionTranscript.mockResolvedValue({ messages: [{ id: 'm1', seq: '1', role: 'user', text: '', createdAt: 1, attachments: files }] });
+ const pending: Array<() => void> = [];
+ maker.getCompanionAttachment.mockImplementation((_bot: string, mediaId: string) => new Promise((resolve) => {
+ pending.push(() => resolve({ id: mediaId, name: mediaId, category: 'file', mimeType: 'text/plain', size: 1, url: null, path: `/tmp/${mediaId}` }));
+ }));
+ renderView();
+ await waitFor(() => expect(maker.getCompanionAttachment).toHaveBeenCalledTimes(CLOUD_ATTACHMENT_LOADS));
+ await act(async () => { pending.shift()!(); });
+ await waitFor(() => expect(maker.getCompanionAttachment).toHaveBeenCalledTimes(CLOUD_ATTACHMENT_LOADS + 1));
+ while (pending.length) await act(async () => { pending.shift()!(); });
+ await waitFor(() => expect(maker.getCompanionAttachment).toHaveBeenCalledTimes(5));
+ while (pending.length) await act(async () => { pending.shift()!(); });
+ });
+
it('loads older messages on request', async () => {
maker.getCompanionTranscript.mockResolvedValueOnce({ ...page, nextBefore: '1' })
.mockResolvedValueOnce({ messages: [{ id: 'm0', seq: '0', role: 'user', text: 'earlier', createdAt: 0 }] });
@@ -148,64 +196,110 @@ describe('CloudCompanionOfflineView', () => {
describe('BotHomeComputerSetting', () => {
const bot = { id: 'mia', name: 'Mia' };
const openMenu = () => fireEvent.keyDown(screen.getByTestId('bot-home-computer-row'), { key: 'ArrowDown' });
+ const laptop = { deviceId: 'laptop', name: 'Laptop', online: true };
+ const local = (targets = [laptop]) => ({ homeDeviceId: 'desk', mode: 'local', targets });
+ const show = (cloud: CompanionCloudSnapshot, props: Partial<typeof bot & { status: string }> = {}) => {
+ resetCompanionCloudStoreForTests(cloud);
+ maker.getCompanionCloudState.mockResolvedValue(cloud);
+ return render(<BotHomeComputerSetting bot={{ ...bot, ...props }} />);
+ };
+ beforeEach(() => { h.profiles = []; h.ensureLoaded.mockReset(); h.ensureLoaded.mockResolvedValue([]); });
it.each([
['the feature is off', snapshot('desk', false)],
- ['the home is another computer', snapshot('laptop')],
+ ['the companion has no main computer yet', snapshot(null)],
])('is hidden when %s', (_name, cloud) => {
- resetCompanionCloudStoreForTests(cloud);
- maker.getCompanionCloudState.mockResolvedValue(cloud);
- render(<BotHomeComputerSetting bot={bot} />);
+ show(cloud);
expect(screen.queryByTestId('bot-home-computer-row')).toBeNull();
});
it('confirms before moving the companion, then opens it on the new computer', async () => {
- resetCompanionCloudStoreForTests(snapshot('desk'));
- maker.getCompanionCloudState.mockResolvedValue(snapshot('desk'));
- maker.listCompanionTransferTargets.mockResolvedValue([{ deviceId: 'laptop', name: 'Laptop', online: true }]);
- maker.transferCompanion.mockResolvedValue({ ok: true });
- render(<BotHomeComputerSetting bot={bot} />);
+ maker.getCompanionHomeChoices.mockResolvedValue(local());
+ maker.switchCompanionHome.mockResolvedValue({ ok: true });
+ show(snapshot('desk'));
expect(screen.getByText('bots.cloud.thisComputer')).toBeTruthy();
openMenu();
- const item = await screen.findByText('bots.cloud.moveTo:{"device":"Laptop"}');
- fireEvent.click(item);
- await screen.findByText('bots.cloud.transferDescription:{"name":"Mia","device":"Laptop"}');
- expect(maker.transferCompanion).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: 'bots.cloud.transferAction:{"device":"Laptop"}' }));
+ fireEvent.click(await screen.findByText('bots.cloud.switchTo:{"device":"Laptop"}'));
+ await screen.findByText('bots.cloud.switchDescription:{"name":"Mia","device":"Laptop"}');
+ expect(maker.switchCompanionHome).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.cloud.switchAction:{"device":"Laptop"}' }));
await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/bots/remote/laptop/mia'));
- expect(maker.transferCompanion).toHaveBeenCalledWith('mia', 'laptop');
+ expect(maker.switchCompanionHome).toHaveBeenCalledWith('mia', 'laptop', undefined);
+ expect(maker.getCompanionHomeChoices).toHaveBeenCalledWith('mia');
+ });
+
+ it('shows where a companion homed on another computer runs, and moves it to this one', async () => {
+ maker.getCompanionHomeChoices.mockResolvedValue({ homeDeviceId: 'laptop', mode: 'remote',
+ targets: [{ deviceId: 'desk', name: 'Desk', online: true, isSelf: true }, { deviceId: 'tablet', name: 'Tablet', online: true, isSelf: false }] });
+ maker.switchCompanionHome.mockResolvedValue({ ok: true });
+ const arrived = snapshot('desk');
+ show(snapshot('laptop'));
+ expect(screen.getByText('Laptop')).toBeTruthy();
+ openMenu();
+ expect(await screen.findByText('bots.cloud.switchTo:{"device":"Tablet"}')).toBeTruthy();
+ fireEvent.click(screen.getByText('bots.cloud.switchHere'));
+ // The move reaches this computer, which builds the companion before it opens.
+ h.ensureLoaded.mockImplementation(async () => {
+ resetCompanionCloudStoreForTests(arrived);
+ return [{ id: 'mia', status: 'active' }];
+ });
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.cloud.switchAction:{"device":"bots.cloud.thisComputer"}' }));
+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/bots/mia'));
+ expect(maker.switchCompanionHome).toHaveBeenCalledWith('mia', 'desk', undefined);
+ });
+
+ it('explains when the main computer runs an older Cindy', async () => {
+ maker.getCompanionHomeChoices.mockResolvedValue({ homeDeviceId: 'laptop', mode: 'unavailable', reason: 'HOME_OUTDATED', targets: [] });
+ show(snapshot('laptop'));
+ openMenu();
+ expect(await screen.findByText('bots.cloud.homeOutdated:{"name":"Mia","device":"Laptop"}')).toBeTruthy();
});
it('shows why a move did not happen', async () => {
- resetCompanionCloudStoreForTests(snapshot('desk'));
- maker.getCompanionCloudState.mockResolvedValue(snapshot('desk'));
- maker.listCompanionTransferTargets.mockResolvedValue([{ deviceId: 'laptop', name: 'Laptop', online: true }]);
- maker.transferCompanion.mockResolvedValue({ ok: false, code: 'OFFLINE' });
- render(<BotHomeComputerSetting bot={bot} />);
+ maker.getCompanionHomeChoices.mockResolvedValue(local());
+ maker.switchCompanionHome.mockResolvedValue({ ok: false, code: 'OFFLINE' });
+ show(snapshot('desk'));
openMenu();
- fireEvent.click(await screen.findByText('bots.cloud.moveTo:{"device":"Laptop"}'));
- fireEvent.click(await screen.findByRole('button', { name: 'bots.cloud.transferAction:{"device":"Laptop"}' }));
- expect(await screen.findByRole('alert')).toHaveProperty('textContent', 'bots.cloud.transferOffline:{"name":"Mia","device":"Laptop"}');
+ fireEvent.click(await screen.findByText('bots.cloud.switchTo:{"device":"Laptop"}'));
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.cloud.switchAction:{"device":"Laptop"}' }));
+ expect(await screen.findByRole('alert')).toHaveProperty('textContent', 'bots.cloud.switchOffline:{"name":"Mia","device":"Laptop"}');
expect(h.navigate).not.toHaveBeenCalled();
});
+ it.each([['busyWait', 'wait'], ['busyStop', 'stop']])('offers to wait for or stop a reply in progress (%s)', async (button, whenBusy) => {
+ maker.getCompanionHomeChoices.mockResolvedValue(local());
+ maker.switchCompanionHome.mockResolvedValueOnce({ ok: false, code: 'BUSY' }).mockResolvedValueOnce({ ok: true });
+ show(snapshot('desk'));
+ openMenu();
+ fireEvent.click(await screen.findByText('bots.cloud.switchTo:{"device":"Laptop"}'));
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.cloud.switchAction:{"device":"Laptop"}' }));
+ await screen.findByText('bots.cloud.busyDescription:{"name":"Mia","device":"Laptop"}');
+ fireEvent.click(screen.getByRole('button', { name: `bots.cloud.${button}` }));
+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/bots/remote/laptop/mia'));
+ expect(maker.switchCompanionHome).toHaveBeenLastCalledWith('mia', 'laptop', { whenBusy });
+ });
+
it('asks to resume a paused companion before moving it', async () => {
- resetCompanionCloudStoreForTests(snapshot('desk'));
- maker.getCompanionCloudState.mockResolvedValue(snapshot('desk'));
- render(<BotHomeComputerSetting bot={{ ...bot, status: 'paused' }} />);
+ show(snapshot('desk'), { status: 'paused' });
openMenu();
expect(await screen.findByText('bots.cloud.resumeToMove:{"name":"Mia"}')).toBeTruthy();
- expect(maker.listCompanionTransferTargets).not.toHaveBeenCalled();
+ expect(maker.getCompanionHomeChoices).not.toHaveBeenCalled();
});
it('says when no other computer can take over', async () => {
- resetCompanionCloudStoreForTests(snapshot('desk'));
- maker.getCompanionCloudState.mockResolvedValue(snapshot('desk'));
- maker.listCompanionTransferTargets.mockResolvedValue([]);
- render(<BotHomeComputerSetting bot={bot} />);
+ maker.getCompanionHomeChoices.mockResolvedValue(local([]));
+ show(snapshot('desk'));
openMenu();
expect(await screen.findByText('bots.cloud.noTargets')).toBeTruthy();
});
+
+ it('counts a companion as arrived only once it is built here and no longer demoted', () => {
+ const cloud = snapshot('desk');
+ expect(companionArrivedHere(cloud, 'mia', [])).toBe(false);
+ expect(companionArrivedHere({ ...cloud, demotedBotIds: ['mia'] }, 'mia', ['mia'])).toBe(false);
+ expect(companionArrivedHere(snapshot('laptop'), 'mia', ['mia'])).toBe(false);
+ expect(companionArrivedHere(cloud, 'mia', ['mia'])).toBe(true);
+ });
});
describe('companionCloudStore', () => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index 88b610df98..ca5127215c 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@ -50,7 +50,7 @@ vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({
return <div>remote-conversation</div>;
},
}));
-import { RemoteBotSessionView } from '../RemoteBotSessionView';
+import { CLOUD_HOME_GRACE_MS, RemoteBotSessionView } from '../RemoteBotSessionView';
beforeEach(() => {
h.markRead.mockClear();
h.online = true;
@@ -118,14 +118,30 @@ it('never mounts a task with a mismatched authoritative source', async () => {
await screen.findByText('bots.sessionLoadFailedDescription');
expect(h.view).not.toHaveBeenCalled();
});
-it('shows the cloud conversation instead of a stale mirror when the main computer is offline', async () => {
+it('keeps the open chat through a brief drop, then shows the cloud conversation when the main computer stays offline', async () => {
h.cloud = { enabled: true, selfDeviceId: 'desk', humanActorId: 'human', demotedBotIds: [], actors: [
{ id: 'a-writer', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'home' }] };
const { rerender } = render(<RemoteBotSessionView />);
await screen.findByText('remote-conversation');
- h.online = false;
- rerender(<RemoteBotSessionView />);
- await screen.findByText('cloud-offline-view');
+ vi.useFakeTimers();
+ try {
+ h.online = false;
+ rerender(<RemoteBotSessionView />);
+ act(() => { vi.advanceTimersByTime(CLOUD_HOME_GRACE_MS - 1); });
+ expect(screen.queryByText('cloud-offline-view')).toBeNull();
+ expect(screen.getByText('remote-conversation')).toBeTruthy();
+ // Back before the grace ends: nothing changed for the reader.
+ h.online = true;
+ rerender(<RemoteBotSessionView />);
+ h.online = false;
+ rerender(<RemoteBotSessionView />);
+ act(() => { vi.advanceTimersByTime(CLOUD_HOME_GRACE_MS - 1); });
+ expect(screen.queryByText('cloud-offline-view')).toBeNull();
+ act(() => { vi.advanceTimersByTime(1); });
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(await screen.findByText('cloud-offline-view')).toBeTruthy();
expect(h.cloudView).toHaveBeenLastCalledWith(expect.objectContaining({ botId: 'writer', deviceId: 'home', name: 'Writer', deviceName: 'Home' }));
// Another computer as the cloud home keeps the existing offline behaviour.
h.cloud = { ...h.cloud, actors: [{ ...h.cloud.actors[0]!, homeDeviceId: 'elsewhere' }] };
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/teammatesSection.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/teammatesSection.test.tsx
index 1942503375..88f5284e0b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/teammatesSection.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/teammatesSection.test.tsx
@@ -822,7 +822,7 @@ describe('cloud companions in the roster', () => {
const rows = screen.getAllByText('Mia');
expect(rows).toHaveLength(1);
const row = rows[0]!.closest('button')!;
- expect(row.textContent).toContain('bots.cloud.homeOfflineShort');
+ expect(row.textContent).not.toContain('bots.remote.offline');
fireEvent.click(row);
expect(mocks.navigate).toHaveBeenCalledWith('/bots/remote/laptop/mia');
});
diff --git a/apps/desktop/src/renderer/features/bots/companionAvatarCache.ts b/apps/desktop/src/renderer/features/bots/companionAvatarCache.ts
new file mode 100644
index 0000000000..bac7c193c3
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/companionAvatarCache.ts
@@ -0,0 +1,84 @@
+/**
+ * Renderer side of the local avatar cache (main `companion-cloud/avatarCache.ts`): an avatar
+ * held by another computer or the cloud is looked up locally first. A miss shows the original
+ * address as before and keeps a copy in the background, so the next time (an offline main
+ * computer, a restart) it comes from this computer.
+ */
+import { useEffect, useState } from 'react';
+
+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+
+export interface CompanionAvatarSource {
+ avatar: string;
+ /** The computer holding a `cindy-media://` avatar; null for a public cloud image. */
+ deviceId: string | null;
+}
+
+type Api = { resolveCompanionAvatar?: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }) => Promise<string | null> };
+
+/** Resolved local addresses (null = not cached) per owner; never shared across accounts. */
+let ownerKey = '';
+let resolved = new Map<string, string | null>();
+const pending = new Map<string, Promise<string | null>>();
+
+function api(): Api['resolveCompanionAvatar'] | null {
+ if (typeof window === 'undefined') return null;
+ const maker = (window as { electronAPI?: { maker?: Api } }).electronAPI?.maker;
+ return typeof maker?.resolveCompanionAvatar === 'function' ? maker.resolveCompanionAvatar.bind(maker) : null;
+}
+
+function scoped(): Map<string, string | null> {
+ const owner = getDataOwnerGeneration();
+ const key = `${owner.dataOwnerId}:${owner.generation}`;
+ if (key !== ownerKey) { ownerKey = key; resolved = new Map(); pending.clear(); }
+ return resolved;
+}
+
+const keyOf = (source: CompanionAvatarSource) => `${source.deviceId ?? ''}\n${source.avatar}`;
+
+function lookup(source: CompanionAvatarSource): Promise<string | null> {
+ const resolve = api();
+ const map = scoped();
+ const key = keyOf(source);
+ if (!resolve) return Promise.resolve(null);
+ const inFlight = pending.get(key);
+ if (inFlight) return inFlight;
+ const run = resolve({ avatar: source.avatar, deviceId: source.deviceId }).catch(() => null).then((url) => {
+ if (scoped() === map) map.set(key, url);
+ // Not cached yet: keep a copy for next time; this mount keeps the original address.
+ // A failed copy is forgotten, so a later display asks again (the main process paces retries).
+ if (!url) void resolve({ avatar: source.avatar, deviceId: source.deviceId, fetch: true }).catch(() => null)
+ .then((copy) => { if (scoped() !== map) return; if (copy) map.set(key, copy); else map.delete(key); });
+ return url;
+ }).finally(() => { pending.delete(key); });
+ pending.set(key, run);
+ return run;
+}
+
+/**
+ * Local address for `source`: undefined while the (fast, local) lookup runs, null when there is
+ * no copy here yet (show the original), or a `cindy-media://` address.
+ */
+export function useCachedCompanionAvatar(source: CompanionAvatarSource | null): string | null | undefined {
+ const key = source ? keyOf(source) : null;
+ const known = () => (source ? (api() ? scoped().get(keyOf(source)) : null) : null);
+ const [value, setValue] = useState<string | null | undefined>(known);
+ useEffect(() => {
+ if (!source) { setValue(null); return; }
+ const hit = known();
+ setValue(hit);
+ if (hit !== undefined) return;
+ let live = true;
+ void lookup(source).then((url) => { if (live) setValue(url); });
+ return () => { live = false; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the source address
+ }, [key]);
+ return source ? value : null;
+}
+
+/** Test-only reset. */
+export function resetCompanionAvatarCacheForTests(): void {
+ ownerKey = '';
+ resolved = new Map();
+ pending.clear();
+}
diff --git a/apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts b/apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts
index ba2bf2d1f9..9485b810f8 100644
--- a/apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts
+++ b/apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts
@@ -2,13 +2,27 @@ import type { CompanionCloudActor, CompanionCloudSnapshot } from '../../../share
import type { RemoteBot } from './remoteBotRoster';
/**
- * Local copies whose home moved to another computer stay out of the roster and entry choice.
- * The shadow list is persisted in main, so it applies offline and with the feature off too.
+ * Local copies whose home moved to another computer stay out of the roster and entry choice:
+ * the companion is listed once, where it runs. The shadow list is persisted in main, so it
+ * applies offline and with the feature off too; a known cloud home elsewhere hides the copy
+ * even before its demotion is published.
*/
export function withoutShadowedBots<T extends { id: string }>(bots: readonly T[], cloud: CompanionCloudSnapshot): T[] {
- if (cloud.demotedBotIds.length === 0) return [...bots];
const shadowed = new Set(cloud.demotedBotIds);
- return bots.filter((bot) => !shadowed.has(bot.id));
+ const elsewhere = new Set(cloud.enabled && cloud.selfDeviceId ? cloud.actors.flatMap((actor) =>
+ actor.homeDeviceId && actor.homeDeviceId !== cloud.selfDeviceId ? [actor.externalId] : []) : []);
+ if (shadowed.size === 0 && elsewhere.size === 0) return [...bots];
+ return bots.filter((bot) => !shadowed.has(bot.id) && !elsewhere.has(bot.id));
+}
+
+/**
+ * Companions the cloud already lists once (their home is known) are not per-computer copies:
+ * leave them out of the older multi-computer Cindy picker.
+ */
+export function withoutCloudCompanions<T extends { id: string }>(bots: readonly T[], cloud: CompanionCloudSnapshot): T[] {
+ if (!cloud.enabled) return [...bots];
+ const homed = new Set(cloud.actors.flatMap((actor) => actor.homeDeviceId ? [actor.externalId] : []));
+ return bots.filter((bot) => !homed.has(bot.id));
}
/** The cloud companion whose home is `deviceId`, when the feature is on. */
@@ -17,11 +31,10 @@ export function cloudCompanionAt(cloud: CompanionCloudSnapshot, deviceId: string
return cloud.actors.find((actor) => actor.externalId === botId && actor.homeDeviceId === deviceId) ?? null;
}
-/** A remote companion whose home computer cannot be reached right now. */
-export function isCloudHomeOffline(cloud: CompanionCloudSnapshot, bot: Pick<RemoteBot, 'id' | 'deviceId' | 'online'> | undefined, deviceId?: string, botId?: string): boolean {
- const actor = cloudCompanionAt(cloud, bot?.deviceId ?? deviceId, bot?.id ?? botId);
- if (!actor || actor.homeDeviceId === cloud.selfDeviceId) return false;
- return !bot?.online;
+/** A remote companion homed on that computer: its connection is not announced (cloud-companions.md §3.1). */
+export function isCloudCompanionRemote(cloud: CompanionCloudSnapshot, bot: Pick<RemoteBot, 'id' | 'deviceId'>): boolean {
+ const actor = cloudCompanionAt(cloud, bot.deviceId, bot.id);
+ return !!actor && actor.homeDeviceId !== cloud.selfDeviceId;
}
/**
diff --git a/apps/desktop/src/renderer/features/bots/companionCloudStore.ts b/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
index 7d38af95d9..ffe6e37492 100644
--- a/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
+++ b/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
@@ -93,6 +93,11 @@ export function useCompanionCloud(): CompanionCloudSnapshot {
return useSyncExternalStore(subscribe, read, read);
}
+/** Latest snapshot outside React (e.g. while waiting for a companion to arrive here). */
+export function getCompanionCloudSnapshot(): CompanionCloudSnapshot {
+ return read();
+}
+
/** Test-only reset of the module mirror. */
export function resetCompanionCloudStoreForTests(next: CompanionCloudSnapshot = EMPTY_COMPANION_CLOUD_SNAPSHOT): void {
owner = getDataOwnerGeneration();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index eefedf1e55..83cfb8c1fb 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8914,7 +8914,8 @@
"failed": "Didn't finish",
"paused": "Paused",
"disabled": "Turned off"
- }
+ },
+ "dirElsewhere": "On “{{device}}”"
},
"remoteSettings": {
"empty": "Nothing here yet.",
@@ -9775,9 +9776,7 @@
"homeLabel": "Main Computer",
"thisComputer": "This computer",
"homeOffline": "Main computer “{{device}}” is offline",
- "homeOfflineShort": "Main computer offline",
"homeUnreachable": "Main computer “{{device}}” doesn’t allow remote control",
- "homeReadOnly": "Main computer: {{device}}",
"continueHere": "Continue on This Computer",
"takeOverHint": "{{name}} will run here from now on, and the conversation below comes along.",
"takingOver": "Getting {{name}} ready on this computer…",
@@ -9795,19 +9794,43 @@
"devicesFailed": "Couldn’t load your computers",
"noTargets": "No computer can take over. The other computer must be online, signed in to the same account, and have “Allow same-account devices to control this machine” turned on",
"resumeToMove": "Resume {{name}} before moving it to another computer",
- "moveTo": "Move to “{{device}}”",
- "transferTitle": "Move {{name}} to “{{device}}”?",
- "transferDescription": "From now on {{name}} runs on “{{device}}”. The working directory and connections stay on this computer, and the conversation here becomes history.",
- "transferAction": "Move to “{{device}}”",
- "transferred": "{{name}} moved to “{{device}}”",
- "transferConflict": "{{name}}’s main computer has already changed, so it wasn’t moved",
- "transferOffline": "Can’t reach the server. {{name}} still runs on this computer",
"transferBusy": "{{name}} is still working on a reply. Move it after the reply finishes",
- "transferFailed": "Couldn’t move {{name}} to “{{device}}”",
"targetUnavailable": "“{{device}}” isn’t available. It must be online with remote control turned on",
"shadowTitle": "This teammate now runs on “{{device}}”",
"shadowHint": "The conversation here is read only.",
- "openOnHome": "Open on “{{device}}”"
+ "openOnHome": "Open on “{{device}}”",
+ "runsOn": "Runs on “{{device}}”",
+ "runsHere": "Runs on this computer",
+ "switchHint": "Change the computer {{name}} runs on",
+ "switchTo": "Move to “{{device}}”",
+ "switchHere": "Move to This Computer",
+ "switchTitle": "Run {{name}} on “{{device}}”?",
+ "switchDescription": "From now on {{name}} runs on “{{device}}”, and the chat history comes along. Working directories, connections and local files stay on the computer they are on.",
+ "switchAction": "Move to “{{device}}”",
+ "switched": "{{name}} now runs on “{{device}}”",
+ "switchConflict": "{{name}}’s main computer has already changed, so it wasn’t moved",
+ "switchOffline": "Couldn’t connect. {{name}}’s main computer hasn’t changed",
+ "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",
+ "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",
+ "busyStop": "Stop and Move",
+ "waitingForTurn": "Waiting for {{name}} to finish, then moving it to “{{device}}”…",
+ "mergeLabel": "Merge Duplicate Cindys",
+ "mergeHint": "You have {{count}} Cindys: {{devices}}",
+ "mergeTitle": "Merge {{count}} Cindys into one?",
+ "mergeDescription": "Only one Cindy remains. The others’ chat history, memories, skills, todos and routines come along; a memory or skill with the same name but different content is kept as a second copy, never overwritten. The other Cindys are turned off; their data stays in the cloud and on their computers.",
+ "mergeKeep": "Keep the name, personality and settings of",
+ "mergeAction": "Merge",
+ "merged": "{{count}} Cindys merged into one, with {{messages}} messages brought along",
+ "mergedRenamed": "{{count}} Cindys merged into one, with {{messages}} messages brought along. Kept as copies: {{renamed}}",
+ "mergeFailed": "Couldn’t merge. Try again later (what was merged won’t be duplicated)",
+ "mergeBusy": "One of the Cindys is still replying. Merge once it finishes",
+ "mergePaused": "One of the Cindys is paused. Resume it in its settings, then merge",
+ "mergeOffline": "Can’t reach “{{device}}”. Merge once it’s online",
+ "mergeOutdated": "“{{device}}” runs an older Cindy. Update it first"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3687a767ff..2ee8f1e345 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8868,7 +8868,8 @@
"failed": "完了しませんでした",
"paused": "一時停止中",
"disabled": "オフ"
- }
+ },
+ "dirElsewhere": "「{{device}}」上"
},
"remoteSettings": {
"empty": "まだ項目がありません。",
@@ -9729,9 +9730,7 @@
"homeLabel": "メインのパソコン",
"thisComputer": "このパソコン",
"homeOffline": "メインのパソコン「{{device}}」がオフラインです",
- "homeOfflineShort": "メインのパソコンがオフライン",
"homeUnreachable": "メインのパソコン「{{device}}」はリモート操作を許可していません",
- "homeReadOnly": "メインのパソコン:{{device}}",
"continueHere": "このパソコンで続ける",
"takeOverHint": "このパソコンで続けると、{{name}} はこちらで動作し、下の会話も引き継がれます。",
"takingOver": "このパソコンで {{name}} を準備しています…",
@@ -9749,19 +9748,43 @@
"devicesFailed": "パソコンの一覧を読み込めませんでした",
"noTargets": "引き継げるパソコンがありません。別のパソコンがオンラインで、同じアカウントでログインし、「同一アカウントのデバイスによる操作を許可」をオンにしている必要があります",
"resumeToMove": "{{name}} を再開してから別のパソコンに移動してください",
- "moveTo": "「{{device}}」に移す",
- "transferTitle": "{{name}} を「{{device}}」に移しますか?",
- "transferDescription": "これから {{name}} は「{{device}}」で動作します。作業ディレクトリと接続はこのパソコンに残り、このパソコンの会話は履歴になります。",
- "transferAction": "「{{device}}」に移す",
- "transferred": "{{name}} を「{{device}}」に移しました",
- "transferConflict": "{{name}} のメインのパソコンはすでに変わっているため、移しませんでした",
- "transferOffline": "サーバーに接続できません。{{name}} は引き続きこのパソコンで動作します",
"transferBusy": "{{name}} はまだ返信中です。返信が終わってから移動してください",
- "transferFailed": "{{name}} を「{{device}}」に移せませんでした",
"targetUnavailable": "「{{device}}」は今は使えません。オンラインでリモート操作がオンになっている必要があります",
"shadowTitle": "この仲間は「{{device}}」で動作しています",
"shadowHint": "ここの会話は閲覧のみできます。",
- "openOnHome": "「{{device}}」で開く"
+ "openOnHome": "「{{device}}」で開く",
+ "runsOn": "「{{device}}」で実行中",
+ "runsHere": "このパソコンで実行中",
+ "switchHint": "{{name}} を実行するパソコンを変更",
+ "switchTo": "「{{device}}」に移す",
+ "switchHere": "このパソコンに移す",
+ "switchTitle": "{{name}} を「{{device}}」で実行しますか?",
+ "switchDescription": "今後 {{name}} は「{{device}}」で実行され、チャット履歴も一緒に移ります。作業ディレクトリ、接続、ローカルのファイルは元のパソコンに残ります。",
+ "switchAction": "「{{device}}」に移す",
+ "switched": "{{name}} は「{{device}}」で実行されるようになりました",
+ "switchConflict": "{{name}} のメインのパソコンはすでに変更されているため、移しませんでした",
+ "switchOffline": "接続できません。{{name}} のメインのパソコンは変わっていません",
+ "switchFailed": "{{name}} を「{{device}}」に移せませんでした",
+ "homeOutdated": "メインのパソコン「{{device}}」の Cindy が古いバージョンです。更新するか、そのパソコンで変更してください",
+ "arrivingLater": "{{name}} はこのパソコンに移り、準備中です。まもなくチームメイト一覧に表示されます",
+ "busyTitle": "{{name}} はまだ返信中です",
+ "busyDescription": "この返信が終わってから「{{device}}」に移すか、返信を止めてすぐに移せます。",
+ "busyWait": "終わってから移す",
+ "busyStop": "止めて移す",
+ "waitingForTurn": "{{name}} の返信が終わるのを待ってから「{{device}}」に移します…",
+ "mergeLabel": "重複した Cindy を統合",
+ "mergeHint": "Cindy が {{count}} 人います:{{devices}}",
+ "mergeTitle": "{{count}} 人の Cindy を1人に統合しますか?",
+ "mergeDescription": "統合後は Cindy が1人だけ残ります。ほかの Cindy のチャット履歴、記憶、スキル、ToDo、ルーティンが引き継がれます。同じ名前で内容が違う記憶とスキルは別に保存され、上書きされません。ほかの Cindy はオフになり、データはクラウドと元のパソコンに残ります。",
+ "mergeKeep": "名前、性格、設定を残す Cindy",
+ "mergeAction": "統合",
+ "merged": "{{count}} 人の Cindy を1人に統合し、{{messages}} 件のメッセージを引き継ぎました",
+ "mergedRenamed": "{{count}} 人の Cindy を1人に統合し、{{messages}} 件のメッセージを引き継ぎました。別名で保存:{{renamed}}",
+ "mergeFailed": "統合できませんでした。あとでもう一度お試しください(統合済みの部分は重複しません)",
+ "mergeBusy": "まだ返信中の Cindy があります。返信が終わってから統合してください",
+ "mergePaused": "一時停止中の Cindy があります。設定で再開してから統合してください",
+ "mergeOffline": "「{{device}}」に接続できません。オンラインになってから統合してください",
+ "mergeOutdated": "「{{device}}」の Cindy が古いバージョンです。先に更新してください"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1411239f2c..89e7c9b99e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8868,7 +8868,8 @@
"failed": "끝내지 못했습니다",
"paused": "일시 중지됨",
"disabled": "꺼짐"
- }
+ },
+ "dirElsewhere": "“{{device}}”에 있음"
},
"remoteSettings": {
"empty": "아직 항목이 없습니다.",
@@ -9729,9 +9730,7 @@
"homeLabel": "주 컴퓨터",
"thisComputer": "이 컴퓨터",
"homeOffline": "주 컴퓨터 '{{device}}' 오프라인",
- "homeOfflineShort": "주 컴퓨터 오프라인",
"homeUnreachable": "주 컴퓨터 '{{device}}'에서 원격 제어를 허용하지 않았습니다",
- "homeReadOnly": "주 컴퓨터: {{device}}",
"continueHere": "이 컴퓨터에서 계속하기",
"takeOverHint": "이 컴퓨터에서 계속하면 {{name}}이(가) 여기에서 실행되고 아래 대화도 함께 옮겨집니다.",
"takingOver": "이 컴퓨터에서 {{name}}을(를) 준비하는 중…",
@@ -9749,19 +9748,43 @@
"devicesFailed": "컴퓨터 목록을 불러오지 못했습니다",
"noTargets": "이어받을 수 있는 컴퓨터가 없습니다. 다른 컴퓨터가 온라인 상태이고 같은 계정으로 로그인한 뒤 '동일 계정 기기의 이 컴퓨터 제어 허용'을 켜야 합니다",
"resumeToMove": "{{name}}을(를) 다시 시작한 뒤 다른 컴퓨터로 옮겨 주세요",
- "moveTo": "'{{device}}'(으)로 옮기기",
- "transferTitle": "{{name}}을(를) '{{device}}'(으)로 옮길까요?",
- "transferDescription": "이제부터 {{name}}은(는) '{{device}}'에서 실행됩니다. 작업 디렉터리와 연결은 이 컴퓨터에 남고, 이 컴퓨터의 대화는 기록이 됩니다.",
- "transferAction": "'{{device}}'(으)로 옮기기",
- "transferred": "{{name}}을(를) '{{device}}'(으)로 옮겼습니다",
- "transferConflict": "{{name}}의 주 컴퓨터가 이미 바뀌어 옮기지 않았습니다",
- "transferOffline": "서버에 연결할 수 없습니다. {{name}}은(는) 계속 이 컴퓨터에서 실행됩니다",
"transferBusy": "{{name}}이(가) 아직 답장 중입니다. 답장이 끝난 뒤 옮겨 주세요",
- "transferFailed": "{{name}}을(를) '{{device}}'(으)로 옮기지 못했습니다",
"targetUnavailable": "'{{device}}'은(는) 지금 사용할 수 없습니다. 온라인 상태이고 원격 제어가 켜져 있어야 합니다",
"shadowTitle": "이 동료는 '{{device}}'에서 실행 중입니다",
"shadowHint": "여기 대화는 보기만 할 수 있습니다.",
- "openOnHome": "'{{device}}'에서 열기"
+ "openOnHome": "'{{device}}'에서 열기",
+ "runsOn": "“{{device}}”에서 실행 중",
+ "runsHere": "이 컴퓨터에서 실행 중",
+ "switchHint": "{{name}}이(가) 실행되는 컴퓨터 변경",
+ "switchTo": "“{{device}}”(으)로 옮기기",
+ "switchHere": "이 컴퓨터로 옮기기",
+ "switchTitle": "{{name}}을(를) “{{device}}”에서 실행할까요?",
+ "switchDescription": "이제부터 {{name}}은(는) “{{device}}”에서 실행되며 채팅 기록도 함께 옮겨집니다. 작업 디렉터리, 연결, 로컬 파일은 원래 컴퓨터에 남습니다.",
+ "switchAction": "“{{device}}”(으)로 옮기기",
+ "switched": "{{name}}이(가) 이제 “{{device}}”에서 실행됩니다",
+ "switchConflict": "{{name}}의 주 컴퓨터가 이미 바뀌어 이번에는 옮기지 않았습니다",
+ "switchOffline": "연결할 수 없습니다. {{name}}의 주 컴퓨터는 바뀌지 않았습니다",
+ "switchFailed": "{{name}}을(를) “{{device}}”(으)로 옮기지 못했습니다",
+ "homeOutdated": "주 컴퓨터 “{{device}}”의 Cindy가 이전 버전입니다. 업데이트하거나 그 컴퓨터에서 변경하세요",
+ "arrivingLater": "{{name}}이(가) 이 컴퓨터로 옮겨졌고 아직 준비 중입니다. 곧 팀원 목록에 표시됩니다",
+ "busyTitle": "{{name}}이(가) 아직 답장 중입니다",
+ "busyDescription": "이번 답장이 끝난 뒤 “{{device}}”(으)로 옮기거나, 답장을 멈추고 바로 옮길 수 있습니다.",
+ "busyWait": "끝나면 옮기기",
+ "busyStop": "멈추고 옮기기",
+ "waitingForTurn": "{{name}}의 답장이 끝나면 “{{device}}”(으)로 옮깁니다…",
+ "mergeLabel": "중복된 Cindy 합치기",
+ "mergeHint": "Cindy가 {{count}}명 있습니다: {{devices}}",
+ "mergeTitle": "Cindy {{count}}명을 하나로 합칠까요?",
+ "mergeDescription": "합친 뒤에는 Cindy 한 명만 남습니다. 다른 Cindy의 채팅 기록, 기억, 스킬, 할 일, 루틴이 함께 옮겨집니다. 이름은 같지만 내용이 다른 기억과 스킬은 따로 저장되며 덮어쓰지 않습니다. 다른 Cindy는 꺼지고, 데이터는 클라우드와 원래 컴퓨터에 남습니다.",
+ "mergeKeep": "이름, 성격, 설정을 남길 Cindy",
+ "mergeAction": "합치기",
+ "merged": "Cindy {{count}}명을 하나로 합치고 메시지 {{messages}}개를 옮겼습니다",
+ "mergedRenamed": "Cindy {{count}}명을 하나로 합치고 메시지 {{messages}}개를 옮겼습니다. 따로 저장된 항목: {{renamed}}",
+ "mergeFailed": "합치지 못했습니다. 나중에 다시 시도하세요(이미 합친 부분은 중복되지 않습니다)",
+ "mergeBusy": "아직 답장 중인 Cindy가 있습니다. 답장이 끝난 뒤 합쳐 주세요",
+ "mergePaused": "일시 중지된 Cindy가 있습니다. 설정에서 다시 시작한 뒤 합쳐 주세요",
+ "mergeOffline": "“{{device}}”에 연결할 수 없습니다. 온라인이 되면 합치세요",
+ "mergeOutdated": "“{{device}}”의 Cindy가 이전 버전입니다. 먼저 업데이트하세요"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3e0ae9c3d4..549e3281a5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8868,7 +8868,8 @@
"failed": "没做完",
"paused": "已暂停",
"disabled": "已停用"
- }
+ },
+ "dirElsewhere": "在「{{device}}」上"
},
"remoteSettings": {
"empty": "暂无内容",
@@ -9729,9 +9730,7 @@
"homeLabel": "主力电脑",
"thisComputer": "这台电脑",
"homeOffline": "主力电脑「{{device}}」离线",
- "homeOfflineShort": "主力电脑离线",
"homeUnreachable": "主力电脑「{{device}}」没有开放远程控制",
- "homeReadOnly": "主力电脑:{{device}}",
"continueHere": "在这台电脑继续",
"takeOverHint": "在这台电脑继续后,{{name}} 改在这里运行,下面的对话一起带过来。",
"takingOver": "正在这台电脑上准备 {{name}}…",
@@ -9749,19 +9748,43 @@
"devicesFailed": "未能读取电脑列表",
"noTargets": "没有可接手的电脑。另一台电脑需要在线、登录同一账号,并开启「允许同账号设备控制本机」",
"resumeToMove": "先恢复 {{name}},再换到另一台电脑",
- "moveTo": "交给「{{device}}」",
- "transferTitle": "把 {{name}} 交给「{{device}}」?",
- "transferDescription": "从现在起 {{name}} 在「{{device}}」上运行。工作目录和连接留在这台电脑,这台电脑上的对话变为历史记录。",
- "transferAction": "交给「{{device}}」",
- "transferred": "{{name}} 已交给「{{device}}」",
- "transferConflict": "{{name}} 的主力电脑已经变了,这次没有交出",
- "transferOffline": "连不上服务器,{{name}} 仍在这台电脑运行",
"transferBusy": "{{name}} 还在回复,等这一轮结束再换电脑",
- "transferFailed": "未能把 {{name}} 交给「{{device}}」",
"targetUnavailable": "「{{device}}」现在不可用,它需要在线并开启远程控制",
"shadowTitle": "这个伙伴已在「{{device}}」上运行",
"shadowHint": "这里的对话只能查看。",
- "openOnHome": "打开「{{device}}」上的伙伴"
+ "openOnHome": "打开「{{device}}」上的伙伴",
+ "runsOn": "在「{{device}}」上运行",
+ "runsHere": "在这台电脑上运行",
+ "switchHint": "更换 {{name}} 运行的电脑",
+ "switchTo": "换到「{{device}}」",
+ "switchHere": "换到这台电脑",
+ "switchTitle": "把 {{name}} 换到「{{device}}」运行?",
+ "switchDescription": "从现在起 {{name}} 在「{{device}}」上运行,对话记录一起带过去。工作目录、连接和本机文件留在原来的电脑上。",
+ "switchAction": "换到「{{device}}」",
+ "switched": "{{name}} 已换到「{{device}}」运行",
+ "switchConflict": "{{name}} 的主力电脑已经变了,这次没有更换",
+ "switchOffline": "连接不上,{{name}} 的主力电脑没有变",
+ "switchFailed": "未能把 {{name}} 换到「{{device}}」",
+ "homeOutdated": "主力电脑「{{device}}」上的 Cindy 版本较旧,请先更新它,或在那台电脑上更换",
+ "arrivingLater": "{{name}} 已换到这台电脑,还在准备中,稍后会出现在伙伴列表里",
+ "busyTitle": "{{name}} 还在回复",
+ "busyDescription": "可以等这一轮结束后再换到「{{device}}」,也可以停止这一轮马上换。",
+ "busyWait": "等回复完再换",
+ "busyStop": "停止并换",
+ "waitingForTurn": "等 {{name}} 回复完,再换到「{{device}}」…",
+ "mergeLabel": "合并重复的 Cindy",
+ "mergeHint": "你有 {{count}} 个 Cindy:{{devices}}",
+ "mergeTitle": "把 {{count}} 个 Cindy 合成一个?",
+ "mergeDescription": "合并后只留下一个 Cindy。其他 Cindy 的对话记录、记忆、技能、待办和例行任务会并进来;同名但内容不同的记忆和技能另存一份,不会覆盖。其他 Cindy 会停用,它们的资料仍保留在云端和原来的电脑上。",
+ "mergeKeep": "保留哪一个的名字、性格和设置",
+ "mergeAction": "合成一个",
+ "merged": "{{count}} 个 Cindy 已合成一个,带过来 {{messages}} 条消息",
+ "mergedRenamed": "{{count}} 个 Cindy 已合成一个,带过来 {{messages}} 条消息;同名的内容另存为:{{renamed}}",
+ "mergeFailed": "没能合并,可以稍后再试一次(已合并的部分不会重复)",
+ "mergeBusy": "有一个 Cindy 还在回复,等它回复完再合并",
+ "mergePaused": "有一个 Cindy 已暂停,先在它的设置里恢复,再合并",
+ "mergeOffline": "「{{device}}」现在连不上,它上线后再合并",
+ "mergeOutdated": "「{{device}}」上的 Cindy 版本较旧,请先更新它再合并"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index ff1f14e91a..717001cf21 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8868,7 +8868,8 @@
"failed": "沒做完",
"paused": "已暫停",
"disabled": "已停用"
- }
+ },
+ "dirElsewhere": "在「{{device}}」上"
},
"remoteSettings": {
"empty": "暫無內容",
@@ -9729,9 +9730,7 @@
"homeLabel": "主力電腦",
"thisComputer": "這台電腦",
"homeOffline": "主力電腦「{{device}}」離線",
- "homeOfflineShort": "主力電腦離線",
"homeUnreachable": "主力電腦「{{device}}」沒有開放遠端控制",
- "homeReadOnly": "主力電腦:{{device}}",
"continueHere": "在這台電腦繼續",
"takeOverHint": "在這台電腦繼續後,{{name}} 改在這裡執行,下面的對話一起帶過來。",
"takingOver": "正在這台電腦上準備 {{name}}…",
@@ -9749,19 +9748,43 @@
"devicesFailed": "未能讀取電腦清單",
"noTargets": "沒有可接手的電腦。另一台電腦需要上線、登入同一帳號,並開啟「允許同帳號裝置控制本機」",
"resumeToMove": "先恢復 {{name}},再換到另一台電腦",
- "moveTo": "交給「{{device}}」",
- "transferTitle": "把 {{name}} 交給「{{device}}」?",
- "transferDescription": "從現在起 {{name}} 在「{{device}}」上執行。工作目錄和連線留在這台電腦,這台電腦上的對話變為歷史紀錄。",
- "transferAction": "交給「{{device}}」",
- "transferred": "{{name}} 已交給「{{device}}」",
- "transferConflict": "{{name}} 的主力電腦已經變了,這次沒有交出",
- "transferOffline": "連不上伺服器,{{name}} 仍在這台電腦執行",
"transferBusy": "{{name}} 還在回覆,等這一輪結束再換電腦",
- "transferFailed": "未能把 {{name}} 交給「{{device}}」",
"targetUnavailable": "「{{device}}」現在無法使用,它需要上線並開啟遠端控制",
"shadowTitle": "這個夥伴已在「{{device}}」上執行",
"shadowHint": "這裡的對話只能檢視。",
- "openOnHome": "開啟「{{device}}」上的夥伴"
+ "openOnHome": "開啟「{{device}}」上的夥伴",
+ "runsOn": "在「{{device}}」上執行",
+ "runsHere": "在這台電腦上執行",
+ "switchHint": "更換 {{name}} 執行的電腦",
+ "switchTo": "換到「{{device}}」",
+ "switchHere": "換到這台電腦",
+ "switchTitle": "把 {{name}} 換到「{{device}}」執行?",
+ "switchDescription": "從現在起 {{name}} 在「{{device}}」上執行,對話紀錄一起帶過去。工作目錄、連線和本機檔案留在原來的電腦上。",
+ "switchAction": "換到「{{device}}」",
+ "switched": "{{name}} 已換到「{{device}}」執行",
+ "switchConflict": "{{name}} 的主力電腦已經變了,這次沒有更換",
+ "switchOffline": "連線不上,{{name}} 的主力電腦沒有變",
+ "switchFailed": "未能把 {{name}} 換到「{{device}}」",
+ "homeOutdated": "主力電腦「{{device}}」上的 Cindy 版本較舊,請先更新它,或在那台電腦上更換",
+ "arrivingLater": "{{name}} 已換到這台電腦,還在準備中,稍後會出現在夥伴列表裡",
+ "busyTitle": "{{name}} 還在回覆",
+ "busyDescription": "可以等這一輪結束後再換到「{{device}}」,也可以停止這一輪馬上換。",
+ "busyWait": "等回覆完再換",
+ "busyStop": "停止並換",
+ "waitingForTurn": "等 {{name}} 回覆完,再換到「{{device}}」…",
+ "mergeLabel": "合併重複的 Cindy",
+ "mergeHint": "你有 {{count}} 個 Cindy:{{devices}}",
+ "mergeTitle": "把 {{count}} 個 Cindy 合成一個?",
+ "mergeDescription": "合併後只留下一個 Cindy。其他 Cindy 的對話紀錄、記憶、技能、待辦和例行任務會併進來;同名但內容不同的記憶和技能另存一份,不會覆蓋。其他 Cindy 會停用,它們的資料仍保留在雲端和原來的電腦上。",
+ "mergeKeep": "保留哪一個的名字、個性和設定",
+ "mergeAction": "合成一個",
+ "merged": "{{count}} 個 Cindy 已合成一個,帶過來 {{messages}} 則訊息",
+ "mergedRenamed": "{{count}} 個 Cindy 已合成一個,帶過來 {{messages}} 則訊息;同名的內容另存為:{{renamed}}",
+ "mergeFailed": "沒能合併,可以稍後再試一次(已合併的部分不會重複)",
+ "mergeBusy": "有一個 Cindy 還在回覆,等它回覆完再合併",
+ "mergePaused": "有一個 Cindy 已暫停,先在它的設定裡恢復,再合併",
+ "mergeOffline": "「{{device}}」現在連不上,它上線後再合併",
+ "mergeOutdated": "「{{device}}」上的 Cindy 版本較舊,請先更新它再合併"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2143ac9748..5395d82627 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4858,7 +4858,8 @@ interface ElectronAPI {
botId: string,
path: string,
) => Promise<{ ok: true } | { ok: false; errorCode: 'NOT_A_DIRECTORY' | 'TOO_MANY' }>;
- removeDirectory: (botId: string, path: string) => Promise<void>;
+ /** `deviceId`: the folder is on that computer (cloud companions); absent for this computer's. */
+ removeDirectory: (botId: string, path: string, deviceId?: string) => Promise<void>;
readTask: (
botId: string,
taskId: string,
@@ -5433,9 +5434,13 @@ interface ElectronAPI {
) => () => void;
getCompanionCloudState: () => Promise<import('../shared/companionCloud').CompanionCloudSnapshot>;
takeOverCompanion: (botId: string) => Promise<import('../shared/companionCloud').CompanionCloudActionResult>;
- transferCompanion: (botId: string, targetDeviceId: string) => Promise<import('../shared/companionCloud').CompanionCloudActionResult>;
+ switchCompanionHome: (botId: string, targetDeviceId: string, options?: import('../shared/companionCloud').CompanionSwitchOptions) => Promise<import('../shared/companionCloud').CompanionCloudActionResult>;
getCompanionTranscript: (botId: string, before?: string) => Promise<import('../shared/companionCloud').CompanionTranscriptPage>;
- listCompanionTransferTargets: () => Promise<import('../shared/companionCloud').CompanionTransferTarget[]>;
+ getCompanionHomeChoices: (botId: string) => Promise<import('../shared/companionCloud').CompanionHomeChoices>;
+ 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>;
+ resolveCompanionAvatar: (request: { avatar: string; deviceId?: string | null; fetch?: boolean }) => Promise<string | null>;
onCompanionCloudChanged: (
cb: (
payload: import('../shared/companionCloud').CompanionCloudSnapshot,
diff --git a/apps/desktop/src/shared/botWorkbench.ts b/apps/desktop/src/shared/botWorkbench.ts
index 044f8bf791..bc7b049620 100644
--- a/apps/desktop/src/shared/botWorkbench.ts
+++ b/apps/desktop/src/shared/botWorkbench.ts
@@ -20,6 +20,8 @@ export interface BotWorkbenchDirectory {
name: string;
addedAt: string;
exists: boolean;
+ /** On another computer (the companion moved here and the folder stayed there); never local. */
+ deviceId?: string;
}
/**
diff --git a/apps/desktop/src/shared/companionCloud.ts b/apps/desktop/src/shared/companionCloud.ts
index 49b1de3e9a..bb861e4086 100644
--- a/apps/desktop/src/shared/companionCloud.ts
+++ b/apps/desktop/src/shared/companionCloud.ts
@@ -38,12 +38,25 @@ export const EMPTY_COMPANION_CLOUD_SNAPSHOT: CompanionCloudSnapshot = Object.fre
demotedBotIds: [],
}) as CompanionCloudSnapshot;
-export type CompanionCloudFailureCode = 'HOME_CONFLICT' | 'OFFLINE' | 'NOT_ENABLED' | 'FAILED' | 'TARGET_UNAVAILABLE' | 'BUSY';
+export type CompanionCloudFailureCode =
+ | 'HOME_CONFLICT' | 'OFFLINE' | 'NOT_ENABLED' | 'FAILED' | 'TARGET_UNAVAILABLE' | 'BUSY'
+ /** The home runs a Cindy that cannot be asked from another computer; change it there. */
+ | 'HOME_OUTDATED'
+ /** The companion (one of the copies, for a merge) is paused: resume it first. */
+ | 'PAUSED';
export type CompanionCloudActionResult =
| { ok: true }
| { ok: false; code: CompanionCloudFailureCode; homeDeviceId?: string | null };
+/**
+ * What a move does while the companion is still working (a turn running or queued in any of
+ * its tasks): fail with `BUSY` (default), wait for it to finish, or stop it first.
+ */
+export interface CompanionSwitchOptions {
+ whenBusy?: 'wait' | 'stop';
+}
+
export interface CompanionTranscriptMessage {
/** Chat Server message id. */
id: string;
@@ -52,6 +65,8 @@ export interface CompanionTranscriptMessage {
text: string;
/** Unix ms. */
createdAt: number;
+ /** Files sent with the message, stored with the room (open through the companion's room). */
+ attachments?: Array<{ mediaId: string; name: string }>;
}
export interface CompanionTranscriptPage {
@@ -61,8 +76,38 @@ export interface CompanionTranscriptPage {
nextBefore?: string;
}
+/** A copy of Cindy in the cloud (made from the Cindy preset), one of several to merge. */
+export interface CompanionCindyCopy {
+ botId: string;
+ name: string;
+ homeDeviceId: string | null;
+}
+
+export type CompanionMergeResult =
+ | { ok: true; merged: number; messages: number; memories: number; skills: number; renamed: string[] }
+ | { ok: false; code: CompanionCloudFailureCode };
+
export interface CompanionTransferTarget {
deviceId: string;
name: string;
online: boolean;
+ /** The computer asking (only in `CompanionHomeChoices`). */
+ isSelf?: boolean;
+}
+
+/**
+ * Where a companion can move, as seen from this computer (cloud-companions.md §3.1):
+ * - `local`: this computer is the home and hands it over itself;
+ * - `remote`: the home is another reachable computer, asked to hand it over;
+ * - `takeOver`: the home cannot be reached; only this computer can continue it;
+ * - `unavailable`: the home cannot be changed from here (`reason`).
+ */
+export interface CompanionHomeChoices {
+ homeDeviceId: string | null;
+ /** Device-link name of the home; empty when unknown here. */
+ homeName?: string;
+ mode: 'local' | 'remote' | 'takeOver' | 'unavailable';
+ reason?: 'HOME_OUTDATED' | 'NOT_ENABLED' | 'NOT_FOUND';
+ /** Computers it can move to (never the current home). */
+ targets: CompanionTransferTarget[];
}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 9259f55390..c89cc3f98f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -23,6 +23,8 @@ import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';
import { CompanionHeader } from '@/session/CompanionHeader';
+import { CloudHomeUnreachableNotice, useSustained } from '@/session/CloudHomeUnreachableNotice';
+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
import { CHAT_HEADER_BLUR_FADE_INSIDE } from '@/session/ChatIdentityHeader';
import { useHiddenHistoryChase } from '@/session/hiddenHistoryChase';
import { collectCompanionPluginInvocations } from '@/session/pluginInvocations';
@@ -2357,6 +2359,15 @@ function SessionScreenContent() {
connectionIssue,
isDeviceUnresponsive,
);
+ // A cloud companion on its main computer (cloud-companions.md §3.1): like an IM chat, a briefly
+ // unreachable computer does not interrupt reading; only a message that cannot get through for a
+ // while offers to continue on another computer.
+ const cloudHome = useCloudCompanionHome(!!companionResource);
+ const cloudHomeActor = cloudHome.supported && companionResource
+ ? cloudHome.actors.find(actor => actor.kind === 'bot' && actor.externalId === companionResource.ref.id && actor.homeDeviceId === deviceId) ?? null
+ : null;
+ const cloudHomeUnreachable = useSustained(!!cloudHomeActor && outboxItems.length > 0 && outboxConnectionDispatchBlocked);
+ const quietConnection = !!cloudHomeActor;
const hasCurrentSession = currentSession !== null;
const currentAgentKind = useMemo(
() => currentSession ? agentKindForSession(currentSession) : null,
@@ -9704,7 +9715,14 @@ function SessionScreenContent() {
<View style={[styles.sessionChromeContent, { paddingTop: horizontalSystemHeader ? nativeHeaderHeight : insets.top + (paneLayout.persistent ? spacing.lg : 0) }, companionChat && Platform.OS !== 'ios' && { backgroundColor: colors.surface }]}>
{headerNode}
- {!isSharedTaskAccessRevoked && (showConnectionBanner || showCachedHistoryNotice) ? (
+ {cloudHomeActor && cloudHomeUnreachable ? (
+ <CloudHomeUnreachableNotice deviceName={deviceName} onSwitch={() => router.push({
+ pathname: '/companions/cloud/[actorId]',
+ params: { actorId: cloudHomeActor.id, botId: cloudHomeActor.externalId, deviceId, deviceName,
+ title: resolveRemoteText(companionResource!.display.title, i18nInstance.language) },
+ })} />
+ ) : null}
+ {!isSharedTaskAccessRevoked && !quietConnection && (showConnectionBanner || showCachedHistoryNotice) ? (
<ConnectionBanner
density="compact"
cachedOnly={showCachedHistoryNotice}
diff --git a/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx
index f3a848c8ce..d313e40ed2 100644
--- a/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx
@@ -11,6 +11,8 @@ import type { RemoteResource } from '@cindy/device-link';
const h = vi.hoisted(() => ({
todos: {} as any, profile: {} as any, dismiss: vi.fn(), chooseMode: vi.fn(), screenOptions: [] as Array<Record<string, unknown>>,
auth: { accountGeneration: 1, user: null },
+ cloud: { supported: false, actors: [] as Array<{ kind: string; externalId: string; homeDeviceId: string | null }> },
+ homeSheet: {} as any,
}));
vi.mock('react-native', () => ({
Keyboard: { dismiss: h.dismiss },
@@ -34,6 +36,8 @@ vi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: ({ ac
vi.mock('@/session/CompanionTodos', () => ({ CompanionTodos: (props: unknown) => { h.todos = props; return null; } }));
vi.mock('@/session/CompanionProfileSheet', () => ({ CompanionProfileSheet: (props: unknown) => { h.profile = props; return null; } }));
vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({ chooseMode: h.chooseMode }) }));
+vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => h.cloud }));
+vi.mock('@/session/CloudHomeSwitchSheet', () => ({ CloudHomeSwitchSheet: (props: unknown) => { h.homeSheet = props; return null; } }));
import { CompanionHeader } from '@/session/CompanionHeader';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root; let host: HTMLDivElement;
@@ -41,6 +45,7 @@ const resource = { ref: { kind: 'bot', collectionId: 'bots', id: 'bot' }, displa
const button = (id: string) => host.querySelector<HTMLButtonElement>(`[data-testid="${id}"]`)!;
beforeEach(() => {
vi.clearAllMocks(); h.auth.accountGeneration = 1; h.profile = {}; h.todos = {}; h.screenOptions = [];
+ h.cloud = { supported: false, actors: [] }; h.homeSheet = {};
host = document.createElement('div'); root = createRoot(host);
});
afterEach(() => act(() => root.unmount()));
@@ -190,3 +195,25 @@ it('only opens Todo for an advertised host capability after entry validation and
await act(async () => root.render(<CompanionHeader {...props} resource={withTodos} />));
expect(h.todos.visible).toBe(false);
});
+
+it('names the main computer of a cloud companion and lets the profile change it', async () => {
+ h.cloud = { supported: true, actors: [{ kind: 'bot', externalId: 'bot', homeDeviceId: 'pc' }] };
+ await act(async () => root.render(<CompanionHeader resource={resource} deviceId="pc" deviceName="Office iMac" online onBack={() => {}} onSearch={() => {}} />));
+ expect(host.textContent).toContain('devices.cloudCompanion.runsOn');
+ await act(async () => button('companion.settings').click());
+ await act(async () => h.profile.onOpenHome());
+ // Opens once the profile sheet has closed.
+ expect(h.homeSheet.visible).toBe(false);
+ await act(async () => h.profile.onClosed());
+ expect(h.homeSheet.visible).toBe(true);
+ expect(h.homeSheet).toMatchObject({ botId: 'bot', homeDeviceId: 'pc', homeName: 'Office iMac' });
+ await act(async () => h.homeSheet.onMoved({ deviceId: 'mac', name: 'Mac', online: true }));
+ expect(h.chooseMode).toHaveBeenCalledWith('teammates');
+});
+
+it('offers no computer change for a companion without a known main computer', async () => {
+ await act(async () => root.render(<CompanionHeader resource={resource} deviceId="pc" deviceName="PC" online onBack={() => {}} onSearch={() => {}} />));
+ await act(async () => button('companion.settings').click());
+ expect(h.profile.onOpenHome).toBeUndefined();
+});
+
diff --git a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
index a7cd5fed51..4a492a6144 100644
--- a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
+++ b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx
@@ -17,7 +17,7 @@ const h = vi.hoisted(() => ({
groupTargetsSeen: [] as unknown[],
create: {} as any, chrome: {} as any, titleArgs: [] as number[], nativeHeader: true, headerHeight: 106, barEdge: 'none',
cloud: { supported: false, actors: [] as Array<{ id: string; kind: string; externalId: string; name: string; avatar: null; homeDeviceId: string | null }>,
- refresh: vi.fn(), setHome: vi.fn() },
+ deviceNames: new Map<string, string>(), refresh: vi.fn(), setHome: vi.fn() },
}));
vi.mock('react-native', async () => {
const { createElement: el } = await import('react');
@@ -93,7 +93,7 @@ beforeEach(() => {
h.modeMenu = {}; h.nativeMenus = true; h.nativeHeader = true; h.headerHeight = 106; h.barEdge = 'none'; h.chrome = {};
h.groups.loading = false; h.groups.refreshing = false; h.groups.error = null;
h.roster.loading = false; h.roster.error = null; h.roster.isOnline.mockReturnValue(true);
- h.cloud.supported = false; h.cloud.actors = [];
+ h.cloud.supported = false; h.cloud.actors = []; h.cloud.deviceNames = new Map();
});
afterEach(() => { act(() => root?.unmount()); root = undefined; });
describe('teammate home entry', () => {
@@ -219,16 +219,28 @@ describe('server groups in the actual teammate home', () => {
describe('cloud companions (main computer offline)', () => {
const actorId = '00000000-0000-4000-8000-000000000001';
const copy = (deviceId: string): HostedRemoteCollectionItem => ({ ...teammate, key: `${deviceId}:writer`, host: { deviceId, deviceName: deviceId.toUpperCase() } });
- it('opens the cloud view for an offline main computer and hides demoted copies', async () => {
+ it('keeps a listed companion quiet and in its normal chat while its main computer looks offline', async () => {
h.cloud.supported = true;
h.cloud.actors = [{ id: actorId, kind: 'bot', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'mac' }];
h.roster.items = [teammate, copy('pc')];
h.roster.isOnline.mockReturnValue(false);
await render();
expect(h.list.items.map((row: HostedRemoteCollectionItem) => row.key)).toEqual(['mac:bot']);
- expect(h.list.cloudOpenable(teammate)).toBe(true);
- expect(h.list.cloudOpenable(copy('pc'))).toBe(false);
+ expect(h.list.quietPresence(teammate)).toBe(true);
await act(async () => h.list.onSelect(teammate));
+ expect(h.nav.openTeammate).toHaveBeenCalledExactlyOnceWith(teammate);
+ expect(h.push).not.toHaveBeenCalledWith(expect.objectContaining({ pathname: '/companions/cloud/[actorId]' }));
+ });
+ it('opens the cloud conversation only for a companion this phone knows from the cloud alone', async () => {
+ h.cloud.supported = true;
+ h.cloud.deviceNames = new Map([['mac', 'Mac']]);
+ h.cloud.actors = [{ id: actorId, kind: 'bot', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'mac' }];
+ h.roster.items = [copy('pc')];
+ await render();
+ const [row] = h.list.items as HostedRemoteCollectionItem[];
+ expect(row.item.revision).toBe('cloud');
+ expect(h.list.quietPresence(row)).toBe(true);
+ await act(async () => h.list.onSelect(row));
expect(h.push).toHaveBeenLastCalledWith({ pathname: '/companions/cloud/[actorId]',
params: { actorId, botId: 'writer', deviceId: 'mac', deviceName: 'Mac', title: 'Writer' } });
expect(h.nav.openTeammate).not.toHaveBeenCalled();
@@ -258,7 +270,7 @@ describe('cloud companions (main computer offline)', () => {
h.roster.isOnline.mockReturnValue(false);
await render();
expect(h.list.items).toHaveLength(2);
- expect(h.list.cloudOpenable(teammate)).toBe(false);
+ expect(h.list.quietPresence(teammate)).toBe(false);
h.cloud.supported = true; h.roster.isOnline.mockReturnValue(true);
await render();
await act(async () => h.list.onSelect(teammate));
diff --git a/apps/mobile/src/__tests__/TeammateList.test.tsx b/apps/mobile/src/__tests__/TeammateList.test.tsx
index c9df24e928..3ed158a2ce 100644
--- a/apps/mobile/src/__tests__/TeammateList.test.tsx
+++ b/apps/mobile/src/__tests__/TeammateList.test.tsx
@@ -197,3 +197,10 @@ it.each([false, null, true])('opens cached teammates while connection evidence i
expect(select).toHaveBeenCalledExactlyOnceWith(item);
if (connected === true) expect(button.textContent).not.toContain('devices.resources.hostOffline');
});
+
+it('keeps a cloud companion quiet while its main computer looks offline: no offline text, dot or dimming', async () => {
+ await act(async () => root.render(el(TeammateList, { items: [item], error: null, isOnline: () => false, quietPresence: () => true,
+ loading: false, refreshing: false, onRefresh: vi.fn(), onSelect: vi.fn(), embedded: true })));
+ expect(node.textContent).not.toContain('devices.resources.hostOffline');
+ expect(node.querySelector('[data-testid="teammate.connection"] [data-testid="status-dot"]')).toBeNull();
+});
diff --git a/apps/mobile/src/__tests__/cloudCompanion.test.ts b/apps/mobile/src/__tests__/cloudCompanion.test.ts
index 2e4e33fd4d..5c4cf1d088 100644
--- a/apps/mobile/src/__tests__/cloudCompanion.test.ts
+++ b/apps/mobile/src/__tests__/cloudCompanion.test.ts
@@ -3,7 +3,7 @@ import { ApiError } from '@/api/client';
import { createChatServerClient, type ChatActor, type ChatMessage } from '@/chat/chatServerClient';
import {
CLOUD_SWITCH_TIMEOUT_MS, cloudActorForRow, cloudCompanionMessages, cloudSwitchAfterSetHome, cloudSwitchCandidates,
- cloudSwitchTick, cloudCompanionRows, type CloudSwitchState,
+ cloudSwitchTick, cloudCompanionRows, cloudHomeTargets, type CloudSwitchState,
} from '@/chat/cloudCompanion';
import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';
@@ -59,6 +59,17 @@ describe('cloud companion rows', () => {
], id(1));
expect(view.map(item => [item.text, item.fromCompanion])).toEqual([['hello', false], ['reply', true]]);
});
+ it('orders by message time, so older history uploaded later still appears first', () => {
+ const at = (n: number, time: string): ChatMessage => ({ id: id(n), seq: String(n), authorId: id(9), author: { kind: 'human', name: '' },
+ createdAt: time, deleted: false, threadRootId: null, content: [{ type: 'text', text: `m${n}` }] });
+ const view = cloudCompanionMessages([at(20, '2026-10-14T00:00:00Z'), at(30, '2026-09-01T00:00:00Z')], id(1));
+ expect(view.map(item => item.text)).toEqual(['m30', 'm20']);
+ });
+
+ it('offers the computers the main computer names, never itself or this phone', () => {
+ const targets = [{ deviceId: 'home', online: true }, { deviceId: 'phone', online: true }, { deviceId: 'mac', online: true }, { deviceId: 'off', online: false }];
+ expect(cloudHomeTargets(targets, 'home', 'phone').map(target => target.deviceId)).toEqual(['mac']);
+ });
});
describe('switching the main computer', () => {
diff --git a/apps/mobile/src/__tests__/cloudHomeUnreachable.test.tsx b/apps/mobile/src/__tests__/cloudHomeUnreachable.test.tsx
new file mode 100644
index 0000000000..7c04cf78ef
--- /dev/null
+++ b/apps/mobile/src/__tests__/cloudHomeUnreachable.test.tsx
@@ -0,0 +1,35 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+vi.mock('react-native', () => ({ StyleSheet: { create: (v: unknown) => v }, View: () => null }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/components/AppText', () => ({ Text: () => null }));
+vi.mock('@/theme', () => ({ lineHeight: {}, radius: {}, spacing: {}, typeScale: {}, useThemedStyles: () => ({}) }));
+vi.mock('@/session/CompanionCardButton', () => ({ CompanionCardButton: () => null }));
+import { CLOUD_HOME_UNREACHABLE_AFTER_MS, useSustained } from '../session/CloudHomeUnreachableNotice';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: ReturnType<typeof createRoot>;
+const seen: boolean[] = [];
+function Harness({ waiting }: { waiting: boolean }) { seen.push(useSustained(waiting)); return null; }
+const render = (waiting: boolean) => act(() => root.render(<Harness waiting={waiting} />));
+beforeEach(() => { vi.useFakeTimers(); seen.length = 0; root = createRoot(document.createElement('div')); });
+afterEach(() => { act(() => root.unmount()); vi.useRealTimers(); });
+
+it('offers the switch only after a message has waited for the main computer the whole time', () => {
+ render(true);
+ act(() => { vi.advanceTimersByTime(CLOUD_HOME_UNREACHABLE_AFTER_MS - 1); });
+ expect(seen.at(-1)).toBe(false);
+ act(() => { vi.advanceTimersByTime(1); });
+ expect(seen.at(-1)).toBe(true);
+ // Delivered: the prompt goes away at once, and a new wait starts the clock again.
+ render(false);
+ expect(seen.at(-1)).toBe(false);
+ render(true);
+ expect(seen.at(-1)).toBe(false);
+ act(() => { vi.advanceTimersByTime(CLOUD_HOME_UNREACHABLE_AFTER_MS / 2); });
+ render(false); render(true);
+ act(() => { vi.advanceTimersByTime(CLOUD_HOME_UNREACHABLE_AFTER_MS / 2); });
+ expect(seen.at(-1)).toBe(false);
+});
diff --git a/apps/mobile/src/chat/cloudCompanion.ts b/apps/mobile/src/chat/cloudCompanion.ts
index 2010dc7654..144c1b33ec 100644
--- a/apps/mobile/src/chat/cloudCompanion.ts
+++ b/apps/mobile/src/chat/cloudCompanion.ts
@@ -21,6 +21,8 @@ export function cloudActorForRow(actors: readonly ChatActor[], row: HostedRemote
}
const TEAMMATES = 'teammates';
+/** Revision of a row built from the cloud actor alone (its computer never listed it here). */
+export const CLOUD_ROW_REVISION = 'cloud';
function cloudAvatar(actor: ChatActor): RemoteResourceAvatar {
const fallbackText = Array.from(actor.name.trim())[0] ?? 'C';
@@ -49,7 +51,7 @@ export function cloudCompanionRows(items: readonly HostedRemoteCollectionItem[],
if (listed.some(row => row.item.ref.kind === 'bot' && row.item.ref.id === actor.externalId && row.host.deviceId === deviceId)) return [];
const ref = { collectionId: TEAMMATES, kind: 'bot', id: actor.externalId };
return [{ key: JSON.stringify([deviceId, ref.collectionId, ref.kind, ref.id]), host: { deviceId, deviceName: deviceNames.get(deviceId) ?? deviceId },
- item: { ref, display: { title: actor.name, avatar: cloudAvatar(actor) }, links: [], revision: 'cloud' } }];
+ item: { ref, display: { title: actor.name, avatar: cloudAvatar(actor) }, links: [], revision: CLOUD_ROW_REVISION } }];
});
return [...listed, ...added];
}
@@ -65,13 +67,21 @@ export function cloudSwitchCandidates(
.map(row => ({ deviceId: row.device.deviceId, name: row.device.name }));
}
+/** Computers the home offers for the companion (its own view), never the home or this phone. */
+export function cloudHomeTargets<T extends { deviceId: string; online: boolean }>(targets: readonly T[], home: string, self: string | null): T[] {
+ return targets.filter(target => target.online && target.deviceId !== home && target.deviceId !== self);
+}
+
export interface CloudMessage { id: string; fromCompanion: boolean; text: string; createdAt: number }
/** Oldest first, deduplicated; the companion's actor wrote its replies, everyone else is the owner. */
export function cloudCompanionMessages(messages: readonly ChatMessage[], actorId: string): CloudMessage[] {
const unique = [...new Map(messages.map(message => [message.id, message])).values()]
.filter(message => !message.deleted && !message.threadRootId && message.origin !== 'system');
+ // Message time first: older history uploaded later (backfill, merges) arrives after newer messages.
unique.sort((a, b) => {
+ const time = Date.parse(a.createdAt) - Date.parse(b.createdAt);
+ if (Number.isFinite(time) && time !== 0) return time;
const left = BigInt(chatCursor(a.seq)); const right = BigInt(chatCursor(b.seq));
return left < right ? -1 : left > right ? 1 : 0;
});
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index 75895f3f76..e0d6579e15 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -754,7 +754,8 @@
"portraitNumber": "Portrait {{number}}",
"uploadAvatar": "Upload Avatar",
"avatarFailed": "Could not open this image. Try another.",
- "nameTaken": "That name is already in use. Choose another."
+ "nameTaken": "That name is already in use. Choose another.",
+ "home": "Main Computer"
},
"companionImport": {
"title": "Import a teammate",
@@ -909,6 +910,22 @@
"timeout": "“{{device}}” isn’t ready yet. Make sure Cindy is open and online on that computer, then try again.",
"conflict": "{{name}} has already moved to “{{device}}”.",
"switchFailed": "Can’t change the main computer right now. Try again later.",
- "unknownDevice": "another computer"
+ "unknownDevice": "another computer",
+ "runsOn": "Runs on “{{device}}”",
+ "homeTitle": "Main Computer",
+ "moveTo": "Move to “{{device}}”",
+ "moveTitle": "Run {{name}} on “{{device}}”?",
+ "moveDescription": "From now on {{name}} runs on “{{device}}”, and the chat history comes along. Working directories, connections and local files stay on the computer they are on.",
+ "moveAction": "Move to “{{device}}”",
+ "moving": "Moving {{name}} to “{{device}}”…",
+ "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",
+ "busyStop": "Stop and Move",
+ "transferBusy": "{{name}} is still working on a reply. Move it after the reply finishes",
+ "switchConflict": "{{name}}’s main computer has already changed, so it wasn’t moved",
+ "homeOutdated": "The main computer “{{device}}” runs an older Cindy. Update it, or change the main computer there",
+ "homeUnreachable": "Can’t reach “{{device}}”. It must be online with “Allow same-account devices to control this machine” turned on",
+ "sendUnreachable": "Your message hasn’t reached the main computer “{{device}}”; it may be offline. You can continue on another computer."
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index c90c1293a8..f41f43f67c 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -754,7 +754,8 @@
"portraitNumber": "アバター {{number}}",
"uploadAvatar": "アバターをアップロード",
"avatarFailed": "この画像を開けません。別の画像を選んでください。",
- "nameTaken": "この名前は使用されています。別の名前を選んでください。"
+ "nameTaken": "この名前は使用されています。別の名前を選んでください。",
+ "home": "メインのパソコン"
},
"companionImport": {
"title": "仲間をインポート",
@@ -909,6 +910,22 @@
"timeout": "「{{device}}」の準備がまだ終わっていません。そのパソコンで Cindy が開いていてオンラインか確認して、もう一度お試しください。",
"conflict": "{{name}} はすでに「{{device}}」に移っています。",
"switchFailed": "メインのパソコンを変更できません。しばらくしてからもう一度お試しください。",
- "unknownDevice": "別のパソコン"
+ "unknownDevice": "別のパソコン",
+ "runsOn": "「{{device}}」で実行中",
+ "homeTitle": "メインのパソコン",
+ "moveTo": "「{{device}}」に移す",
+ "moveTitle": "{{name}} を「{{device}}」で実行しますか?",
+ "moveDescription": "今後 {{name}} は「{{device}}」で実行され、チャット履歴も一緒に移ります。作業ディレクトリ、接続、ローカルのファイルは元のパソコンに残ります。",
+ "moveAction": "「{{device}}」に移す",
+ "moving": "{{name}} を「{{device}}」に移しています…",
+ "busyTitle": "{{name}} はまだ返信中です",
+ "busyDescription": "この返信が終わってから「{{device}}」に移すか、返信を止めてすぐに移せます。",
+ "busyWait": "終わってから移す",
+ "busyStop": "止めて移す",
+ "transferBusy": "{{name}} はまだ返信中です。返信が終わってから移してください",
+ "switchConflict": "{{name}} のメインのパソコンはすでに変更されているため、移しませんでした",
+ "homeOutdated": "メインのパソコン「{{device}}」の Cindy が古いバージョンです。更新するか、そのパソコンで変更してください",
+ "homeUnreachable": "「{{device}}」に接続できません。オンラインで「同じアカウントのデバイスからの操作を許可」をオンにする必要があります",
+ "sendUnreachable": "メッセージがメインのパソコン「{{device}}」に届いていません。オフラインの可能性があります。別のパソコンで続けられます。"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index dedc5ddc0d..89be7cd50b 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -754,7 +754,8 @@
"portraitNumber": "아바타 {{number}}",
"uploadAvatar": "아바타 업로드",
"avatarFailed": "이미지를 열 수 없습니다. 다른 이미지를 선택하세요.",
- "nameTaken": "이미 사용 중인 이름입니다. 다른 이름을 선택하세요."
+ "nameTaken": "이미 사용 중인 이름입니다. 다른 이름을 선택하세요.",
+ "home": "주 컴퓨터"
},
"companionImport": {
"title": "동료 가져오기",
@@ -909,6 +910,22 @@
"timeout": "'{{device}}'이(가) 아직 준비되지 않았습니다. 그 컴퓨터에서 Cindy가 열려 있고 온라인인지 확인한 뒤 다시 시도하세요.",
"conflict": "{{name}}은(는) 이미 '{{device}}'(으)로 옮겨졌습니다.",
"switchFailed": "지금은 주 컴퓨터를 바꿀 수 없습니다. 잠시 후 다시 시도하세요.",
- "unknownDevice": "다른 컴퓨터"
+ "unknownDevice": "다른 컴퓨터",
+ "runsOn": "“{{device}}”에서 실행 중",
+ "homeTitle": "주 컴퓨터",
+ "moveTo": "“{{device}}”(으)로 옮기기",
+ "moveTitle": "{{name}}을(를) “{{device}}”에서 실행할까요?",
+ "moveDescription": "이제부터 {{name}}은(는) “{{device}}”에서 실행되며 채팅 기록도 함께 옮겨집니다. 작업 디렉터리, 연결, 로컬 파일은 원래 컴퓨터에 남습니다.",
+ "moveAction": "“{{device}}”(으)로 옮기기",
+ "moving": "{{name}}을(를) “{{device}}”(으)로 옮기는 중…",
+ "busyTitle": "{{name}}이(가) 아직 답장 중입니다",
+ "busyDescription": "이번 답장이 끝난 뒤 “{{device}}”(으)로 옮기거나, 답장을 멈추고 바로 옮길 수 있습니다.",
+ "busyWait": "끝나면 옮기기",
+ "busyStop": "멈추고 옮기기",
+ "transferBusy": "{{name}}이(가) 아직 답장 중입니다. 답장이 끝난 뒤 옮기세요",
+ "switchConflict": "{{name}}의 주 컴퓨터가 이미 바뀌어 이번에는 옮기지 않았습니다",
+ "homeOutdated": "주 컴퓨터 “{{device}}”의 Cindy가 이전 버전입니다. 업데이트하거나 그 컴퓨터에서 변경하세요",
+ "homeUnreachable": "“{{device}}”에 연결할 수 없습니다. 온라인 상태이고 “같은 계정의 기기에서 이 컴퓨터 제어 허용”이 켜져 있어야 합니다",
+ "sendUnreachable": "메시지가 주 컴퓨터 “{{device}}”에 전달되지 않았습니다. 오프라인일 수 있습니다. 다른 컴퓨터에서 계속할 수 있습니다."
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 81699d9eac..d0368cbde9 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -754,7 +754,8 @@
"portraitNumber": "头像 {{number}}",
"uploadAvatar": "上传头像",
"avatarFailed": "无法打开此图片,请换一张。",
- "nameTaken": "已有同名伙伴,请换一个名字。"
+ "nameTaken": "已有同名伙伴,请换一个名字。",
+ "home": "主力电脑"
},
"companionImport": {
"title": "导入伙伴",
@@ -909,6 +910,22 @@
"timeout": "「{{device}}」还没准备好。请确认那台电脑上的 Cindy 已打开并联网,再试一次。",
"conflict": "{{name}} 已经换到「{{device}}」继续了。",
"switchFailed": "暂时无法更换主力电脑,请稍后再试。",
- "unknownDevice": "另一台电脑"
+ "unknownDevice": "另一台电脑",
+ "runsOn": "在「{{device}}」上运行",
+ "homeTitle": "主力电脑",
+ "moveTo": "换到「{{device}}」",
+ "moveTitle": "把 {{name}} 换到「{{device}}」运行?",
+ "moveDescription": "从现在起 {{name}} 在「{{device}}」上运行,对话记录一起带过去。工作目录、连接和本机文件留在原来的电脑上。",
+ "moveAction": "换到「{{device}}」",
+ "moving": "正在把 {{name}} 换到「{{device}}」…",
+ "busyTitle": "{{name}} 还在回复",
+ "busyDescription": "可以等这一轮结束后再换到「{{device}}」,也可以停止这一轮马上换。",
+ "busyWait": "等回复完再换",
+ "busyStop": "停止并换",
+ "transferBusy": "{{name}} 还在回复,等这一轮结束再换电脑",
+ "switchConflict": "{{name}} 的主力电脑已经变了,这次没有更换",
+ "homeOutdated": "主力电脑「{{device}}」上的 Cindy 版本较旧,请先更新它,或在那台电脑上更换",
+ "homeUnreachable": "现在连不上「{{device}}」,它需要在线并开启「允许同账号设备控制本机」",
+ "sendUnreachable": "消息还没送到主力电脑「{{device}}」,它可能已离线。可以换一台电脑继续。"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index 1dd5b61020..888eea87bb 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -754,7 +754,8 @@
"portraitNumber": "頭像 {{number}}",
"uploadAvatar": "上傳頭像",
"avatarFailed": "無法開啟此圖片,請換一張。",
- "nameTaken": "已有同名夥伴,請換一個名字。"
+ "nameTaken": "已有同名夥伴,請換一個名字。",
+ "home": "主力電腦"
},
"companionImport": {
"title": "匯入夥伴",
@@ -909,6 +910,22 @@
"timeout": "「{{device}}」還沒準備好。請確認那台電腦上的 Cindy 已開啟並連上網路,再試一次。",
"conflict": "{{name}} 已經換到「{{device}}」繼續了。",
"switchFailed": "暫時無法更換主力電腦,請稍後再試。",
- "unknownDevice": "另一台電腦"
+ "unknownDevice": "另一台電腦",
+ "runsOn": "在「{{device}}」上執行",
+ "homeTitle": "主力電腦",
+ "moveTo": "換到「{{device}}」",
+ "moveTitle": "把 {{name}} 換到「{{device}}」執行?",
+ "moveDescription": "從現在起 {{name}} 在「{{device}}」上執行,對話紀錄一起帶過去。工作目錄、連線和本機檔案留在原來的電腦上。",
+ "moveAction": "換到「{{device}}」",
+ "moving": "正在把 {{name}} 換到「{{device}}」…",
+ "busyTitle": "{{name}} 還在回覆",
+ "busyDescription": "可以等這一輪結束後再換到「{{device}}」,也可以停止這一輪馬上換。",
+ "busyWait": "等回覆完再換",
+ "busyStop": "停止並換",
+ "transferBusy": "{{name}} 還在回覆,等這一輪結束再換電腦",
+ "switchConflict": "{{name}} 的主力電腦已經變了,這次沒有更換",
+ "homeOutdated": "主力電腦「{{device}}」上的 Cindy 版本較舊,請先更新它,或在那台電腦上更換",
+ "homeUnreachable": "現在連不上「{{device}}」,它需要在線並開啟「允許同帳號裝置控制本機」",
+ "sendUnreachable": "訊息還沒送到主力電腦「{{device}}」,它可能已離線。可以換一台電腦繼續。"
}
}
diff --git a/apps/mobile/src/session/CloudHomeSwitchSheet.tsx b/apps/mobile/src/session/CloudHomeSwitchSheet.tsx
new file mode 100644
index 0000000000..7c76db09a7
--- /dev/null
+++ b/apps/mobile/src/session/CloudHomeSwitchSheet.tsx
@@ -0,0 +1,121 @@
+/**
+ * 手机上更换伙伴的主力电脑(docs/product-rules/cloud-companions.md §3.1):主力电脑在线时,经 device-link
+ * 读那台电脑视角下可接手的电脑,选中后请它交出(与桌面同一条路径,交出前同步对话与资料)。伙伴还在回复时
+ * 可以等这一轮结束或停止后再换。主力电脑版本较旧或连不上时只说明原因;离线时由离线页面「换一台电脑继续」。
+ */
+import { useEffect, useState } from 'react';
+import { ActivityIndicator, Alert, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import {
+ COMPANION_CLOUD_CAPS_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ COMPANION_CLOUD_REMOTE_HAND_OVER_VERSION,
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+ companionCloudCapsVersion,
+ parseCompanionCloudRemoteActionResult,
+ parseCompanionCloudRemoteTargets,
+ type CompanionCloudRemoteTarget,
+} from '@cindy/device-link';
+import { Text } from '@/components/AppText';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { lineHeight, spacing, typeScale } from '@/theme/tokens';
+import { CompanionSettingsRow } from './CompanionSettingsRow';
+import { CompanionSheet } from './CompanionSheet';
+import { cloudHomeTargets } from '@/chat/cloudCompanion';
+
+type Phase =
+ | { kind: 'loading' }
+ | { kind: 'ready'; targets: CompanionCloudRemoteTarget[] }
+ | { kind: 'note'; key: 'homeOutdated' | 'homeUnreachable' | 'devicesFailed' | 'noTargets' }
+ | { kind: 'moving'; target: CompanionCloudRemoteTarget };
+
+export function CloudHomeSwitchSheet({ visible, onClose, botId, name, homeDeviceId, homeName, selfDeviceId, onMoved }: {
+ visible: boolean;
+ onClose: () => void;
+ botId: string;
+ name: string;
+ homeDeviceId: string;
+ homeName: string;
+ /** This phone (never a target). */
+ selfDeviceId?: string | null;
+ onMoved: (target: CompanionCloudRemoteTarget) => void;
+}) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const { invoke } = useDeviceLink();
+ const [phase, setPhase] = useState<Phase>({ kind: 'loading' });
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!visible) return;
+ let live = true;
+ setPhase({ kind: 'loading' });
+ setError(null);
+ void (async () => {
+ const version = companionCloudCapsVersion(await invoke(homeDeviceId, COMPANION_CLOUD_CAPS_CHANNEL, []).catch(() => null));
+ if (!live) return;
+ if (version === 0) { setPhase({ kind: 'note', key: 'homeUnreachable' }); return; }
+ if (version < COMPANION_CLOUD_REMOTE_HAND_OVER_VERSION) { setPhase({ kind: 'note', key: 'homeOutdated' }); return; }
+ try {
+ const targets = cloudHomeTargets(parseCompanionCloudRemoteTargets(await invoke(homeDeviceId, COMPANION_CLOUD_TARGETS_CHANNEL, [])),
+ homeDeviceId, selfDeviceId ?? null);
+ if (live) setPhase(targets.length ? { kind: 'ready', targets } : { kind: 'note', key: 'noTargets' });
+ } catch {
+ if (live) setPhase({ kind: 'note', key: 'devicesFailed' });
+ }
+ })();
+ return () => { live = false; };
+ }, [homeDeviceId, invoke, selfDeviceId, visible]);
+
+ const move = async (target: CompanionCloudRemoteTarget, whenBusy?: 'wait' | 'stop') => {
+ const offered = phase.kind === 'ready' ? phase.targets : [target];
+ setPhase({ kind: 'moving', target });
+ setError(null);
+ let result;
+ try {
+ result = parseCompanionCloudRemoteActionResult(await invoke(homeDeviceId, COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ whenBusy ? [botId, target.deviceId, { whenBusy }] : [botId, target.deviceId]));
+ } catch {
+ result = { ok: false as const, code: 'OFFLINE' };
+ }
+ if (result.ok) { onMoved(target); return; }
+ setPhase({ kind: 'ready', targets: offered });
+ if (result.code === 'BUSY' && !whenBusy) {
+ Alert.alert(t('devices.cloudCompanion.busyTitle', { name }), t('devices.cloudCompanion.busyDescription', { name, device: target.name }), [
+ { text: t('devices.common.cancel'), style: 'cancel' },
+ { text: t('devices.cloudCompanion.busyStop'), style: 'destructive', onPress: () => void move(target, 'stop') },
+ { text: t('devices.cloudCompanion.busyWait'), onPress: () => void move(target, 'wait') },
+ ]);
+ return;
+ }
+ setError(t(result.code === 'BUSY' ? 'devices.cloudCompanion.transferBusy'
+ : result.code === 'HOME_CONFLICT' ? 'devices.cloudCompanion.switchConflict' : 'devices.cloudCompanion.switchFailed', { name, device: target.name }));
+ };
+
+ const confirm = (target: CompanionCloudRemoteTarget) => {
+ Alert.alert(t('devices.cloudCompanion.moveTitle', { name, device: target.name }), t('devices.cloudCompanion.moveDescription', { name, device: target.name }), [
+ { text: t('devices.common.cancel'), style: 'cancel' },
+ { text: t('devices.cloudCompanion.moveAction', { device: target.name }), onPress: () => void move(target) },
+ ]);
+ };
+
+ return <CompanionSheet visible={visible} onClose={onClose} title={t('devices.cloudCompanion.homeTitle')} preventDismiss={phase.kind === 'moving'} testID="cloudHome.sheet">
+ <View style={styles.content}>
+ <Text style={styles.note}>{t('devices.cloudCompanion.runsOn', { device: homeName })}</Text>
+ {phase.kind === 'loading' || phase.kind === 'moving' ? <ActivityIndicator style={styles.spinner} /> : null}
+ {phase.kind === 'moving' ? <Text style={styles.note}>{t('devices.cloudCompanion.moving', { name, device: phase.target.name })}</Text> : null}
+ {phase.kind === 'note' ? <Text style={styles.note}>{t(`devices.cloudCompanion.${phase.key}`, { device: homeName })}</Text> : null}
+ {phase.kind === 'ready' ? phase.targets.map(target => <CompanionSettingsRow key={target.deviceId} icon={null} trailing="chevron"
+ label={t('devices.cloudCompanion.moveTo', { device: target.name || t('devices.cloudCompanion.unknownDevice') })}
+ onPress={() => confirm(target)} testID={`cloudHome.target.${target.deviceId}`} />) : null}
+ {error ? <Text style={styles.note} accessibilityRole="alert">{error}</Text> : null}
+ </View>
+ </CompanionSheet>;
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ content: { gap: spacing.sm, paddingBottom: spacing.lg },
+ note: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ spinner: { marginVertical: spacing.md },
+});
diff --git a/apps/mobile/src/session/CloudHomeUnreachableNotice.tsx b/apps/mobile/src/session/CloudHomeUnreachableNotice.tsx
new file mode 100644
index 0000000000..073675535c
--- /dev/null
+++ b/apps/mobile/src/session/CloudHomeUnreachableNotice.tsx
@@ -0,0 +1,42 @@
+/**
+ * 云端伙伴的消息发不出去时才出现的提示(docs/product-rules/cloud-companions.md §3.1):像 IM 一样,
+ * 主力电脑一时连不上不打扰浏览;只有发出的消息持续送不到主力电脑,才提示「主力电脑「X」连不上」并提供
+ * 换一台电脑继续(打开云端对话页里的换电脑流程)。
+ */
+import { useEffect, useState } from 'react';
+import { StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { Text } from '@/components/AppText';
+import { lineHeight, radius, spacing, typeScale, useThemedStyles, type ThemeColors } from '@/theme';
+import { CompanionCardButton } from './CompanionCardButton';
+
+/** How long a message may wait for the main computer before the switch is offered. */
+export const CLOUD_HOME_UNREACHABLE_AFTER_MS = 15_000;
+
+/** True once `waiting` has held continuously for `afterMs` (a message cannot reach the computer). */
+export function useSustained(waiting: boolean, afterMs = CLOUD_HOME_UNREACHABLE_AFTER_MS): boolean {
+ const [sustained, setSustained] = useState(false);
+ useEffect(() => {
+ if (!waiting) { setSustained(false); return; }
+ const timer = setTimeout(() => setSustained(true), afterMs);
+ return () => clearTimeout(timer);
+ }, [afterMs, waiting]);
+ return waiting && sustained;
+}
+
+export function CloudHomeUnreachableNotice({ deviceName, onSwitch }: { deviceName: string; onSwitch(): void }) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ return <View style={styles.card} accessibilityRole="alert" testID="cloudHome.unreachable">
+ <Text style={styles.copy}>{t('devices.cloudCompanion.sendUnreachable', { device: deviceName })}</Text>
+ <CompanionCardButton primary label={t('devices.cloudCompanion.switchAction')} onPress={onSwitch} testID="cloudHome.unreachable.switch" />
+ </View>;
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ card: {
+ gap: spacing.sm, marginHorizontal: spacing.lg, marginTop: spacing.sm, padding: spacing.md,
+ borderRadius: radius.container, backgroundColor: colors.surfaceElevated,
+ },
+ copy: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+});
diff --git a/apps/mobile/src/session/CompanionHeader.tsx b/apps/mobile/src/session/CompanionHeader.tsx
index 21e4c89975..1b944bba8c 100644
--- a/apps/mobile/src/session/CompanionHeader.tsx
+++ b/apps/mobile/src/session/CompanionHeader.tsx
@@ -12,6 +12,8 @@ import { CHAT_HEADER_GLYPH_STROKE, CHAT_HEADER_MARK_SIZE, ChatIdentityHeader, Ch
import { CompanionPresenceRing } from './CompanionPresenceRing';
import { CompanionProfileSheet } from './CompanionProfileSheet';
import { useTeammateNavigation } from './useTeammateNavigation';
+import { CloudHomeSwitchSheet } from './CloudHomeSwitchSheet';
+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
/** Presence dot before the computer name (the list's dot, sized for a 12pt line). */
const PRESENCE_DOT = 6;
@@ -37,6 +39,10 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, contro
const styles = useThemedStyles(makeStyles);
const {colors}=useTheme();
const navigation = useTeammateNavigation();
+ // A cloud companion is one teammate wherever it runs: name its main computer and offer to change it.
+ const cloud = useCloudCompanionHome(true);
+ const homed = cloud.supported && cloud.actors.some(actor => actor.kind === 'bot' && actor.externalId === resource.ref.id && actor.homeDeviceId === deviceId);
+ const [homeSheet, setHomeSheet] = useState(false);
const [profile, setProfile] = useState(false);
const [todos, setTodos] = useState(false);
const [initialPage, setInitialPage] = useState<'home' | 'memory' | 'capabilities'>('home');
@@ -44,7 +50,9 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, contro
const pending = useRef<(() => void) | null>(null);
const name = resolveRemoteText(resource.display.title, i18n.language);
const afterProfile = (action: () => void) => { pending.current = action; setProfile(false); };
- const connection = online ? '' : t('devices.resources.hostOffline');
+ // A cloud companion does not show its computer's presence (it belongs to the account, like an IM
+ // contact); a message that cannot get through is what asks to switch computers.
+ const connection = online || homed ? '' : t('devices.resources.hostOffline');
return <>
<ChatIdentityHeader testIDPrefix="companion"
mark={<>
@@ -53,8 +61,8 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, contro
</>}
title={name}
subtitle={<View style={styles.subtitleRow}>
- <View style={[styles.presence, online ? styles.presenceOn : styles.presenceOff]} testID="companion.header.presence" />
- <ChatIdentitySubtitle>{connection ? `${connection} · ${deviceName}` : deviceName}</ChatIdentitySubtitle>
+ {homed ? null : <View style={[styles.presence, online ? styles.presenceOn : styles.presenceOff]} testID="companion.header.presence" />}
+ <ChatIdentitySubtitle>{[connection, homed ? t('devices.cloudCompanion.runsOn', { device: deviceName }) : deviceName].filter(Boolean).join(' · ')}</ChatIdentitySubtitle>
</View>}
identityLabel={[name, deviceName, connection].filter(Boolean).join(', ')}
identityHint={t('devices.companions.openProfile', { name })}
@@ -67,7 +75,11 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, contro
<CompanionProfileSheet initialPage={initialPage} visible={profile} onClose={() => setProfile(false)} onClosed={() => { const action = pending.current; pending.current = null; action?.(); }}
resource={resource} collectionId={resource.ref.collectionId} deviceId={deviceId} deviceName={deviceName} online={online}
onDeleted={() => void navigation.chooseMode('teammates')}
- onOpenSearch={() => afterProfile(onSearch)} />
+ onOpenSearch={() => afterProfile(onSearch)}
+ {...(homed && online ? { onOpenHome: () => afterProfile(() => setHomeSheet(true)) } : {})} />
+ {homed ? <CloudHomeSwitchSheet visible={homeSheet} onClose={() => setHomeSheet(false)} botId={resource.ref.id} name={name}
+ homeDeviceId={deviceId} homeName={deviceName}
+ onMoved={() => { setHomeSheet(false); void navigation.chooseMode('teammates'); }} /> : null}
</>;
}
diff --git a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx
index 271a1afad1..46d8fbc4d1 100644
--- a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx
+++ b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx
@@ -58,6 +58,7 @@ export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {
</HStack></Section>
<Section>{row('profile', 'person.crop.circle')}{row('memory', 'brain')}{row('models', 'slider.horizontal.3')}{row('skills', 'sparkles')}</Section>
<Section>{row('artifacts', 'doc.text')}{p.onSearch ? row('search', 'magnifyingglass', p.onSearch) : null}{row('permissions', 'hand.raised')}</Section>
+ {p.onHome ? <Section>{row('home', 'desktopcomputer', p.onHome)}</Section> : null}
<Section>{p.data?.panels.filter(item => ['restart', 'resume', 'delete'].includes(item.id) && item.action).map(item => <Button key={item.id} onPress={() => p.onConfirm(item)} modifiers={[buttonStyle('plain'), listRowInsets({ top: 4, bottom: 4, leading: 16, trailing: 16 }), disabled(p.busy || !p.online), frame({ minHeight: 44 }), ...(item.id === 'delete' ? [foregroundStyle(colors.destructive)] : [])]}><HStack modifiers={[frame({ maxWidth: Infinity, minHeight: 44 }), contentShape(shapes.rectangle())]}><Text>{label(item.action!.label)}</Text><Spacer /></HStack></Button>)}</Section>
{/* Same as Android: a host without the settings forms asks for a Cindy update on that computer. */}
{p.online && p.data && !p.data.panels.some(item => item.id === 'profile') ? note(tr('hostUpgrade')) : null}
diff --git a/apps/mobile/src/session/CompanionProfileNativeView.tsx b/apps/mobile/src/session/CompanionProfileNativeView.tsx
index 493380cbc3..2a0c12be11 100644
--- a/apps/mobile/src/session/CompanionProfileNativeView.tsx
+++ b/apps/mobile/src/session/CompanionProfileNativeView.tsx
@@ -14,6 +14,8 @@ export interface CompanionProfileNativeViewProps {
onConfirm(panel: ProfilePanel | null): void; onRetry(): void; onDiscard(reload: boolean): void;
onEditor(resourceId: string): void; onEditorPanel(panel: ProfilePanel): void;
onSearch?(): void;
+ /** Change the computer this companion runs on (cloud companions). */
+ onHome?(): void;
}
// SwiftUI is isolated from Android's bundle. The shared component owns all draft/save logic.
export function CompanionProfileNativeView(_props: CompanionProfileNativeViewProps) { return null; }
diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsx
index c597ef8c44..b1d7c7e09c 100644
--- a/apps/mobile/src/session/CompanionProfileSheet.tsx
+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx
@@ -4,7 +4,7 @@ import { useRouter } from 'expo-router';
import { randomUUID } from 'expo-crypto';
import { ActivityIndicator, Alert, Image, Platform, Pressable, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
-import { Brain, Camera, FileText, Hand, History, Info, Link2, Settings2, Sparkles } from 'lucide-react-native';
+import { Brain, Camera, FileText, Hand, History, Info, Link2, Monitor, Settings2, Sparkles } from 'lucide-react-native';
import { resolveRemoteText, type RemoteResource, type RemoteResourceRef, type RemoteText } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { Text, TextInput } from '@/components/AppText';
@@ -46,6 +46,8 @@ export interface CompanionProfileSheetProps {
online: boolean;
onDeleted?: () => void;
onOpenSearch?: () => void;
+ /** Change the computer this companion runs on (cloud companions). */
+ onOpenHome?: () => void;
}
/** Identity-keyed content prevents previous-account drafts and reads from surviving a switch. */
export function CompanionProfileSheet(props: CompanionProfileSheetProps) {
@@ -56,7 +58,7 @@ export function CompanionProfileSheet(props: CompanionProfileSheetProps) {
/** One navigation host, with real host reads, draft guards and in-surface confirmations. */
function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
- const { visible, resource, collectionId, deviceId, deviceName, online, onClose, onOpenSearch } = props;
+ const { visible, resource, collectionId, deviceId, deviceName, online, onClose, onOpenSearch, onOpenHome } = props;
const { t, i18n } = useTranslation();
const router = useRouter();
const pendingTask = useRef<string | null>(null);
@@ -360,7 +362,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
onConfirm={confirm}
onRetry={retry} onDiscard={discardDraft}
onEditor={id => void openEditor(id)} onEditorPanel={selectEditorPanel}
- onSearch={onOpenSearch} /></>;
+ onSearch={onOpenSearch} {...(onOpenHome ? { onHome: onOpenHome } : {})} /></>;
// Android mirrors the iOS page map, entry order and save rules; only the surface is platform-drawn.
const save = (target: ProfilePanel, blocked: boolean) => <MainWindowActionButton action={{ label: t('devices.companionProfile.save'), busy,
@@ -381,6 +383,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
</View>
<View style={styles.group}>{row('profile', Info)}{row('memory', Brain)}{row('models', Sparkles)}{row('skills', Settings2)}</View>
<View style={styles.group}>{row('artifacts', FileText)}{onOpenSearch ? row('search', History, onOpenSearch) : null}{row('permissions', Hand)}</View>
+ {onOpenHome ? <View style={styles.group}>{row('home', Monitor, onOpenHome)}</View> : null}
{/* Host order, like iOS: restart / resume / delete are whatever the computer offers now. */}
{management.length ? <View style={styles.group}>{management.map(item => actionRow(item, () => confirm(item), item.id === 'delete'))}</View> : null}
{online && data && !actionPanel('profile') ? note('hostUpgrade') : null}
diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsx
index 36276d501c..6d31c45dc0 100644
--- a/apps/mobile/src/session/TeammateHomeScreen.tsx
+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx
@@ -29,7 +29,7 @@ import { useTeammateRoster } from './useTeammateRoster';
import { useBotGroupRoster } from './useBotGroupRoster';
import { useTeammateNavigation } from './useTeammateNavigation';
import { remoteSessionStore } from './remoteSessionStore';
-import { cloudActorForRow, cloudCompanionRows } from '@/chat/cloudCompanion';
+import { CLOUD_ROW_REVISION, cloudActorForRow, cloudCompanionRows } from '@/chat/cloudCompanion';
import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
import { cloudCompanionRoute } from './teammateNavigation';
import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';
@@ -55,7 +55,10 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {
// One row per companion, under its main computer (a row built from the cloud when none is listed).
const items = useMemo(() => cloud.supported ? cloudCompanionRows(roster.items, cloud.actors, cloud.deviceNames) : roster.items,
[cloud.actors, cloud.deviceNames, cloud.supported, roster.items]);
- const cloudActor = (row: HostedRemoteCollectionItem) => cloud.supported && !roster.isOnline(row.host) ? cloudActorForRow(cloud.actors, row) : null;
+ // A cloud companion opens its normal chat (cached when its computer is unreachable). Only a row
+ // this phone knows from the cloud alone (never listed by its computer) opens the cloud conversation.
+ const cloudActor = (row: HostedRemoteCollectionItem) => cloud.supported && row.item.revision === CLOUD_ROW_REVISION ? cloudActorForRow(cloud.actors, row) : null;
+ const quietPresence = (row: HostedRemoteCollectionItem) => cloud.supported && !!cloudActorForRow(cloud.actors, row);
// A companion moved by another device shows up as changed roster rows (a new row, or a cached
// row whose computer re-listed it): re-read the main computers then, not only on focus.
const listedCompanions = roster.items.map(row => `${row.key}\t${row.item.revision}`).sort().join('\n');
@@ -158,7 +161,7 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {
</View>
</>}
<TeammateList key={searchEpoch} {...roster} items={items}
- cloudOpenable={(row) => !!cloudActor(row)}
+ quietPresence={quietPresence}
topInset={nativeHeader ? headerHeight : undefined}
notice={navigation.saveFailed ? <Text accessibilityRole="alert" style={styles.notice}>{t('devices.companions.preferenceSaveFailed')}</Text> : null} autoFocusSearch={searchEpoch > 0}
loading={roster.items.length + groups.items.length === 0 && (roster.loading || groups.loading)}
diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsx
index 802a457e36..8757bcb7fb 100644
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@ -51,10 +51,11 @@ export interface TeammateListProps {
isOnline(host: RemoteResourceHostTarget): boolean;
connectionState?(host: RemoteResourceHostTarget): boolean | null;
/**
- * The row's computer is the companion's main computer and the server keeps its cloud
- * conversation: an offline row stays openable (docs/product-rules/cloud-companions.md §3.1).
+ * A cloud companion's row (docs/product-rules/cloud-companions.md §3.1): it belongs to the
+ * account, so presence is not shown — like an IM contact, it stays a normal row while its
+ * computer is briefly unreachable; a send that cannot get through is what asks to switch.
*/
- cloudOpenable?(row: HostedRemoteCollectionItem): boolean;
+ quietPresence?(row: HostedRemoteCollectionItem): boolean;
onRefresh(): void;
onSelect(item: HostedRemoteCollectionItem): void;
/** SheetSurface already owns the scroll view. */
@@ -90,7 +91,7 @@ function useAwaitingSessions(items: readonly HostedRemoteCollectionItem[]): Read
}
/** Identity list shared by home (with group chats) and the collection route. No host headings. */
-export function TeammateList({ items, loading, refreshing, error, isOnline, connectionState, cloudOpenable, onRefresh, onSelect,
+export function TeammateList({ items, loading, refreshing, error, isOnline, connectionState, quietPresence, onRefresh, onSelect,
embedded = false, autoFocusSearch = false, onInteract, groups, emptyAction, scrollInsetProps, topInset, notice }: TeammateListProps) {
const { t, i18n } = useTranslation();
const { user } = useAuth();
@@ -182,19 +183,19 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, conn
const timestamp = display.timestamp;
const time = timestamp !== undefined && Number.isFinite(new Date(timestamp).getTime())
? formatRemoteSessionSidebarTime(new Date(timestamp).toISOString(), now) : '';
- const cloud = !online && !!cloudOpenable?.(row);
- const connection = cloud ? t('devices.cloudCompanion.homeOffline', { device: row.host.deviceName })
+ const quiet = !!quietPresence?.(row);
+ const connection = quiet ? ''
: connected === false ? t('devices.resources.hostOffline') : connected === null ? t('devices.resources.connectionUnknown') : '';
const prefix = attention || (waiting ? t('devices.companions.awaiting') : '');
return <CompanionListRow key={`bot:${row.key}`} testID={`teammates.item.${row.host.deviceId}.${row.item.ref.id}`}
accessibilityLabel={[title, ambiguous ? row.host.deviceName : '', connection, prefix, generating ? workingCopy : summary, time,
unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}
avatar={<>
- <View style={connected === false ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>
+ <View style={connected === false && !quiet ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>
<RemoteCompanionAvatar avatar={display.avatar} deviceId={row.host.deviceId} name={title} online={connected === true} size={COMPANION_ROW_AVATAR_SIZE} framed />
</View>
<CompanionPresenceRing active={generating} />
- <CompanionPresenceDot connected={connected} />
+ {quiet ? null : <CompanionPresenceDot connected={connected} />}
</>}
title={title}
device={ambiguous ? row.host.deviceName : undefined}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index c16ac0f894..244d971bd4 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -18,7 +18,7 @@
| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
| `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 |
| `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatReplyIcon.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/linkInteraction.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/favoritesSyncFailure.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 519 |
+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatReplyIcon.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/linkInteraction.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/favoritesSyncFailure.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionAvatarCache.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 522 |
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 45 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 3 |
| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatReplyIcon.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/McpAppCard.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/linkInteraction.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/favoritesSyncFailure.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 249 | 38 | 341 |
@@ -54,7 +54,7 @@
| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 59 |
| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, LoginCaptchaWebView, LoginNativeButton, LoginNativeButton.ios, LoginSkinControls, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, MobileUserAvatar, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileUserAvatar.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 221 | 84 |
| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, CompanionNativeContent.ios, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, DeviceLinkContext, FileTypeIcon, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, ImageLightbox, IncomingShareBridge, McpAppViews, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, composerPullThrough, gestureHandler, mediaPlayerWebView, nativeToolbarMenuItems, new, peerFileTransport, useLocale, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/FileTypeIcon.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/voicePillWidthMotion.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 251 | 117 |
-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, ChatReplyIcon, CindyMakeSessionGate, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionEntering, CompanionHeader, CompanionImportSheet, CompanionLearningFooter, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionMessageActions, CompanionMessageCard, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionPresenceRing, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, CompanionTodoRow, CompanionTodos, CompanionWorkingStatus, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, McpAppCard, McpAppViews, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileUserAvatar, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, MountOnFirstOpen, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginCardActions, PluginInvocationHeader, PluginMenuUnreadDot, PluginSetupNativeActions, PluginSetupNativeForm, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, ReadableHistoryRecovery, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionEntryRecovery, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, TodoDateInput, TodoDateInput.android, TodoDateInput.ios, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, composerPullThrough, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, useSharedTaskConfirmation, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ChatReplyIcon.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/FileTypeIcon.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileUserAvatar.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/PluginCardActions.tsx, apps/mobile/src/plugins/PluginMenuUnreadDot.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AgentErrorDetails.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CindyMakeSessionGate.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionHeader.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/CompanionTaskResultCard.tsx, apps/mobile/src/session/CompanionTodoRow.tsx, apps/mobile/src/session/CompanionTodos.tsx, apps/mobile/src/session/CompanionWorkingStatus.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerMorphSource.ios.tsx, apps/mobile/src/session/ComposerMorphSource.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSessionInfoMeta.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/HomeUnreadContext.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/McpAppCard.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/MountOnFirstOpen.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/ReadableHistoryRecovery.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/RunningTokenRatePopover.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionActionSheetFrame.android.tsx, apps/mobile/src/session/SessionActionSheetFrame.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionEntryRecovery.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionTransientNotice.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/TodoDateInput.android.tsx, apps/mobile/src/session/TodoDateInput.ios.tsx, apps/mobile/src/session/TodoDateInput.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/session/voicePillWidthMotion.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 252 | 321 |
+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AgentErrorDetails, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, ChatIdentityHeader, ChatReplyIcon, CindyMakeSessionGate, CloudHomeSwitchSheet, CloudHomeUnreachableNotice, CompanionCardButton, CompanionChoice, CompanionCreateNativeView, CompanionCreateNativeView.ios, CompanionEntering, CompanionHeader, CompanionImportSheet, CompanionLearningFooter, CompanionMemoryPage, CompanionMemoryPage.ios, CompanionMessageActions, CompanionMessageCard, CompanionModelChain, CompanionNativeContent.ios, CompanionPortraitPicker, CompanionPresenceRing, CompanionProfileArtifacts, CompanionProfileNativeView, CompanionProfileNativeView.ios, CompanionProfileSheet, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, CompanionTaskResultCard, CompanionTodoRow, CompanionTodos, CompanionWorkingStatus, ComposerActivityPill, ComposerAttachmentTray, ComposerDockKeyboardFollow, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerMorphSource, ComposerMorphSource.ios, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetCollabView, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ContextSheetPlugins, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FileTypeIcon, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeModeSwitch, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSessionInfoMeta, HomeStackHeader, HomeSurface, HomeUnreadContext, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InputHandoffCard, InputHandoffDeviceCode, InputHandoffPictureStep, InputHandoffQrCode, InputHandoffRecordRow, InputHandoffSheet, InputHandoffSheet.ios, InputHandoffStepFields, InteractionPanel, MarkdownBlockContent, McpAppCard, McpAppViews, MessageActionSheet, MessageLoadingImage, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobileOutboxBridge, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileUserAvatar, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, MountOnFirstOpen, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NativeVideoPlayer, NewTaskSelectionRow, NewTaskSelectionSheet, NewTaskSelectionSheet.android, NewTaskSelectionSheet.ios, OrcaWorkerDirectoryPicker, OutsideTap, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginCardActions, PluginInvocationHeader, PluginMenuUnreadDot, PluginSetupNativeActions, PluginSetupNativeForm, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, ReadableHistoryRecovery, RecentMessageHistories, RemoteAccessGuide, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, RemoteSourceMark, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, RunningTokenRatePopover, SentInlineAtomBody, SessionActionSheet, SessionActionSheetFrame, SessionActionSheetFrame.android, SessionDetailsNative, SessionDetailsNative.ios, SessionEntryRecovery, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionRightSpinner, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionTransientNotice, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, ThinkingDots, TodoDateInput, TodoDateInput.android, TodoDateInput.ios, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, WorkingStatusText, [sessionId], _layout, composerPullThrough, gestureHandler, listDisclosureTransition, mathWebView, mediaPlayerWebView, mermaidWebView, nativeToolbarMenuItems, peerFileTransport, useLocale, useSharedTaskConfirmation, voicePillWidthMotion | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ChatReplyIcon.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/FileTypeIcon.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileUserAvatar.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/inputHandoff/InputHandoffCard.tsx, apps/mobile/src/inputHandoff/InputHandoffDeviceCode.tsx, apps/mobile/src/inputHandoff/InputHandoffPictureStep.tsx, apps/mobile/src/inputHandoff/InputHandoffQrCode.tsx, apps/mobile/src/inputHandoff/InputHandoffRecordRow.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.ios.tsx, apps/mobile/src/inputHandoff/InputHandoffSheet.tsx, apps/mobile/src/inputHandoff/InputHandoffStepFields.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/plugins/PluginCardActions.tsx, apps/mobile/src/plugins/PluginMenuUnreadDot.tsx, apps/mobile/src/plugins/PluginSetupNativeActions.tsx, apps/mobile/src/plugins/PluginSetupNativeForm.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AgentErrorDetails.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CindyMakeSessionGate.tsx, apps/mobile/src/session/CloudHomeSwitchSheet.tsx, apps/mobile/src/session/CloudHomeUnreachableNotice.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionChoice.tsx, apps/mobile/src/session/CompanionCreateNativeView.ios.tsx, apps/mobile/src/session/CompanionCreateNativeView.tsx, apps/mobile/src/session/CompanionEntering.tsx, apps/mobile/src/session/CompanionHeader.tsx, apps/mobile/src/session/CompanionImportSheet.tsx, apps/mobile/src/session/CompanionLearningFooter.tsx, apps/mobile/src/session/CompanionMemoryPage.ios.tsx, apps/mobile/src/session/CompanionMemoryPage.tsx, apps/mobile/src/session/CompanionMessageActions.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/CompanionModelChain.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPortraitPicker.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionProfileArtifacts.tsx, apps/mobile/src/session/CompanionProfileNativeView.ios.tsx, apps/mobile/src/session/CompanionProfileNativeView.tsx, apps/mobile/src/session/CompanionProfileSheet.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/CompanionTaskResultCard.tsx, apps/mobile/src/session/CompanionTodoRow.tsx, apps/mobile/src/session/CompanionTodos.tsx, apps/mobile/src/session/CompanionWorkingStatus.tsx, apps/mobile/src/session/ComposerActivityPill.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerDockKeyboardFollow.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerMorphSource.ios.tsx, apps/mobile/src/session/ComposerMorphSource.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetCollabView.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ContextSheetPlugins.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeModeSwitch.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSessionInfoMeta.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/HomeUnreadContext.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/McpAppCard.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageLoadingImage.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/MountOnFirstOpen.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NativeVideoPlayer.tsx, apps/mobile/src/session/NewTaskSelectionRow.tsx, apps/mobile/src/session/NewTaskSelectionSheet.android.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/OrcaWorkerDirectoryPicker.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/ReadableHistoryRecovery.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/RemoteSourceMark.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/RunningTokenRatePopover.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionActionSheetFrame.android.tsx, apps/mobile/src/session/SessionActionSheetFrame.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionEntryRecovery.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionRightSpinner.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionTransientNotice.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/ThinkingDots.tsx, apps/mobile/src/session/TodoDateInput.android.tsx, apps/mobile/src/session/TodoDateInput.ios.tsx, apps/mobile/src/session/TodoDateInput.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/WorkingStatusText.tsx, apps/mobile/src/session/composerPullThrough.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/listDisclosureTransition.tsx, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/session/voicePillWidthMotion.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 252 | 323 |
| `mobile.chat.sharing` | mobile | 共享任务邀请与成员;供应商分享链接提示 | app/shared-session.tsx / app/provider-share.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskEndedState, SharedTaskScreen, SheetModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, provider-share, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/provider-share.tsx, apps/mobile/app/shared-session.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 68 |
| `mobile.companions.cloud` | mobile | 云端伙伴:主力电脑离线时的对话与换电脑 | app/companions/cloud/[actorId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, BotGroupAvatars, BotGroupMessageText, CenteredScreen, ChatIdentityHeader, CloudCompanionScreen, CompanionCardButton, CompanionNativeContent.ios, CompanionPresenceRing, CompanionSettingsRow, CompanionSettingsRow.ios, CompanionSheet, CompanionSheet.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [actorId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/cloud/[actorId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/BotGroupAvatars.tsx, apps/mobile/src/session/BotGroupMessageText.tsx, apps/mobile/src/session/ChatIdentityHeader.tsx, apps/mobile/src/session/CloudCompanionScreen.tsx, apps/mobile/src/session/CompanionCardButton.tsx, apps/mobile/src/session/CompanionNativeContent.ios.tsx, apps/mobile/src/session/CompanionPresenceRing.tsx, apps/mobile/src/session/CompanionSettingsRow.ios.tsx, apps/mobile/src/session/CompanionSettingsRow.tsx, apps/mobile/src/session/CompanionSheet.ios.tsx, apps/mobile/src/session/CompanionSheet.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 71 |
| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 57 |
diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.md
index 82697aea1a..8fcece13ad 100644
--- a/docs/dev-rules/media-storage-and-protocols.md
+++ b/docs/dev-rules/media-storage-and-protocols.md
@@ -110,6 +110,13 @@
对象名为 `wallpapers/<sha256>.webp` / `.mp4`;缩略图可用
`node scripts/prepare-wallpaper-previews.mjs` 从原始图片重建,总预算 300 KiB。
清单见 Desktop 的 `src/shared/wallpaper-video-manifest.json`。
+- 伙伴头像的本机副本(2026-10-17 用户裁决:读过的头像在本机缓存一份,显示前先读缓存):另一台电脑上
+ 伙伴的 `cindy-media://blobs/…` 头像与云端伙伴身份的 `https://` 公开头像,经 `companion-cloud/avatarCache.ts`
+ 复用集成缓存的索引(`integration-cache` 引用行,键 `companion-avatar:…`,`isCache: true`)入仓,由回收器按
+ 总量上限与 LRU 统一回收,不另建目录、store 或协议。本机已有同指纹 blob 时直接使用,不再复制。只保存主机按
+ 字节识别为图片、且不超过头像上限(5 MB)的内容;公开头像走共用的受控公网图片下载。两种地址各自不可变
+ (blob 地址即内容指纹,云端换头像会生成新地址),命中不需要重新校验。Renderer 经
+ `maker:companion-avatar:resolve` 先查本机副本,未命中时照常显示原地址并在后台保存一份。
- 可再生 HTML 临时快照缓存是独立副本的例外:仅在快照已物化自己的文件、HTTP 服务不依赖
媒体仓 blob、且该缓存不作为持久附件提交时,使用 `isCache: true` 和空引用入仓。
必须验证媒体仓缓存不可用时快照仍可读取,以及重复打开、失败、取消和重试不新增业务引用;
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index c59cbfe552..30342424d1 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2117,3 +2117,15 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca
请求期间被挡住;取消确认不发起删除。UI 继续复用语义颜色与标准确认弹窗。
确认删除同时阻止在途冷缓存回填、清理该设备磁盘缓存并作废删除前的目录读取;
目录暂时不可用时,其他离线设备继续保留缓存。
+
+## 云端伙伴:从任意电脑更换主力电脑
+
+`maker:companion-cloud:caps` 的 `companionCloud` 从 1 升到 2,新增两个同账号 device-link channel:只读的
+`maker:companion-cloud:targets`(主力电脑视角下可接手的电脑)与写入的 `maker:companion-cloud:hand-over`
+(`[botId, targetDeviceId, options?]`,在主力电脑上走原有交出流程;`options.whenBusy` 为 `wait` / `stop`,老主力电脑忽略;隧道超时 7 分钟),以及合并 Cindy 的 `maker:companion-cloud:merge`(`[keepBotId, fromBotIds]`,只在本机运行保留的 Cindy 时执行,隧道超时 10 分钟)和合并前请来源 Cindy 的主力电脑先同步的 `maker:companion-cloud:flush`(`[botId]`,只在本机是它的主力电脑时执行、不改主力电脑,忙碌时 `BUSY`,隧道超时 7 分钟;版本 < 2 或连不上的主力电脑不请求,合并按云端已有内容进行)。接手方仍只要求版本 ≥ 1,
+所以新旧电脑之间照常能互相交出;发起方读到主力电脑版本 < 2 时不提供远程更换,提示先更新那台电脑,
+不退回成直接改服务器上的主力电脑。旧发起方不知道新 channel,行为不变。两个 channel 不进共享任务访客白名单,
+不改 relay 帧、服务端 schema 或 Mobile 指纹。本机 IPC `maker:companion-cloud:transfer` / `:devices` 换成
+`: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` 块;旧客户端按文件名显示。手机端同样不改原生指纹。
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index ed34cc6ace..109a30bb4e 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -53,6 +53,7 @@
| 项目 | 列出、登记、改名、移除;工作目录列表 | 有 | 无 |
| 伙伴 | 发现伙伴、伙伴间消息 | 有 | 有 |
| 伙伴 | 资料、能力、工作台、待办、后台任务 | 有 | 无 |
+| 伙伴 | 查看与更换主力电脑 | 有 | 有(2026-10-17) |
表里「无」的项是待补的缺口,不是有意的限制。其中「切换权限档」「代用户确认权限或回答提问」
会让 Agent 改变约束自己的那一层,补之前需要单独的产品决定。
diff --git a/docs/product-rules/cloud-companions.md b/docs/product-rules/cloud-companions.md
index 3fd0ad9701..509fb4921d 100644
--- a/docs/product-rules/cloud-companions.md
+++ b/docs/product-rules/cloud-companions.md
@@ -21,16 +21,26 @@
其他电脑上原有的 Cindy 对话作为本机历史保留,可回看、可搜索,不再继续运行。其他伙伴本来就只
存在于一台电脑,那台电脑就是它的主力电脑。
+2026-10-16 产品裁决(Dash 确认):
+
+1. 每个伙伴都是跨设备存在的同一个伙伴,主力电脑只决定 Agent 在哪台电脑上运行;用户在**任何一台电脑**上
+ 都能手动更换主力电脑,换完仍是同一个伙伴、同一段聊天(§3.1)。
+2. 多台电脑上原有的 Cindy 合成一个:统一身份与聊天,保留旧记录的来源,资料冲突时由用户选择保留哪份
+ (替代上面第 4 条里「其他电脑上的 Cindy 对话只作本机历史」的做法,分批落地,见 §6「未覆盖」)。
+
## 2. 数据归属
| 存在服务器(跟着伙伴走) | 只留在主力电脑 |
|---|---|
| 身份:名字、头像(Chat Server actor) | 工作目录 `workspace/` 与其中文件 |
-| 资料:简介、SOUL、自定义提示词、关于用户(USER.md) | 模型连接、登录凭证、MCP 配置、权限档 |
-| 记忆:`memories/*.md` 每条一份 | 完整运行记录(工具调用、思考、附件原件) |
-| 自有技能:`skills/<slug>/SKILL.md` | 例行任务的定义与执行(只在主力电脑运行) |
-| 1:1 对话层:用户消息与伙伴最终回复 | 待办 `todos.v1.json` |
-| 主力电脑(`homeDeviceId`) | 工作台项目登记 |
+| 资料:简介、SOUL、自定义提示词、关于用户(USER.md)、来自哪个预设(`templateId`) | 模型连接、登录凭证、MCP 配置、权限档 |
+| 记忆:`memories/*.md` 每条一份 | 完整运行记录(工具调用、思考) |
+| 自有技能:`skills/<slug>/SKILL.md` | 例行任务的执行与运行记录(只在主力电脑运行) |
+| 1:1 对话层:用户消息与伙伴最终回复,以及主人发送的附件原件 | 待办里在途的投递、插件的游标与回执 |
+| 待办(未完成、设为稍后、近 30 天内完成的,最多 500 条,每条一份) | 工作台项目的文件本身 |
+| 例行任务的定义(每条一份,不含运行记录) | |
+| 工作台:项目目录(标明在哪台电脑上)与 PR / issue / 想法的判断 | |
+| 主力电脑(`homeDeviceId`) | |
- 服务器是对话层与资料快照的权威副本;主力电脑是运行与写入的唯一来源。
- **只有主力电脑写云端资料**。其他电脑修改伙伴设置时,经现有远程设置(device-link)写到主力电脑,
@@ -52,8 +62,18 @@
### 3.1 离线与切换
-- 伙伴的主力电脑离线时:伙伴列表与聊天头部显示「主力电脑「<名字>」离线」;聊天区显示云端对话(只读)
- 与一条横幅「主力电脑「<名字>」离线 · 在这台电脑继续」。
+- 像 IM 一样,主力电脑一时连不上不打扰浏览:伙伴列表和聊天头部不显示离线文字、离线圆点,头像不变暗;
+ 已打开的聊天保持原样(手机照常显示本机缓存的聊天,桌面在连不上的头 15 秒内保留当前聊天)。连接状态会随重连
+ 抖动,不能把一次断线当成主力电脑离线。
+- 真的用不了时才提示:
+ - 手机:发出的消息持续 15 秒仍送不到主力电脑,聊天区出现「消息还没送到主力电脑「<名字>」…」与「换一台电脑继续」;
+ 消息送达后提示立即消失。
+ - 桌面:主力电脑持续连不上超过 15 秒,或打开时就连不上,聊天区改为云端对话(只读)与横幅
+ 「主力电脑「<名字>」离线 · 在这台电脑继续」。
+ - 这台设备从没列到过主力电脑名下的伙伴(只能从云端补行),点开直接进入云端对话。
+- 云端对话与在线聊天显示同样的消息:主人发的消息(包括主人在主力电脑上直接输入的)都上云;别的来源
+ (任务、其他伙伴、插件、共享成员、定时任务、IM 渠道、群聊)发进来的消息加「〔来自…〕」前缀;只有不在聊天里
+ 显示的内部续接输入不上云。
- 点「在这台电脑继续」:
1. 服务器把主力电脑改成这台电脑(带原主力电脑做比较,避免两端同时抢);
2. 这台电脑按云端资料、记忆和技能建立(或更新)本机伙伴,伙伴 ID 与云端一致;
@@ -63,14 +83,36 @@
电脑,那台电脑收到变化后自动完成第 2、3 步,手机随即打开那台电脑上的伙伴。
- 原主力电脑重新上线后,发现主力电脑已换走:停止领取执行,隐藏本机副本,伙伴改为显示在新主力
电脑名下。它离线期间没来得及上传的资料以服务器版本为准,不回写覆盖。
-- 伙伴设置的「主力电脑」一行显示当前主力电脑;在主力电脑上可以把伙伴交给另一台在线电脑,规则同上。
+- 伙伴设置的「主力电脑」一行和聊天头部的「在「X」上运行」显示当前主力电脑,任何一台电脑上都能点开更换:
+ - 本机就是主力电脑:列出可接手的其他电脑,由本机交出(下面 §6 的交出规则)。
+ - 主力电脑是另一台在线、可远程控制的电脑:列出那台电脑视角下可接手的电脑(包括这台),选中后经 device-link
+ 请主力电脑按同一套交出规则交出(`maker:companion-cloud:targets` / `maker:companion-cloud:hand-over`);
+ 还在回复、资料没传完等情况由主力电脑拒绝并原样提示。换到这台电脑时,交出完成后立即重读主力电脑,
+ 本机按自动接管建立伙伴,建好后打开本机伙伴(约 2 分钟内没建好则提示稍后出现在列表里)。
+ - 主力电脑离线或连不上:只能「在这台电脑继续」(上面的接管)。
+ - 主力电脑上的 Cindy 版本不支持被远程请求交出:提示先更新那台电脑或在那台电脑上更换。
+- 伙伴已暂停时不交出,提示先恢复。
+
+### 3.2 头像
+
+- 伙伴头像是身份的一部分,跟着伙伴存在服务器(主力电脑上传为公开图片地址),供群聊成员、手机、主力电脑离线时的
+ 其他电脑和换电脑时恢复使用。
+- 读过的头像在本机缓存一份,显示时先读本机副本,没有才去主力电脑或服务器取,取到后保存;因此主力电脑离线、
+ 服务器暂时连不上或重启之后,读过的头像照常显示。缓存可回收,回收后下次重新获取。实现与存储边界见
+ [媒体存储](../dev-rules/media-storage-and-protocols.md)「伙伴头像的本机副本」。
+- 头像只把单个表情或字符当作文字显示;网址等其他内容加载不了时显示名字首字,不会把地址画成文字。
## 4. 1:1 对话层同步
- 每个伙伴在 Chat Server 上有一个固定的私聊房间(主人 ↔ 伙伴),房间 ID 由伙伴 actor ID 确定,
任意电脑并发创建得到同一个房间。
- 主力电脑把主任务里用户可见的消息和伙伴的最终回复按顺序导入这个房间(导入不触发伙伴执行、不发通知),
- 以本机消息 ID 去重,断网后从上次位置续传。附件只同步文件名占位,原件留在主力电脑;只发附件没有文字的消息同样以占位同步。
+ 以本机消息 ID 去重,断网后从上次位置续传。主人发送的图片和文件经房间附件上传,其他设备可以打开,换电脑时下载到新电脑;
+ 只有永远传不了(文件已不在、超过大小、旧格式地址、聊天服务器拒绝)时才退回文件名占位;暂时失败(断网、服务器 5xx、超时、
+ 签名地址过期——对象存储返回 401/403)时这一轮停下、下一轮连同这条消息重试,换电脑时的下载与合并 Cindy 时的搬运同样按这条区分(暂时失败则
+ 接管或合并本次失败、稍后重试)。只发附件没有文字的消息同样同步。伙伴回复里引用的文件暂不上传。
+- 房间保存完整对话:开始同步之前的本机历史(包括这台电脑接管前自己的历史)在后台按时间从旧到新补传,每轮有上限,
+ 交出前补完。房间按到达顺序排列,读取时(离线查看、接管导入、手机)按消息时间排序。
- 主力电脑在线时,其他电脑与手机继续用现有远程方式(device-link)直接看和发主任务,体验不变。
- 主力电脑离线时,其他端从房间读取对话层;用户在离线横幅里选择切换电脑后再继续。
- 房间里由主人直接发出的消息(例如未来的离线排队)在主力电脑上线后由它领取,作为「来自其他设备」的
@@ -96,7 +138,7 @@
安装认领了伙伴时同样只删本机;本安装尚未确认认领(检查未完成,或伙伴刚被交到这台电脑)时,先按自动接管的方式认领,
抢到才停用,被另一个安装抢先则只删本机。其他电脑(包括删除时离线、之后才上线的)
看到云端伙伴已停用时,把本机副本转为降级:隐藏、只读、不运行。
-- 接管时导入云端最近 200 条对话为本机历史。服务器不回传导入来源 ID,本机按「角色 + 消息时间(毫秒)」
+- 接管时导入房间里的全部对话为本机历史(读到房间第一条为止,读不完整则这次接管失败、稍后重试;合并 Cindy 同样如此;云端对话查看最多读最近约 5 万条),附件一起下载。服务器不回传导入来源 ID,本机按「角色 + 消息时间(毫秒)」
识别这台电脑当初导入上去的消息;已插入的云端历史(`cloud-history:<消息>`)和房间里直接发给伙伴、已投递进本机主任务的消息(`chat-direct:<执行>:<消息>`)按房间消息 ID 识别,都不重复插入(接管中途失败重试时,同一时间的拆分片段不会被误跳过);之后像「重启伙伴」一样从历史重建上下文,伙伴还有一轮在跑时等它结束再重建,期间副本保持降级。
- 已降级的本机副本:不领取执行、不上传、不导入对话,不同步名字与头像,不出现在伙伴列表、主入口选择、
Cindy 多设备合并、本机 `list_agents` 和远程资源 `teammates` 列表(因此也不出现在其他设备的 `list_agents`),
@@ -124,18 +166,22 @@
- 接管后对话镜像从本机最后一条自有消息(不含导入的云端历史)之后开始,本机接管前的旧对话不上传到房间。
- 资料上传遇到版本冲突时先确认本机仍是主力电脑(否则停止并重新读取),再按服务器当前值最多重写一次;读本机资料(SOUL / USER / 自定义提示词)、
记忆与技能时只有「不存在」视为空,其它读取错误跳过本轮且不写墓碑;接管时读不到本机文件同样中止、保持降级重试;首次升级的大批写入每轮每台电脑最多约 30 条,其余下一轮。
-- 对话导入只导入主人亲手输入的用户消息(`agentMeta` 无来源标记,或只有 `sourceDevice`)与伙伴回复(不含私有协调回复、过程旁白 `assistantPhase: commentary` 与子 Agent 输出(`parentToolUseId` / `parent_tool_use_id`,以及与界面同一判据的 Claude `parentUuid`);一轮还没结束时、工具调用前的旁白仍按普通回复导入);来自其他
- 任务、伙伴、插件、IM、自动化、Orca、共享成员的输入一律不上云。游标之外每轮回扫最近 10 分钟(从窗口开头起最多 200 行;10 分钟内超过 200 行时,排在后面的晚落库回复可能漏掉、只留在本机),
- 补上晚落库的回复;接管导入的 `cloud-history:` 行不推进游标。首次同步只看本机最近 1,000 行,导入其中最近 200 条可上云的
- 消息;这 1,000 行里一条都没有时(例如主人最后一次输入后伙伴又处理了上千条自动化或 IM 输入),房间从此刻开始,更早的对话
- 只留在本机。已回退或删除的本机消息不导入,接管时也不再插回。
+- 对话导入与伙伴聊天里看到的一致(2026-10-17 Dash 确认:离线时的显示要和在线一样):主人输入的用户消息(含其他设备上的输入;`agentMeta.autoReviewUserText` 是主人本人输入的标记,不是其他来源)、伙伴回复(不含私有协调回复、过程旁白 `assistantPhase: commentary` 与子 Agent 输出(`parentToolUseId` / `parent_tool_use_id`,以及与界面同一判据的 Claude `parentUuid`);一轮还没结束时、工具调用前的旁白仍按普通回复导入),以及聊天里可见的其他来源输入(其他任务、伙伴、插件、IM、定时任务、协同、共享成员、群聊)。后者在正文前加一行与聊天标签同口径的来源,如「〔来自飞书〕」;IM 只取本人原话,不带宿主拼接的上下文。聊天里本来就隐藏的自动续跑(`autoResume`)、伙伴间协调(`botTaskCoordination`)与委派续跑不上云。游标之外每轮回扫最近 10 分钟(从窗口开头起最多 200 行;10 分钟内超过 200 行时,排在后面的晚落库回复可能漏掉、只留在本机),
+ 补上晚落库的回复;接管导入的 `cloud-history:` 行不推进游标。首次同步先导入本机最近 1,000 行里最近 200 条可上云的消息,
+ 更早的由补传带上(见 §4)。已回退或删除的本机消息不导入,接管时也不再插回。
- 已暂停的伙伴不交出(不同步资料与对话):设置里的「主力电脑」行提示先恢复再换电脑。
-- 伙伴在任一任务里(主任务、群聊 / 群分工专线、委派)还有一轮在运行或排队时不交出;已领取、尚未投递的 1:1 房间消息在投递前再确认本机仍是主力电脑,交出后不再投递(提示「还在回复,等这一轮结束再换电脑」),在同步前和改主力电脑前各检查一次,避免交出后旧电脑上的这一轮继续调用工具、改文件、产生不会同步的回复。
+- 伙伴在任一任务里(主任务、群聊 / 群分工专线、委派)还有一轮在运行或排队时默认不交出,界面问用户「等回复完再换」
+ (主力电脑上最多等约 4 分钟,期间这一轮的回复照常同步)或「停止并换」(按用户的停止停掉各任务里的这一轮,再交出);
+ 从其他电脑或手机发起时同样由主力电脑执行这两种选择;已领取、尚未投递的 1:1 房间消息在投递前再确认本机仍是主力电脑,交出后不再投递(提示「还在回复,等这一轮结束再换电脑」),在同步前和改主力电脑前各检查一次,避免交出后旧电脑上的这一轮继续调用工具、改文件、产生不会同步的回复。
- 交出伙伴前先把积压的对话全部导入房间(不受平时每轮最多 10 页的限制),再上传全部资料并重复上传直到一轮没有新变化,再立即同步伙伴的名字与头像(不再等下一轮登记;这个伙伴的头像上传失败同样不交出;别的伙伴头像有问题不影响,各伙伴的名字与头像分别同步),然后才改主力电脑(连续变化时不交出、提示失败),导入期间改动的资料也会带上;交出期间后台的定时上传与导入暂停(先等正在进行的一轮结束),
不会有旧的一轮在交出之后再写入云端;有超过上传
上限的值(例如过大的技能)时同样不交出,原主力电脑保持不变。
-- 交出伙伴前探测目标电脑的 `maker:companion-cloud:caps`(device-link 只读通道,返回 `{companionCloud: 1}`),
- 旧版本不支持则拒绝该目标;可选目标列表同样只列支持的电脑。手机端「换一台电脑继续」暂未探测(见下)。
+- 交出伙伴前探测目标电脑的 `maker:companion-cloud:caps`(device-link 只读通道,返回 `{companionCloud: <版本>}`;
+ 1 = 能接手伙伴,2 = 另外接受其他电脑请它交出伙伴),版本低于 1 则拒绝该目标;可选目标列表同样只列支持的电脑。
+ 其他电脑和手机请主力电脑交出前同样探测:低于 2 时不提供更换,提示先更新主力电脑。手机端离线横幅的「换一台电脑继续」暂未探测(见下)。
+- 请主力电脑交出(`maker:companion-cloud:hand-over`)是同账号远程控制写操作:只在主力电脑开启「允许同账号设备控制
+ 本机」时可用,不进共享任务访客白名单;隧道超时放宽到 7 分钟,因为交出前可能先等这一轮结束,再传完积压对话与全部资料。回执丢失时
+ 发起方立即重读主力电脑,按服务器上的实际主力电脑显示。
- 同一台电脑上的两个 Cindy 安装(例如开发版与正式版)共用设备标识。每个安装在自己的 userData 生成随机安装 ID,
主力电脑上的安装把伙伴偏好 `companion.install.v1 = {installationId, deviceId}` 写为自己的;设备相同但安装 ID 不同的
安装把伙伴视为降级(隐藏、不领取、不上传、不导入、不自动接管)。在那个安装里「在这台电脑继续」会改写这条记录;
@@ -156,8 +202,9 @@
它正在进行的那一轮上传(资料,或一批对话导入)可能在接走之后才写入云端;迟到的对话留在房间里,新主力电脑已完成的历史导入不会再吸收它,直到下次接管。资料方面:新主力电脑本机仍是接管时的值,且不会覆盖这次写入(首次同步只更新版本号,不把云端较新的值当成本机修改;本机真正改了这一项才会上传),下次接管时才拿到;
服务器的偏好写入不校验主力电脑,不为此新增服务端契约。
- 已知限制:哪些云端值由本机上传或接管写入,只记在账号隔离的状态文件里(只有这些键会写墓碑)。状态文件丢失或损坏后,
- 重建的记录不带这个归属:此后在本机删除的记忆或技能不会在云端删除,下次接管会带回来(原值仍在,不丢数据);
- 不为此另存一份归属。状态文件写入失败(例如磁盘已满)时,本次运行里的状态照常生效(降级立即生效),下一次更新时连同写入;
+ 重建的记录不带这个归属:此后在本机删除的记忆、技能、例行任务、工作台内容,以及超出随行范围的待办,不会在云端清掉,
+ 下次接管会带回来(原值仍在,不丢数据);不为此另存一份归属,也不按服务器上的键补写墓碑——状态丢失时分不清
+ 「本机删过」和「本机还没恢复」(例如接管途中丢失),补写可能删掉云端唯一的一份(2026-10-17 取舍:宁可多带回,不误删)。状态文件写入失败(例如磁盘已满)时,本次运行里的状态照常生效(降级立即生效),下一次更新时连同写入;
在写入成功前退出则丢失这些记录,按上面的状态文件丢失处理。降级名单(`shadowed.json`)读不出来或内容损坏时按空名单处理:服务器可达且功能开启时会按主力电脑
重新降级;在服务器不可达或功能关闭的那次启动里,旧副本可能暂时显示并可在本机使用。状态文件损坏不另做保护。
- 已知限制:「在这台电脑继续」用于原主力电脑离线(或被认为离线)时接管,不能等待或停止原电脑上正在运行的一轮。原电脑其实
@@ -166,8 +213,29 @@
- 已知限制:`/me` 返回的设备标识变化(例如重新绑定设备)会让这台电脑上所有伙伴转为降级;房间里的占位文字
(如 `[附件: …]`)固定为中文;降级发生时正在进行的那一轮不会导入;已导入房间后又在本机回退的消息仍留在房间;
删除伙伴时若当时没有可用的云端连接(未登录或旧服务器),不会记下待停用;手机换电脑不探测目标版本。
-- 未覆盖、留作后续:手机与非主力电脑离线编辑资料;例行任务与待办上云;IM 渠道按伙伴绑定;
- 离线时在其他端直接发送并排队。
+- 待办、例行任务与工作台跟着伙伴走:换电脑时在新电脑上按 ID 恢复(云端为准;例行任务的墓碑删除本机同一条,待办的
+ 删除本身是一条标记、随值走,待办的墓碑只表示它已超出随行范围(关闭超过 30 天或排在 500 条之外),云端清掉、本机保留)。
+ 旧工作台判断转成的待办到新电脑后按同一 ID 重新挂回那条判断,不另生成一条。例行任务的计时从
+ 恢复时开始,不补跑错过的;带有原电脑检查命令的、一次性触发时间已过的,到新电脑先关闭。工作台里原电脑上的项目目录
+ 显示为「在「X」上」,不作为这台电脑的授权范围;回到原电脑时恢复为本机目录。待办里尚在投递的动作不带走。
+- 伙伴列表与未读计数:伙伴已知在别的电脑上运行时,本机副本立即不再列出(不必等降级发布),每个伙伴只出现一行;
+ 已接入云端的 Cindy 不再进入按电脑列出的旧 Cindy 合并入口,只有未接入云端的才保留它。
+- 合并多台电脑上的 Cindy(2026-10-16 裁决第 2 条):只认由 Cindy 预设创建的伙伴(资料快照里的 `templateId`、默认身份
+ 或 `cindy-default`),从不按名字。Cindy 的设置里出现「合并重复的 Cindy」,用户选一个作为名字、性格与设置的基准;
+ 由它的主力电脑执行(在别的电脑上发起时经 `maker:companion-cloud:merge` 请它执行,连不上或版本较旧时提示):
+ 先请每个被合并的 Cindy 的主力电脑把还没上传的对话与资料传完(本机直接做;别的电脑经 `maker:companion-cloud:flush`;
+ 还在回复时提示等回复完再合并,有 Cindy 已暂停(保留的或被合并的)时提示先恢复,同步失败则不合并;那台电脑连不上或版本较旧时按云端已有的合并,没传上来的留在那台电脑上)。
+ 然后其他 Cindy 的记忆、自有技能、待办、例行任务、工作台与全部对话并进来,对话保留原时间,附件重新上传;
+ 同名但内容不同的记忆和技能另存为「名字-来源电脑」(已被占用再加 -2、-3…),不覆盖;待办与例行任务在保留的 Cindy 里使用
+ 按来源派生的新稳定 ID(同 key 的待办另起稳定 key),不会互相覆盖。全部并完、保留的 Cindy 本机任务也导入完成后,再请各来源同步一次:期间
+ 开始回复或有了新内容(云端的资料或对话比读取时新)时这次不停用、提示稍后再合并;确认没有新内容后其余 Cindy 才在云端停用,
+ 它们的电脑把本机副本转为降级,资料仍在云端与原电脑上;在此之前失败,来源都保持可用,再合并一次即可,不会重复。
+ 服务器不需要改动。
+- Agent 与用户同权:伙伴工具 `get_teammate_home` / `move_teammate_home` 查看与更换任一伙伴的主力电脑(与界面同一条路径),
+ 更换交给当前任务的权限档。
+- 头像:见 §3.2。
+- 未覆盖、留作后续:手机与非主力电脑离线编辑资料;IM 渠道按伙伴绑定;离线时在其他端直接发送并排队;
+ 伙伴回复里引用的文件上云;手机端合并 Cindy;合并时让用户逐条选择同名内容保留哪份(目前两份都保留)。
## 7. 实现位置
@@ -175,5 +243,6 @@
`/me` 的设备标识与能力开关)。
- Desktop:`apps/desktop/src/main/companion-cloud/`(登记主力电脑、资料上传、对话导入、接管、降级、
删除时停用);渲染层 `features/bots/` 的 `companionCloudStore.ts`(`maker:companion-cloud:*` 状态与变化推送)、
- `CloudCompanionOfflineView.tsx`(离线横幅与云端对话)、`BotHomeComputerSetting.tsx`(设置里的「主力电脑」行)。
+ `CloudCompanionOfflineView.tsx`(离线横幅与云端对话)、`BotHomeComputerSetting.tsx`(设置里的「主力电脑」行与
+ 聊天头部的「在 X 上运行」,任何电脑上都可更换)。
- Mobile:伙伴离线横幅、云端对话只读视图与换电脑选择。
diff --git a/packages/device-link/src/__tests__/companionCloud.test.ts b/packages/device-link/src/__tests__/companionCloud.test.ts
new file mode 100644
index 0000000000..255d8c191a
--- /dev/null
+++ b/packages/device-link/src/__tests__/companionCloud.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import {
+ INVOKE_TIMEOUT_OVERRIDES_MS,
+ REMOTE_INVOKE_ALLOWLIST,
+} from "../allowlist.js";
+import {
+ COMPANION_CLOUD_CAPS_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+ companionCloudCapsVersion,
+ isCompanionCloudCaps,
+ parseCompanionCloudRemoteActionResult,
+ parseCompanionCloudRemoteTargets,
+} from "../companionCloud.js";
+
+describe("cloud companion device-link contract", () => {
+ it("lets another computer ask the home, with room for the hand-over to sync first", () => {
+ for (const channel of [
+ COMPANION_CLOUD_CAPS_CHANNEL,
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ ])
+ expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);
+ expect(
+ INVOKE_TIMEOUT_OVERRIDES_MS[COMPANION_CLOUD_HAND_OVER_CHANNEL],
+ ).toBeGreaterThanOrEqual(120_000);
+ });
+
+ it("reads the declared version; version 1 still receives companions", () => {
+ expect(companionCloudCapsVersion({ companionCloud: 2 })).toBe(2);
+ expect(companionCloudCapsVersion({ companionCloud: "2" })).toBe(0);
+ expect(companionCloudCapsVersion(null)).toBe(0);
+ expect(isCompanionCloudCaps({ companionCloud: 1 })).toBe(true);
+ expect(isCompanionCloudCaps({})).toBe(false);
+ });
+
+ it("drops malformed remote answers", () => {
+ expect(
+ parseCompanionCloudRemoteTargets([
+ { deviceId: "a", name: "A", online: true },
+ { deviceId: "" },
+ "x",
+ { deviceId: "b" },
+ ]),
+ ).toEqual([
+ { deviceId: "a", name: "A", online: true },
+ { deviceId: "b", name: "", online: false },
+ ]);
+ expect(parseCompanionCloudRemoteTargets({})).toEqual([]);
+ expect(
+ parseCompanionCloudRemoteActionResult({ ok: true, extra: 1 }),
+ ).toEqual({ ok: true });
+ expect(
+ parseCompanionCloudRemoteActionResult({
+ ok: false,
+ code: "HOME_CONFLICT",
+ homeDeviceId: null,
+ }),
+ ).toEqual({ ok: false, code: "HOME_CONFLICT", homeDeviceId: null });
+ expect(
+ parseCompanionCloudRemoteActionResult({ ok: false, code: "not a code" }),
+ ).toEqual({ ok: false, code: "FAILED" });
+ expect(parseCompanionCloudRemoteActionResult(undefined)).toEqual({
+ ok: false,
+ code: "FAILED",
+ });
+ });
+});
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index af57c850df..987454a872 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -35,7 +35,15 @@ import {
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
} from './orcaRemoteWorker.js';
import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';
-import { COMPANION_CLOUD_CAPS_CHANNEL } from './companionCloud.js';
+import {
+ COMPANION_CLOUD_CAPS_CHANNEL,
+ COMPANION_CLOUD_FLUSH_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_TIMEOUT_MS,
+ COMPANION_CLOUD_MERGE_CHANNEL,
+ COMPANION_CLOUD_MERGE_TIMEOUT_MS,
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+} from './companionCloud.js';
import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';
import { REMOTE_DESKTOP_INVOKE_MS } from './remoteDesktopIce.js';
import {
@@ -440,6 +448,17 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// 云端伙伴:交出伙伴前探测目标电脑是否支持接手(只读常量,无 sender 依赖、无本机 UI 副作用)。
// 老版本无 handler → CHANNEL_NOT_ALLOWED,交出方拒绝该目标。
COMPANION_CLOUD_CAPS_CHANNEL,
+ // 云端伙伴:在任一台电脑上更换伙伴的主力电脑。只读读取主力电脑视角的可接手电脑,以及请主力电脑
+ // 交出伙伴(写)。准入同本机伙伴设置的「主力电脑」一行:同账号 + 主力电脑开启远程控制时控制端本就
+ // 能远程改这个伙伴;交出走被控端同一业务流程(同步、忙碌检查、比较后改主力电脑),handler 不依赖
+ // sender、无本机 UI 副作用。仅同账号远控,不进 sharedTask 访客白名单。老版本无 handler →
+ // CHANNEL_NOT_ALLOWED;控制端按 caps 版本隐藏入口。
+ COMPANION_CLOUD_TARGETS_CHANNEL,
+ COMPANION_CLOUD_HAND_OVER_CHANNEL,
+ // 云端伙伴:请保留的那个 Cindy 所在电脑合并其他 Cindy(写;同账号远控,准入同上,业务 handler 只在
+ // 本机运行保留的那个 Cindy 时执行)。合并前请各来源 Cindy 的主力电脑先同步(写,只上传、不改主力电脑)。
+ COMPANION_CLOUD_MERGE_CHANNEL,
+ COMPANION_CLOUD_FLUSH_CHANNEL,
// —— Rewind / Fork / Title / Context ——
'maker:rewind:preview',
'maker:rewind:commit',
@@ -836,6 +855,10 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {
[DL_SESSION_HANDOFF_CHANNEL]: 65_000,
// 运行设备准备工作目录并启动 Worker 的 Agent,可能超过默认 30s。
[ORCA_REMOTE_WORKER_OPEN_CHANNEL]: ORCA_REMOTE_WORKER_OPEN_TIMEOUT_MS,
+ // 交出伙伴先把积压对话与全部资料传到服务器,再改主力电脑。
+ [COMPANION_CLOUD_HAND_OVER_CHANNEL]: COMPANION_CLOUD_HAND_OVER_TIMEOUT_MS,
+ [COMPANION_CLOUD_MERGE_CHANNEL]: COMPANION_CLOUD_MERGE_TIMEOUT_MS,
+ [COMPANION_CLOUD_FLUSH_CHANNEL]: COMPANION_CLOUD_HAND_OVER_TIMEOUT_MS,
// listing tier 轻量 DB 读:毫秒级查询,12s 仍等不到只能是链路问题,快速失败喂给熔断器。
// 12s 同时覆盖被控端冷启动 DB 迁移的常见时长(那类失败是快速返回的 DbClient not ready,
// 不吃满超时),不会误伤首拉重试。
diff --git a/packages/device-link/src/companionCloud.ts b/packages/device-link/src/companionCloud.ts
index 07c24ca067..9329872207 100644
--- a/packages/device-link/src/companionCloud.ts
+++ b/packages/device-link/src/companionCloud.ts
@@ -1,17 +1,90 @@
/**
* 云端伙伴(docs/product-rules/cloud-companions.md):把伙伴交给另一台电脑前,先确认那台电脑的
- * Cindy 支持接手云端伙伴。只读能力探测,返回 `{ companionCloud: 1 }`;老版本没有该 channel →
+ * Cindy 支持接手云端伙伴。只读能力探测,返回 `{ companionCloud: <版本> }`;老版本没有该 channel →
* CHANNEL_NOT_ALLOWED,交出方据此拒绝目标(不把伙伴交给接不住它的电脑)。
+ *
+ * 版本:1 = 能接手伙伴;2 = 另外接受其他电脑发来的「换主力电脑」、合并 Cindy 与合并前同步的请求(下面几个 channel)。
*/
export const COMPANION_CLOUD_CAPS_CHANNEL = 'maker:companion-cloud:caps';
-export const COMPANION_CLOUD_VERSION = 1;
+export const COMPANION_CLOUD_VERSION = 2;
+/** 能接手伙伴的最低版本。 */
+export const COMPANION_CLOUD_RECEIVE_VERSION = 1;
+/** 主力电脑接受其他电脑发起换主力电脑的最低版本。 */
+export const COMPANION_CLOUD_REMOTE_HAND_OVER_VERSION = 2;
+
+/**
+ * 在主力电脑上读取伙伴可以换到的电脑(只读,主力电脑视角:发起方自己也在其中)。
+ * 入参无;返回 `CompanionCloudRemoteTarget[]`。
+ */
+export const COMPANION_CLOUD_TARGETS_CHANNEL = 'maker:companion-cloud:targets';
+/**
+ * 请主力电脑把伙伴交给另一台电脑(写)。入参 `[botId, targetDeviceId, options?]`;在主力电脑上走与本机
+ * 「主力电脑」设置完全相同的交出流程(先同步对话与资料、确认没有进行中的一轮),返回
+ * `CompanionCloudRemoteActionResult`。`options.whenBusy`:伙伴还在回复时 `wait` 等这一轮结束(最多约 4 分钟)、
+ * `stop` 先停止再交出;缺省按忙碌拒绝(`BUSY`)。老版本主力电脑忽略第三个参数,按忙碌拒绝。
+ */
+export const COMPANION_CLOUD_HAND_OVER_CHANNEL = 'maker:companion-cloud:hand-over';
+/** 交出可能先等这一轮结束(约 4 分钟),再把积压对话与全部资料传完;给足执行预算与回程余量。 */
+export const COMPANION_CLOUD_HAND_OVER_TIMEOUT_MS = 7 * 60_000;
+
+/**
+ * 请保留的那个 Cindy 所在的主力电脑把其他 Cindy 合并进来(写)。入参 `[keepBotId, fromBotIds[]]`;
+ * 只在本机运行保留的那个 Cindy 时执行(否则 `HOME_CONFLICT`),返回 `{ ok, merged, messages, memories, skills, renamed }`
+ * 或 `{ ok:false, code }`。合并要搬对话与附件,给足预算。
+ */
+export const COMPANION_CLOUD_MERGE_CHANNEL = 'maker:companion-cloud:merge';
+export const COMPANION_CLOUD_MERGE_TIMEOUT_MS = 10 * 60_000;
+
+/**
+ * 合并前请某个 Cindy 的主力电脑把它的对话积压与全部资料传到服务器(写,不改主力电脑)。入参 `[botId]`;
+ * 只在本机是它的主力电脑时执行(否则 `HOME_CONFLICT`),伙伴还在回复时 `BUSY`,返回
+ * `CompanionCloudRemoteActionResult`。与交出同一套同步,给同样的预算。
+ */
+export const COMPANION_CLOUD_FLUSH_CHANNEL = 'maker:companion-cloud:flush';
export interface CompanionCloudCaps {
companionCloud: number;
}
+export interface CompanionCloudRemoteTarget {
+ deviceId: string;
+ name: string;
+ online: boolean;
+}
+
+export type CompanionCloudRemoteActionResult =
+ | { ok: true }
+ | { ok: false; code: string; homeDeviceId?: string | null };
+
+/** Declared cloud-companion version, or 0 when the answer is not a caps record. */
+export function companionCloudCapsVersion(value: unknown): number {
+ if (!value || typeof value !== 'object') return 0;
+ const version = (value as { companionCloud?: unknown }).companionCloud;
+ return typeof version === 'number' && Number.isFinite(version) ? version : 0;
+}
+
/** True when the remote answer declares cloud-companion support. */
export function isCompanionCloudCaps(value: unknown): value is CompanionCloudCaps {
- return !!value && typeof value === 'object' && typeof (value as { companionCloud?: unknown }).companionCloud === 'number'
- && (value as { companionCloud: number }).companionCloud >= COMPANION_CLOUD_VERSION;
+ return companionCloudCapsVersion(value) >= COMPANION_CLOUD_RECEIVE_VERSION;
+}
+
+/** Remote targets answer, dropping anything malformed. */
+export function parseCompanionCloudRemoteTargets(value: unknown): CompanionCloudRemoteTarget[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((item) => {
+ if (!item || typeof item !== 'object') return [];
+ const { deviceId, name, online } = item as Record<string, unknown>;
+ if (typeof deviceId !== 'string' || !deviceId || deviceId.length > 200) return [];
+ return [{ deviceId, name: typeof name === 'string' ? name.slice(0, 200) : '', online: online === true }];
+ });
+}
+
+/** Remote hand-over answer; anything malformed counts as a failure. */
+export function parseCompanionCloudRemoteActionResult(value: unknown): CompanionCloudRemoteActionResult {
+ if (!value || typeof value !== 'object') return { ok: false, code: 'FAILED' };
+ const record = value as Record<string, unknown>;
+ if (record.ok === true) return { ok: true };
+ const code = typeof record.code === 'string' && /^[A-Z_]{1,40}$/.test(record.code) ? record.code : 'FAILED';
+ const homeDeviceId = typeof record.homeDeviceId === 'string' ? record.homeDeviceId : record.homeDeviceId === null ? null : undefined;
+ return { ok: false, code, ...(homeDeviceId !== undefined ? { homeDeviceId } : {}) };
}
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index f121561e7c..20e73cbfbd 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -89,6 +89,7 @@ import {
registerBotWorkbenchTools,
type BotWorkbenchCallbacks,
} from './xdt-helper/bot_workbench.js';
+import { registerTeammateHomeTools, type TeammateHomeCallbacks } from './xdt-helper/teammate_home.js';
import {
registerBotCapabilityTools,
withCindyGatedBotToolDescriptions,
@@ -151,7 +152,7 @@ export const HELPER_CATEGORY_DESCRIPTIONS: Record<(typeof CATEGORY_ENUM)[number]
handoff: '给已有任务发消息,或新建任务。发给已有任务可跨电脑(deviceId::sessionId);新建只在本机。',
skills: 'Skill 的搜索、发布与学习。本机与 SkillHub。',
app_update: `检查与安装本机的 ${BRAND_NAME} 更新。本机。`,
- bots: '伙伴:资料、能力、工作台、待办、后台任务与伙伴间消息。伙伴间消息可跨电脑(list_agents / send_to_agent);其余本机。',
+ bots: '伙伴:资料、能力、工作台、待办、后台任务、伙伴间消息与主力电脑。伙伴间消息(list_agents / send_to_agent)与主力电脑(get_teammate_home / move_teammate_home)可跨电脑;其余本机。',
};
interface SessionTaskCallbacks {
@@ -818,6 +819,8 @@ export interface XdtHelperMcpDeps {
*/
botWorkbench?: BotWorkbenchCallbacks;
botCapabilities?: BotCapabilityCallbacks;
+ /** Which computer runs a teammate, and moving it to another (cloud companions). */
+ teammateHome?: TeammateHomeCallbacks;
/**
* 官方反馈 issue 提交回调(弹确认卡片 → 用户确认 → POST server)。host 注入后,
* feedback 类工具 submit_github_issue 会被注册; 不注入则不出现在 list_tools 里。
@@ -1028,6 +1031,12 @@ export function createXdtHelperMcpServer(
});
}
+ if (deps.teammateHome) {
+ registerTeammateHomeTools(registry, {
+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ callbacks: deps.teammateHome,
+ });
+ }
if (deps.botCapabilities) {
registerBotCapabilityTools(registry, {
getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
index c50383de8c..af99f47c8f 100644
--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
@@ -58,7 +58,7 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [
'【原则】用户本人能做的操作(含跨电脑),Agent 也应有对应工具;是否执行由权限档与自动审核决定。数据保存在各自的电脑上:下结论「没有 / 没人在跟」之前,先确认查的是不是只有本机。',
'【任务】cindy_helper history 类:list_sessions / search_chat_history(device=local|all|<deviceId>)、get_chat_history(deviceId::sessionId)、list_history_devices 可跨电脑;list_workdirs、list_session_queue 仅本机。handoff 类 send_to_session:发给既有任务可跨电脑(deviceId::sessionId),新建任务仅本机。control 类 archive_sessions / unarchive_sessions 可跨电脑(deviceId::sessionId,单次限定一台电脑);改名、移动、标签、排队消息、插话、停止、运行设置、list_projects 与项目增删改仅本机。',
'【定时任务】cindy_scheduler:schedule_list / get / list_runs(device=local|all|<deviceId>,list 可用 query 做文本筛选)与 schedule_update / pause / resume / delete / run_now(device=<deviceId>)可跨电脑;schedule_create、schedule_set_pre_run_hook、当前运行的通知设置仅本机。',
- '【伙伴】cindy_helper bots 类(仅伙伴任务可见):list_agents / send_to_agent 可跨电脑(deviceId::botId);资料、能力、工作台、待办、后台任务仅本机。',
+ '【伙伴】cindy_helper bots 类(仅伙伴任务可见):list_agents / send_to_agent 可跨电脑(deviceId::botId);get_teammate_home / move_teammate_home 查看与更换任一伙伴的主力电脑(跨电脑,更换按权限档);资料、能力、工作台、待办、后台任务仅本机。',
'【跨电脑的前提】对方电脑在线、同一账号、已开启远程控制。离线、未开启、版本不支持或超时会按电脑写明原因,结果里的 partial=true 表示有电脑没查到。',
'【尚无工具】在另一台电脑上新建任务或定时任务、管理另一台电脑上的任务(改名 / 停止 / 队列)与项目;这些用户可在远程控制里手动完成。',
].join(' '),
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index 1c78632135..6ed0e3d5ee 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -182,6 +182,11 @@ export {
registerCreateTeammateTool,
type CreateTeammateCallbacks,
} from './create_teammate.js';
+export {
+ registerTeammateHomeTools,
+ type TeammateHomeCallbacks,
+ type TeammateHomeComputerWire,
+} from './teammate_home.js';
export {
registerBotCapabilityTools,
buildFindBotCapabilitiesDescription,
diff --git a/packages/lizi-mcps/src/xdt-helper/teammate_home.ts b/packages/lizi-mcps/src/xdt-helper/teammate_home.ts
new file mode 100644
index 0000000000..580a89e33d
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/teammate_home.ts
@@ -0,0 +1,66 @@
+import { z } from 'zod';
+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
+import type { ControlResult, LiziMcpSessionContext } from '../types.js';
+import { errorPayload, okPayload } from './_payload.js';
+
+/**
+ * 伙伴的主力电脑(docs/product-rules/cloud-companions.md §3.1):伙伴属于账号,主力电脑只决定它在哪台
+ * 电脑上运行。用户在任何一台电脑上能看和换的,Agent 也能(agent-user-parity.md)。换电脑会把伙伴的
+ * 运行交给另一台电脑,按当前任务的权限档处理(Full Access 不拦,Auto 审阅,Ask 确认)。
+ */
+export interface TeammateHomeComputerWire {
+ deviceId: string;
+ name: string;
+ /** The computer this tool runs on. */
+ isSelf: boolean;
+}
+
+export interface TeammateHomeCallbacks {
+ get(params: { callerSessionId: string; teammateId: string }): Promise<ControlResult<{
+ teammateId: string;
+ home: TeammateHomeComputerWire | null;
+ /** local: this computer runs it; remote: its home is asked; takeOver: only this computer can continue it; unavailable: see reason. */
+ mode: 'local' | 'remote' | 'takeOver' | 'unavailable';
+ reason?: string;
+ choices: TeammateHomeComputerWire[];
+ }, string>>;
+ move(params: { callerSessionId: string; teammateId: string; targetDeviceId: string; whenBusy?: 'wait' | 'stop' }): Promise<ControlResult<{
+ teammateId: string;
+ homeDeviceId: string;
+ }, string>>;
+}
+
+export function registerTeammateHomeTools(
+ registry: XdtHelperToolRegistry,
+ deps: { getSessionContext: () => LiziMcpSessionContext; callbacks: TeammateHomeCallbacks },
+): void {
+ registry.register({
+ name: 'get_teammate_home',
+ category: 'bots',
+ description: 'Read which computer runs a teammate (its main computer) and which computers it can move to. A teammate belongs to the account: its chat and profile are the same on every computer; the main computer only decides where its agent runs. Use the exact teammate id from list_agents (without a device prefix). Cross-computer: answers for teammates running on any of the user\'s computers.',
+ inputShape: { teammate_id: z.string().min(1).max(200) },
+ handler: async ({ teammate_id }: { teammate_id: string }) => {
+ const callerSessionId = deps.getSessionContext().sessionId;
+ if (!callerSessionId) return errorPayload('NOT_A_BOT_SESSION', 'An active task is required');
+ const result = await deps.callbacks.get({ callerSessionId, teammateId: teammate_id.trim() });
+ return result.ok ? okPayload(result) : errorPayload(result.errorCode, result.message);
+ },
+ });
+ registry.register({
+ name: 'move_teammate_home',
+ category: 'bots',
+ description: 'Move a teammate to another of the user\'s computers when the user asks (change its main computer). Pick target_device_id from get_teammate_home choices. Its chat history, profile, memories, skills, todos and routines move with it; files and logins stay on their computers. If it is still replying the move fails with BUSY unless when_busy is "wait" (finish the reply first, up to about 4 minutes) or "stop" (stop the reply). A missing answer may still have moved it: read get_teammate_home before retrying. Cross-computer write: follows the task\'s permission mode.',
+ inputShape: {
+ teammate_id: z.string().min(1).max(200),
+ target_device_id: z.string().min(1).max(200),
+ when_busy: z.enum(['fail', 'wait', 'stop']).optional(),
+ },
+ handler: async ({ teammate_id, target_device_id, when_busy }: { teammate_id: string; target_device_id: string; when_busy?: 'fail' | 'wait' | 'stop' }) => {
+ const callerSessionId = deps.getSessionContext().sessionId;
+ if (!callerSessionId) return errorPayload('NOT_A_BOT_SESSION', 'An active task is required');
+ const result = await deps.callbacks.move({ callerSessionId, teammateId: teammate_id.trim(), targetDeviceId: target_device_id.trim(),
+ ...(when_busy && when_busy !== 'fail' ? { whenBusy: when_busy } : {}) });
+ return result.ok ? okPayload({ action: 'moved', ...result }) : errorPayload(result.errorCode, result.message);
+ },
+ });
+}