Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(teammates): migrate retired avatars to custom media
zqchrisa2f886ba6657
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 4090e89fb7..68e09ae6ea 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -804,6 +804,8 @@ function extraResourcesForTarget(targetPlatform: string): string[] {const base = ['resources/icon.png','resources/cindy-source.json',+ // Input bytes for upgrading retired preset avatars to ordinary managed images.+ 'resources/legacy-teammate-avatars','resources/tools','drizzle','resources/cc-manager',diff --git a/apps/desktop/src/renderer/assets/bot-presets/dash.png b/apps/desktop/resources/legacy-teammate-avatars/dash.pngsimilarity index 100%rename from apps/desktop/src/renderer/assets/bot-presets/dash.pngrename to apps/desktop/resources/legacy-teammate-avatars/dash.pngdiff --git a/apps/desktop/src/renderer/assets/bot-presets/lizi.png b/apps/desktop/resources/legacy-teammate-avatars/lizi.pngsimilarity index 100%rename from apps/desktop/src/renderer/assets/bot-presets/lizi.pngrename to apps/desktop/resources/legacy-teammate-avatars/lizi.pngdiff --git a/apps/desktop/src/main/localDb/__tests__/botAvatarProfileTx.test.ts b/apps/desktop/src/main/localDb/__tests__/botAvatarProfileTx.test.tsindex 8f69b4747c..b89560b74c 100644--- a/apps/desktop/src/main/localDb/__tests__/botAvatarProfileTx.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/botAvatarProfileTx.test.ts@@ -17,6 +17,7 @@ describe('Bot avatar profile transaction', () => {id TEXT PRIMARY KEY,current_version INTEGER NOT NULL,updated_at INTEGER NOT NULL,+ display_name TEXT NOT NULL DEFAULT 'Teammate',avatar TEXT NOT NULL);CREATE TABLE media_blobs (hash TEXT PRIMARY KEY);@@ -28,7 +29,7 @@ describe('Bot avatar profile transaction', () => {origin_kind TEXT,created_at INTEGER NOT NULL);- INSERT INTO bot_profiles VALUES ('bot-1', 1, 1, '🤖');+ INSERT INTO bot_profiles (id, current_version, updated_at, avatar) VALUES ('bot-1', 1, 1, '🤖');INSERT INTO media_blobs VALUES ('${HASH_A}'), ('${HASH_B}');INSERT INTO media_refs VALUES ('old-ref', '${HASH_A}', 'bot-avatar', 'bot-1', 'user', 1);`);@@ -78,6 +79,14 @@ describe('Bot avatar profile transaction', () => {]);});+ it('does not overwrite a user avatar replaced without a profile version change', () => {+ update({ avatar: '🚀', clearBotAvatarRefs: true });+ expect(() => update({ expectedAvatar: '🤖', botAvatarRef: { id: 'migration-ref', hash: HASH_B, createdAt: 3 } }))+ .toThrow('Teammate avatar changed');+ expect(db.prepare('SELECT avatar, current_version FROM bot_profiles').get()).toEqual({ avatar: '🚀', current_version: 1 });+ expect(db.prepare('SELECT * FROM media_refs').all()).toEqual([]);+ });+it('clears the private image ref when the Bot returns to an emoji', () => {update({ avatar: '🚀', clearBotAvatarRefs: true });expect(db.prepare('SELECT avatar FROM bot_profiles WHERE id = ?').get('bot-1')).toEqual({@@ -87,7 +96,6 @@ describe('Bot avatar profile transaction', () => {});it('creates the profile and image reference atomically, rolling both back on reference failure', () => {db.exec(`- ALTER TABLE bot_profiles ADD COLUMN display_name TEXT;ALTER TABLE bot_profiles ADD COLUMN description TEXT;ALTER TABLE bot_profiles ADD COLUMN avatar_color TEXT;ALTER TABLE bot_profiles ADD COLUMN status TEXT;diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex e4f4e33321..9e2f8e914f 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -593,6 +593,10 @@ export interface BotsUpdateProfileArgs {capabilitiesJson: string;profileContentChanged: boolean;expectedCurrentVersion: number;+ /** Avatar-only edits do not advance the profile version; migrations also compare the address. */+ expectedAvatar?: string;+ /** Storage-only compatibility changes must not reorder the teammate list. */+ preserveUpdatedAt?: boolean;/** Inserted and made authoritative in the same tx as the avatar address. */botAvatarRef?: { id: string; hash: string; createdAt: number };clearBotAvatarRefs?: boolean;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/legacyTeammateAvatar.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/legacyTeammateAvatar.test.tsnew file mode 100644index 0000000000..30fc77da94--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/legacyTeammateAvatar.test.ts@@ -0,0 +1,120 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { createHash } from 'node:crypto';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import path from 'node:path';+import { tmpdir } from 'node:os';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as schema from '../../schema';+import type { DbClient } from '../../client/DbClient';+import { tx } from '../../worker/opHandlers/tx';+import { resolveSafe } from '../../../cindy-media/blobStore';+import { migrateLegacyTeammateAvatar } from '../legacyTeammateAvatar';++const state = vi.hoisted(() => ({ userData: '', appPath: '', packaged: false }));+vi.mock('electron', () => ({ app: {+ getPath: () => state.userData,+ getAppPath: () => state.appPath,+ get isPackaged() { return state.packaged; },+} }));+vi.mock('../../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+const desktop = path.resolve(__dirname, '../../../../..');++describe('retired teammate avatar migration', () => {+ let raw: Database.Database;+ let client: Pick<DbClient, 'drizzle' | 'tx'>;+ const snapshot = (avatar = 'cindy://avatar/preset/dash') => ({ id: 'old', avatar, currentVersion: 4, updatedAt: 123 });+ const read = () => raw.prepare('SELECT avatar, current_version, updated_at FROM bot_profiles').get() as { avatar: string; current_version: number; updated_at: number };+ beforeEach(() => {+ state.userData = mkdtempSync(path.join(tmpdir(), 'teammate-avatar-migration-'));+ state.appPath = desktop;+ state.packaged = false;+ raw = new Database(':memory:');+ raw.pragma('foreign_keys = ON');+ raw.exec(readFileSync(path.join(desktop, 'drizzle/0070_woozy_harpoon.sql'), 'utf8'));+ raw.exec(`CREATE TABLE bot_profiles (id TEXT PRIMARY KEY, display_name TEXT, avatar TEXT, current_version INTEGER, updated_at INTEGER);+ INSERT INTO bot_profiles VALUES ('old', 'User renamed Dash', 'cindy://avatar/preset/dash', 4, 123);`);+ client = {+ drizzle: drizzle(raw, { schema }),+ tx: (async (name: string, args: unknown) => tx(raw, { name, args })) as DbClient['tx'],+ };+ });+ afterEach(() => { raw.close(); rmSync(state.userData, { recursive: true, force: true }); vi.restoreAllMocks(); });++ it.each(['dash', 'lizi'])('preserves exact %s bytes as a custom image, pins them and is idempotent', async name => {+ const original = snapshot(`cindy://avatar/preset/${name}`);+ raw.prepare('UPDATE bot_profiles SET avatar = ?').run(original.avatar);+ await migrateLegacyTeammateAvatar(client, original, () => {});+ const bytes = readFileSync(path.join(desktop, `resources/legacy-teammate-avatars/${name}.png`));+ const hash = createHash('sha256').update(bytes).digest('hex');+ expect(read()).toEqual({ avatar: `cindy-media://blobs/${hash}.png`, current_version: 4, updated_at: 123 });+ const resolved = resolveSafe(read().avatar);+ expect(resolved).not.toBeNull();+ expect(readFileSync(resolved!.absPath)).toEqual(bytes);+ expect(raw.prepare('SELECT hash, ref_kind, ref_id FROM media_refs').all()).toEqual([{ hash, ref_kind: 'bot-avatar', ref_id: 'old' }]);+ expect(await migrateLegacyTeammateAvatar(client, { ...original, avatar: read().avatar }, () => {})).toBe(false);+ expect(raw.prepare('SELECT count(*) AS n FROM media_refs').get()).toEqual({ n: 1 });+ });++ it.each(['cindy://avatar/preset/cindy', '🌸', `cindy-media://blobs/${'a'.repeat(64)}.png`, 'cindy://avatar/preset/unknown'])('leaves non-legacy address %s untouched', async avatar => {+ const store = vi.spyOn(client, 'tx');+ expect(await migrateLegacyTeammateAvatar(client, snapshot(avatar), () => {})).toBe(false);+ expect(store).not.toHaveBeenCalled();+ expect(raw.prepare('SELECT * FROM media_refs').all()).toEqual([]);+ });++ it('keeps the legacy address after a storage failure and retries successfully', async () => {+ state.appPath = state.userData;+ await migrateLegacyTeammateAvatar(client, snapshot(), () => {});+ expect(read().avatar).toBe(snapshot().avatar);+ expect(raw.prepare('SELECT * FROM media_refs').all()).toEqual([]);+ state.appPath = desktop;+ await migrateLegacyTeammateAvatar(client, snapshot(), () => {});+ expect(read().avatar).toMatch(/^cindy-media:/);+ });++ it('loads compatibility bytes from packaged resources rather than the source checkout', async () => {+ const prior = Object.getOwnPropertyDescriptor(process, 'resourcesPath');+ Object.defineProperty(process, 'resourcesPath', { configurable: true, value: path.join(desktop, 'resources') });+ state.packaged = true;+ state.appPath = state.userData;+ try {+ await migrateLegacyTeammateAvatar(client, snapshot(), () => {});+ expect(read().avatar).toMatch(/^cindy-media:/);+ } finally {+ if (prior) Object.defineProperty(process, 'resourcesPath', prior);+ else Reflect.deleteProperty(process, 'resourcesPath');+ }+ });++ it('does not replace a concurrent custom avatar at the same profile version', async () => {+ const originalTx = client.tx;+ client.tx = (async (name: string, args: unknown) => {+ raw.prepare('UPDATE bot_profiles SET avatar = ?').run('🌸');+ return originalTx(name as 'bots.updateProfile', args as never);+ }) as DbClient['tx'];+ await migrateLegacyTeammateAvatar(client, snapshot(), () => {});+ expect(read().avatar).toBe('🌸');+ expect(raw.prepare('SELECT * FROM media_refs').all()).toEqual([]);+ });++ it('preserves activity that advances while the old image is being imported', async () => {+ const originalTx = client.tx;+ client.tx = (async (name: string, args: unknown) => {+ raw.prepare('UPDATE bot_profiles SET updated_at = 999').run();+ return originalTx(name as 'bots.updateProfile', args as never);+ }) as DbClient['tx'];+ await migrateLegacyTeammateAvatar(client, snapshot(), () => {});+ expect(read().avatar).toMatch(/^cindy-media:/);+ expect(read().updated_at).toBe(999);+ });++ it('does not publish to a different owner if the account changes during file reading', async () => {+ let checks = 0;+ await expect(migrateLegacyTeammateAvatar(client, snapshot(), () => {+ if (++checks > 1) throw new Error('owner changed');+ })).rejects.toThrow('owner changed');+ expect(read().avatar).toBe(snapshot().avatar);+ expect(raw.prepare('SELECT * FROM media_blobs').all()).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.tsindex ada56af5af..e3a077275b 100644--- a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts+++ b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts@@ -1,3 +1,5 @@+import { writeBlob } from '../../cindy-media/blobStore.js';+import { recordBlob, type LedgerDb } from '../../cindy-media/ledger.js';import { sniffImageMime } from '../../lightboxMediaActions.js';import { throwIpcError } from '../../utils/ipcValidate.js';@@ -32,3 +34,17 @@ export function decodeBotAvatarImage(value: unknown): { buffer: Buffer; mimeTypeconst buffer = Buffer.from(value, 'base64');return { buffer, mimeType: validateBotAvatarBuffer(buffer) };}++/** Shared upload/migration ingress; the caller atomically attaches the returned blob to the profile. */+export async function storeTeammateAvatarImage(+ image: { buffer: Buffer; mimeType: string },+ db: LedgerDb,+ assertCurrent: () => void,+) {+ assertCurrent();+ const written = await writeBlob({ buffer: image.buffer, mimeType: validateBotAvatarBuffer(image.buffer) });+ assertCurrent();+ await recordBlob({ hash: written.hash, ext: written.ext, mimeType: written.mimeType, bytes: written.bytes, isCache: false }, db);+ assertCurrent();+ return written;+}diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 4fd9ec0bfe..e37483e4ce 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -73,10 +73,9 @@ import {isSupportedBotAvatarValue,portableBotAvatarOrFallback,} from '../../../shared/botAvatarValue.js';+import { migrateLegacyTeammateAvatar } from './legacyTeammateAvatar.js';import { MAKER_PUSH } from '../../maker-ipc/channels.js';-import { writeBlob } from '../../cindy-media/blobStore.js';-import { recordBlob } from '../../cindy-media/ledger.js';-import { decodeBotAvatarImage, validateBotAvatarBuffer } from './botAvatarSelection.js';+import { decodeBotAvatarImage, validateBotAvatarBuffer, storeTeammateAvatarImage } from './botAvatarSelection.js';import {inferBotTemplatePresetId,isBotTemplatePresetId,@@ -473,8 +472,12 @@ async function readProfile() {const owner = captureBotOperationOwner();const db = client.drizzle;- const [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);+ let [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);if (!profile) throwIpcError('NOT_FOUND', 'Bot 不存在');+ if (await migrateLegacyTeammateAvatar(client, profile, owner.assertCurrent)) {+ [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);+ if (!profile) throwIpcError('NOT_FOUND', 'Bot 不存在');+ }const canonicalResolution = await reconcileCanonicalLink(botId, client);const canonicalSessionId = canonicalResolution.canonicalSessionId;const links = await db@@ -663,6 +666,10 @@ async function readProfile(async function readRemoteBotProfile(client: ReturnType<typeof getDbClient>, botId: string) {const owner = captureBotOperationOwner();const db = client.drizzle;+ const [stored] = await db.select().from(botProfiles).where(eq(botProfiles.id, botId)).limit(1);+ if (!stored) throwIpcError('NOT_FOUND', 'Bot 不存在');+ if (!isBotVisibleRemotely(stored)) return null;+ await migrateLegacyTeammateAvatar(client, stored, owner.assertCurrent);const [profile] = await db.select({id: botProfiles.id,@@ -961,10 +968,7 @@ export async function createBotProfile(raw: unknown) {throwIpcError('ALREADY_EXISTS', 'Bot home already belongs to another profile');}if (avatarImage) {- const written = await writeBlob(avatarImage);- assertCreationOwnerStillCurrent();- await recordBlob({ hash: written.hash, ext: written.ext, mimeType: written.mimeType, bytes: written.bytes, isCache: false }, db);- assertCreationOwnerStillCurrent();+ const written = await storeTeammateAvatarImage(avatarImage, db, assertCreationOwnerStillCurrent);avatar = written.url;botAvatarRef = { id: randomUUID(), hash: written.hash, createdAt: now };}@@ -1345,17 +1349,7 @@ export function registerBotIpc(): void {// reference move together in one SQLite transaction. If the transaction// loses a race, the unreferenced content-addressed blob is recycler-safe.ownerBoundary.assertCurrent();- const written = await writeBlob({ buffer, mimeType });- await recordBlob(- {- hash: written.hash,- ext: written.ext,- mimeType: written.mimeType,- bytes: written.bytes,- isCache: false,- },- db,- );+ const written = await storeTeammateAvatarImage({ buffer, mimeType }, db, ownerBoundary.assertCurrent);const now = Date.now();await client.tx('bots.updateProfile', {id: botId,diff --git a/apps/desktop/src/main/localDb/ipc/legacyTeammateAvatar.ts b/apps/desktop/src/main/localDb/ipc/legacyTeammateAvatar.tsnew file mode 100644index 0000000000..a1c7f4e34b--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/legacyTeammateAvatar.ts@@ -0,0 +1,46 @@+import { randomUUID } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { app } from 'electron';+import type { DbClient } from '../client/DbClient.js';+import { createLogger } from '../../logger.js';+import { storeTeammateAvatarImage, validateBotAvatarBuffer } from './botAvatarSelection.js';++const log = createLogger('legacy-teammate-avatar');+const legacyFiles: Record<string, string> = {+ 'cindy://avatar/preset/dash': 'dash.png',+ 'cindy://avatar/preset/lizi': 'lizi.png',+};++/** Upgrade by stored address, never by name or template: user replacements remain untouched. */+export async function migrateLegacyTeammateAvatar(+ client: Pick<DbClient, 'drizzle' | 'tx'>,+ profile: { id: string; avatar: string; currentVersion: number },+ assertCurrent: () => void,+): Promise<boolean> {+ const filename = legacyFiles[profile.avatar.trim().toLowerCase()];+ if (!filename) return false;+ try {+ assertCurrent();+ const root = app.isPackaged ? process.resourcesPath : path.join(app.getAppPath(), 'resources');+ const buffer = await fs.readFile(path.join(root, 'legacy-teammate-avatars', filename));+ const written = await storeTeammateAvatarImage({ buffer, mimeType: validateBotAvatarBuffer(buffer) }, client.drizzle, assertCurrent);+ // No profile version or activity-time change. The ref and address either both+ // commit or neither does; a concurrent user replacement wins even at the same version.+ await client.tx('bots.updateProfile', {+ id: profile.id, avatar: written.url,+ expectedAvatar: profile.avatar, expectedCurrentVersion: profile.currentVersion,+ identitySource: '', capabilitiesJson: '{}', profileContentChanged: false,+ botAvatarRef: { id: randomUUID(), hash: written.hash, createdAt: Date.now() },+ preserveUpdatedAt: true, now: Date.now(),+ });+ assertCurrent();+ } catch (error) {+ assertCurrent();+ // Leave the legacy value usable through the compatibility image and retry on+ // the next read. Failed/raced imports use the existing zero-ref recycler grace period.+ log.warn('legacy avatar migration deferred', { error: error instanceof Error ? error.name : typeof error });+ }+ // Re-read even after a lost race: return the user's current avatar, never this stale snapshot.+ return true;+}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex c1f1d91f51..50f4ecbfb0 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -234,19 +234,25 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersithrow new Error('botAvatarRef requires an avatar address');}return db.transaction(() => {- const current = db.prepare('SELECT current_version AS currentVersion, display_name AS displayName FROM bot_profiles WHERE id = ?')- .get(id) as { currentVersion: number; displayName: string } | undefined;+ const current = db.prepare('SELECT current_version AS currentVersion, display_name AS displayName, avatar FROM bot_profiles WHERE id = ?')+ .get(id) as { currentVersion: number; displayName: string; avatar: string } | undefined;if (!current) throw Object.assign(new Error('Bot 不存在'), { code: 'NOT_FOUND' });if (current.currentVersion !== expectedVersion) {throw Object.assign(new Error('Bot Profile 已被另一处更新,请刷新后重试'), { code: 'PRECONDITION_FAILED' });}+ if (p.expectedAvatar !== undefined && current.avatar !== expectString(p.expectedAvatar, 'expectedAvatar')) {+ throw Object.assign(new Error('Teammate avatar changed during update'), { code: 'PRECONDITION_FAILED' });+ }if (p.displayName !== undefined && normalizeBotName(expectString(p.displayName, 'displayName')) !== normalizeBotName(current.displayName)) {const name = normalizeBotName(expectString(p.displayName, 'displayName'));const others = db.prepare("SELECT display_name AS name FROM bot_profiles WHERE id != ? AND status != 'archived'").all(id) as Array<{ name: string }>;if (others.some(row => normalizeBotName(row.name) === name)) throw Object.assign(new Error('A companion with this name already exists'), { code: 'ALREADY_EXISTS' });}- const fields = ['updated_at = ?'];- const values: unknown[] = [now];+ if (p.preserveUpdatedAt !== undefined && typeof p.preserveUpdatedAt !== 'boolean') {+ throw new Error('preserveUpdatedAt must be a boolean');+ }+ const fields = p.preserveUpdatedAt === true ? ['updated_at = updated_at'] : ['updated_at = ?'];+ const values: unknown[] = p.preserveUpdatedAt === true ? [] : [now];for (const [key, column] of [['displayName', 'display_name'], ['description', 'description'], ['avatar', 'avatar'],['avatarColor', 'avatar_color'], ['status', 'status'],diff --git a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx b/apps/desktop/src/renderer/features/bots/BotAvatar.tsxindex b04a573d96..57770cfb14 100644--- a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx+++ b/apps/desktop/src/renderer/features/bots/BotAvatar.tsx@@ -21,8 +21,9 @@ import { rewriteToRemoteMediaOrigin } from '@/../shared/remoteMediaUrl';import { useEffect, useState } from 'react';import cindyPresetAvatar from '@/assets/bot-presets/cindy.png';-import dashPresetAvatar from '@/assets/bot-presets/dash.png';-import liziPresetAvatar from '@/assets/bot-presets/lizi.png';+// Upgrade failure/older remote-host fallback only; migrated profiles use cindy-media.+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 { CINDY_AVATAR_SCHEME_PREFIX, isCindyAvatarSentinel } from './botAvatarIdentity';