Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(teammates): use gallery avatars and provision on remote entry
zqchris591145ffc7fd
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 68e09ae6ea..f2e1b7664d 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -806,6 +806,7 @@ function extraResourcesForTarget(targetPlatform: string): string[] {'resources/cindy-source.json',// Input bytes for upgrading retired preset avatars to ordinary managed images.'resources/legacy-teammate-avatars',+ 'resources/teammate-portrait-gallery.png','resources/tools','drizzle','resources/cc-manager',diff --git a/apps/desktop/src/renderer/assets/bot-presets/portrait-gallery.png b/apps/desktop/resources/teammate-portrait-gallery.pngsimilarity index 100%rename from apps/desktop/src/renderer/assets/bot-presets/portrait-gallery.pngrename to apps/desktop/resources/teammate-portrait-gallery.pngdiff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botAvatarSelection.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botAvatarSelection.test.tsindex 92fca24a05..fcc3cfec91 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botAvatarSelection.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botAvatarSelection.test.ts@@ -1,8 +1,17 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import path from 'node:path';+import { createHash } from 'node:crypto';++const state = vi.hoisted(() => ({ packaged: false }));+vi.mock('electron', () => ({ app: {+ getAppPath: () => path.resolve(__dirname, '../../../../..'),+ get isPackaged() { return state.packaged; },+} }));import {BOT_AVATAR_MAX_BYTES,decodeBotAvatarImage,+ readDefaultTeammatePortrait,validateBotAvatarBuffer,} from '../botAvatarSelection';@@ -48,3 +57,34 @@ describe('Bot avatar selection', () => {}});});++describe('bundled teammate portrait fallback', () => {+ it('provides sixteen distinct real portraits and wraps without reviving a retired role', async () => {+ const sharp = (await import('sharp')).default;+ const hashes = new Set<string>();+ for (let index = 0; index < 16; index++) {+ const image = await readDefaultTeammatePortrait(index);+ expect(image.mimeType).toBe('image/png');+ expect(await sharp(image.buffer).metadata()).toMatchObject({ width: 256, height: 256 });+ hashes.add(createHash('sha256').update(image.buffer).digest('hex'));+ }+ expect(hashes.size).toBe(16);+ expect(await readDefaultTeammatePortrait(16)).toEqual(await readDefaultTeammatePortrait(0));+ });++ it('uses the packaged gallery with exactly the same pixels as development', async () => {+ const expected = await readDefaultTeammatePortrait(3);+ const original = Object.getOwnPropertyDescriptor(process, 'resourcesPath');+ Object.defineProperty(process, 'resourcesPath', {+ configurable: true, value: path.resolve(__dirname, '../../../../../resources'),+ });+ state.packaged = true;+ try {+ expect(await readDefaultTeammatePortrait(3)).toEqual(expected);+ } finally {+ state.packaged = false;+ if (original) Object.defineProperty(process, 'resourcesPath', original);+ else Reflect.deleteProperty(process, 'resourcesPath');+ }+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 41993f61d7..a013097baf 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3,7 +3,7 @@ import { setModelVisibilityMirror } from '../../../maker-host/model-visibility-mimport Database from 'better-sqlite3';import type { ProviderView } from '@cindy/model-providers';import { createHash } from 'node:crypto';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { drizzle } from 'drizzle-orm/better-sqlite3';@@ -58,7 +58,7 @@ const h = await vi.hoisted(async () => {h.worktrees = [];}),isSessionAlive: vi.fn(() => false),- remove: vi.fn(async () => undefined),+ remove: vi.fn(async (_path: import('node:fs').PathLike, _options?: import('node:fs').RmOptions) => undefined),ensureGit: vi.fn(async () => undefined),closeSession: vi.fn(async () => undefined),getSession: vi.fn(() => null as {@@ -78,7 +78,12 @@ const h = await vi.hoisted(async () => {});});-vi.mock('node:fs/promises', () => ({ default: { rm: h.remove } }));+vi.mock('node:fs/promises', async importOriginal => {+ const actual = await importOriginal<typeof import('node:fs/promises')>();+ return { ...actual, default: { ...actual, rm: h.remove } };+});+// Legacy byte migration has its own real-storage suite.+vi.mock('../legacyTeammateAvatar.js', () => ({ migrateLegacyTeammateAvatar: async () => false }));vi.mock('../../../maker-ipc/botDefaultProvisioning.js', () => ({provisionDefaultBot: vi.fn(), markDefaultBotOffered: vi.fn(),withDefaultBotProvisioningLock: async (_root: string, assertOwner: () => void, action: () => Promise<unknown>) => {@@ -89,6 +94,7 @@ vi.mock('../../../maker-ipc/botDefaultProvisioning.js', () => ({vi.mock('electron', () => ({app: {getPath: vi.fn(() => h.userDataDir),+ getAppPath: () => resolve(__dirname, '../../../../..'),},ipcMain: {handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {@@ -208,6 +214,8 @@ import { readRemoteBotSessionAccess } from '../botRemoteSessionAccess';import { assertRemoteBotInvocationAllowed, projectRemoteSessionResult, projectRemoteBotPush } from '../../../device-link/remoteBotSessionBoundary';import { listBotSkillsForSession, saveBotSkillForSession } from '../../../maker-ipc/botSkillService';import { resolveBotCanonicalSession } from '../../../maker-ipc/botCanonicalSessionRegistry';+import { provisionDefaultBot } from '../../../maker-ipc/botDefaultProvisioning';+import { resolveSafe } from '../../../cindy-media/blobStore';function testSha256(value: string): string {return createHash('sha256').update(value).digest('hex');@@ -406,6 +414,7 @@ function createDb(filename = ':memory:'): void {updated_at INTEGER NOT NULL);`);+ sqlite.exec(readFileSync(resolve(__dirname, '../../../../../drizzle/0070_woozy_harpoon.sql'), 'utf8'));h.sqlite = sqlite;const rawDb = drizzle(sqlite, {schema: {@@ -450,6 +459,11 @@ beforeEach(async () => {resetCustomMcpRegistry();registerCustomMcpArrays(h.mcpProviders);vi.clearAllMocks();+ vi.mocked(provisionDefaultBot).mockReset();+ h.remove.mockImplementation(async (...args) => {+ const fs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');+ await fs.rm(...args);+ });h.handlers.clear();h.nextSession = 0;h.providers = [{@@ -777,6 +791,59 @@ describe('Bot canonical Session lifecycle', () => {).toBeUndefined();});+ it('creates a real gallery portrait when the shared tool entry receives only a name', async () => {+ const { createBotProfile } = await import('../bots');+ const created = await createBotProfile({ name: 'Name only' });+ expect(created.avatar).toMatch(/^cindy-media:\/\/blobs\/[a-f0-9]{64}\.png$/);+ const sharp = (await import('sharp')).default;+ const stored = readFileSync(resolveSafe(created.avatar).absPath);+ expect(await sharp(stored).metadata()).toMatchObject({ width: 256, height: 256 });+ expect(h.sqlite!.prepare('SELECT hash, ref_kind FROM media_refs WHERE ref_id = ?').get(created.id))+ .toEqual({ hash: createHash('sha256').update(stored).digest('hex'), ref_kind: 'bot-avatar' });+ const next = await createBotProfile({ name: 'Another name' });+ expect(next.avatar).not.toBe(created.avatar);+ expect((await invoke('local-db:bots:get', created.id)).avatar).toBe(created.avatar);+ });++ it.each(['legacy IPC', 'resource registry'])('provides Cindy on first Mobile entry via %s and shares the receipt after deletion', async entry => {+ const real = await vi.importActual<typeof import('../../../maker-ipc/botDefaultProvisioning')>(+ '../../../maker-ipc/botDefaultProvisioning');+ vi.mocked(provisionDefaultBot).mockImplementation(real.provisionDefaultBot);+ h.sqlite!.prepare('DELETE FROM bot_profiles').run();+ // A fresh owner has no receipt, roster or history. No desktop list has run.+ h.ownerScopeKey = `mobile-first-${entry}:1`;+ const legacyList = () => runDeviceLinkInvokeContext(+ { controllerDeviceId: 'mobile-first', channel: 'local-db:bots:list' },+ () => invoke('local-db:bots:list', undefined),+ );+ const { registerBotRemoteResourceProvider } = await import('../botRemoteResourceProvider');+ const { remoteResourceRegistry } = await import('../../../device-link/remoteResourceRegistry');+ registerBotRemoteResourceProvider();+ const mobileList = entry === 'legacy IPC' ? legacyList : async () => {+ const result = await remoteResourceRegistry.list({ controllerDeviceId: 'mobile-first' }, {+ client: { protocolVersion: 1, primitives: ['markdown'] }, collectionId: 'teammates',+ });+ return result.items.map(item => ({ id: item.ref.id, name: item.display.title }));+ };+ const first = await mobileList();+ expect(first).toEqual([expect.objectContaining({ id: 'cindy-default', name: 'Cindy' })]);+ expect(first[0]).not.toHaveProperty('identitySource');+ await invoke('local-db:bots:list', undefined);+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS n FROM bot_profiles').get()).toEqual({ n: 1 });+ // Removing even all history cannot undo the account's one-time receipt.+ h.sqlite!.prepare('DELETE FROM bot_profiles').run();+ await expect(mobileList()).resolves.toEqual([]);+ await expect(invoke('local-db:bots:list', undefined)).resolves.toEqual([]);+ });++ it('rejects a remote list when its owner changes during provisioning', async () => {+ vi.mocked(provisionDefaultBot).mockImplementationOnce(async () => { h.ownerScopeKey = 'other:2'; });+ await expect(runDeviceLinkInvokeContext(+ { controllerDeviceId: 'mobile-first', channel: 'local-db:bots:list' },+ () => invoke('local-db:bots:list', undefined),+ )).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });+it('allows device-link to read Bot projections without weakening local renderer trust', async () => {const list = h.handlers.get('local-db:bots:list');const get = h.handlers.get('local-db:bots:get');diff --git a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.tsindex e3a077275b..c59670df59 100644--- a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts+++ b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts@@ -1,3 +1,5 @@+import path from 'node:path';+import { app } from 'electron';import { writeBlob } from '../../cindy-media/blobStore.js';import { recordBlob, type LedgerDb } from '../../cindy-media/ledger.js';import { sniffImageMime } from '../../lightboxMediaActions.js';@@ -48,3 +50,23 @@ export async function storeTeammateAvatarImage(assertCurrent();return written;}++/** The same bundled gallery used by the picker; no model or renderer is needed. */+export async function readDefaultTeammatePortrait(index: number): Promise<{ buffer: Buffer; mimeType: string }> {+ const { default: sharp } = await import('sharp');+ const root = app.isPackaged ? process.resourcesPath : path.join(app.getAppPath(), 'resources');+ const image = sharp(path.join(root, 'teammate-portrait-gallery.png'));+ const { width, height } = await image.metadata();+ if (!width || !height || width < 4 || height < 4) throw new Error('Invalid teammate portrait gallery');+ const cell = Math.abs(Math.trunc(index)) % 16;+ const column = cell % 4;+ const row = Math.floor(cell / 4);+ const left = Math.floor(column * width / 4);+ const top = Math.floor(row * height / 4);+ const buffer = await image.extract({+ left, top,+ width: Math.floor((column + 1) * width / 4) - left,+ height: Math.floor((row + 1) * height / 4) - top,+ }).resize(256, 256).png().toBuffer();+ return { buffer, mimeType: validateBotAvatarBuffer(buffer) };+}diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 78bccb18ab..530345401e 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -76,7 +76,7 @@ import {} from '../../../shared/botAvatarValue.js';import { migrateLegacyTeammateAvatar } from './legacyTeammateAvatar.js';import { MAKER_PUSH } from '../../maker-ipc/channels.js';-import { decodeBotAvatarImage, validateBotAvatarBuffer, storeTeammateAvatarImage } from './botAvatarSelection.js';+import { decodeBotAvatarImage, validateBotAvatarBuffer, storeTeammateAvatarImage, readDefaultTeammatePortrait } from './botAvatarSelection.js';import {inferBotTemplatePresetId,isBotTemplatePresetId,@@ -762,9 +762,34 @@ async function readBotRemoteResourceSource(};}+/** Desktop, device-link and resource discovery share the same owner-bound receipt. */+async function provisionDefaultBotForList(+ client: ReturnType<typeof getDbClient>,+ owner: ReturnType<typeof captureBotOperationOwner>,+): Promise<void> {+ try {+ await provisionDefaultBot({+ ownerRoot: owner.userDataDir, assertOwner: owner.assertCurrent,+ hasBotHistory: async () => {+ const profiles = await client.drizzle.select({ id: botProfiles.id }).from(botProfiles).limit(1);+ if (profiles.length) return true;+ const history = await client.drizzle.select({ id: sessions.id }).from(sessions).where(eq(sessions.source, 'bot')).limit(1);+ return history.length > 0;+ },+ create: () => createBotProfile({ id: 'cindy-default', name: 'Cindy', templateId: 'cindy',+ avatar: BOT_TEMPLATE_PRESET_AVATARS.cindy, identitySource: CINDY_DEFAULT_IDENTITY,+ prepareInvitation: true }),+ });+ } catch (error) {+ log.warn('initial companion deferred', { error: error instanceof Error ? error.name : typeof error });+ }+ owner.assertCurrent();+}+export async function listBotRemoteResourceSources(): Promise<BotRemoteResourceSource[]> {const owner = captureBotOperationOwner();const client = getDbClient();+ await provisionDefaultBotForList(client, owner);const profiles = await client.drizzle.select({ id: botProfiles.id }).from(botProfiles).where(isNull(botProfiles.hiddenAt)).orderBy(desc(botProfiles.updatedAt));owner.assertCurrent();@@ -888,8 +913,8 @@ export async function createBotProfile(raw: unknown) {if (!/^[a-z0-9][a-z0-9_-]*$/.test(id) || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/.test(id)) {throwIpcError('INVALID_PARAMS', 'Bot id must be a lowercase portable directory identifier');}- // Existing bundled artwork remains a valid fallback, independent of the retired role template.- const requestedAvatar = readBotAvatar(body.avatar) || 'cindy://avatar/preset/dash';+ // Retired sentinels are accepted only when explicitly supplied by an older client.+ const requestedAvatar = readBotAvatar(body.avatar);// Managed addresses must come from validated image bytes ingested below,// never from a renderer or model supplying a URL string alone.let avatar = portableBotAvatarOrFallback(requestedAvatar);@@ -968,8 +993,9 @@ export async function createBotProfile(raw: unknown) {if (existingIds.some((profile) => botProfileDir(creationOwnerBoundary.userDataDir, profile.id).toLowerCase() === newHome)) {throwIpcError('ALREADY_EXISTS', 'Bot home already belongs to another profile');}- if (avatarImage) {- const written = await storeTeammateAvatarImage(avatarImage, db, assertCreationOwnerStillCurrent);+ const selectedImage = avatarImage ?? (!requestedAvatar ? await readDefaultTeammatePortrait(existingIds.length) : null);+ if (selectedImage) {+ const written = await storeTeammateAvatarImage(selectedImage, db, assertCreationOwnerStillCurrent);avatar = written.url;botAvatarRef = { id: randomUUID(), hash: written.hash, createdAt: now };}@@ -1239,26 +1265,8 @@ export function registerBotIpc(): void {if (!remote) assertTrustedAppRendererEvent(event);const client = tryGetDbClient();if (!client) return [];- if (!remote) {- const owner = captureBotOperationOwner();- try {- await provisionDefaultBot({- ownerRoot: ownerScopedUserDataPath(), assertOwner: owner.assertCurrent,- hasBotHistory: async () => {- const profiles = await client.drizzle.select({ id: botProfiles.id }).from(botProfiles).limit(1);- if (profiles.length) return true;- const history = await client.drizzle.select({ id: sessions.id }).from(sessions).where(eq(sessions.source, 'bot')).limit(1);- return history.length > 0;- },- create: () => createBotProfile({ id: 'cindy-default', name: 'Cindy', templateId: 'cindy',- avatar: BOT_TEMPLATE_PRESET_AVATARS.cindy, identitySource: CINDY_DEFAULT_IDENTITY,- prepareInvitation: true }),- });- } catch (error) {- log.warn('initial companion deferred', { error: error instanceof Error ? error.name : typeof error });- }- owner.assertCurrent();- }+ const owner = captureBotOperationOwner();+ await provisionDefaultBotForList(client, owner);const db = client.drizzle;// Unread accounting is opt-in: the read position lives in the renderer, so// a caller that has none (device-link, first boot) simply gets zeros.diff --git a/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx b/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsxindex dc465c2ab3..9b26783a0e 100644--- a/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx+++ b/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx@@ -2,7 +2,7 @@ import * as Popover from '@radix-ui/react-popover';import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Camera, Check, ChevronDown } from 'lucide-react';-import gallery from '@/assets/bot-presets/portrait-gallery.png';+import gallery from '../../../../resources/teammate-portrait-gallery.png';import { Spinner } from '@/components/ui/spinner';import { BOT_AVATAR_MAX_BYTES } from '../../../shared/botAvatarValue';diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 52df57e6f0..32974110cd 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -303,10 +303,12 @@ Session 任务遵守同一套机制与呈现契约:新增共同能力须同时核对指南、工具注册、运行期挂载和实际服务;不得只改文案或给默认 Cindy 私装 Skill。验收必须包含新伙伴和存量伙伴的原聊天,确认模型实际收到新版基座并调用对应工具;不能以文件存在或新伙伴成功代替旧伙伴升级验收。-- 首次使用伙伴时自动提供 Cindy;进入伙伴直接打开她的消息流,不增加介绍页或头像首页。+- 首次使用伙伴时自动提供 Cindy(Desktop、device-link 和 Mobile 资源列表共用一次性供给);+ 进入伙伴直接打开她的消息流,不增加介绍页或头像首页。账号级的一次性记录保留在 Bot Home 之外,删除伙伴不会重新添加。升级时已有阵容和历史保持原样,不猜测缺少 Cindy 是否代表用户曾删除她。没有 Cindy 时,主入口直接显示创建表单,其他伙伴仍从侧栏打开。-- 创建只必填名字,头像可从图库选择或上传;创建后直接进入伙伴自身的对话。身份细节未提供时不编造,+- 创建只必填名字,头像可从图库选择或上传;工具等入口未提供头像时,同样从现有图库保存真实图片,+ 不回落已退役角色头像。创建后直接进入伙伴自身的对话。身份细节未提供时不编造,不先调用辅助模型生成资料,也不按固定数量创建 Skill。已有生成草稿和自有 Skill 继续兼容。- Dash / LiZi 等旧角色模板已移除,只有默认 Cindy 保留内置身份。已有伙伴按持久 Profile 运行;保留历史头像地址与模板标识的读取,未完成邀请使用已保存身份,不重建旧模板或补装角色 Skill。