Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(agent-island): 伙伴消息以伙伴身份显示,展开行共用头像列对齐
Dash645a8837473e
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex c3bf43daf7..1744b2cf54 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -789,6 +789,8 @@ function extraResourcesForTarget(targetPlatform: string): string[] {'resources/cindy-version-protocol.json',// Input bytes for upgrading retired preset avatars to ordinary managed images.'resources/legacy-teammate-avatars',+ // Bundled preset artwork main draws outside the renderer (Agent Island companion avatars).+ 'resources/companion-preset-avatars','resources/teammate-portrait-gallery.png',// Cindy-owned Agent Skills are materialized under userData on startup.'resources/system-skills',diff --git a/apps/desktop/native/agent-island/macos-agent-island-helper.swift b/apps/desktop/native/agent-island/macos-agent-island-helper.swiftindex 6cc03127b2..1635e65369 100644--- a/apps/desktop/native/agent-island/macos-agent-island-helper.swift+++ b/apps/desktop/native/agent-island/macos-agent-island-helper.swift@@ -1365,9 +1365,21 @@ struct AgentIslandPermissionAction: Codable, Equatable {let canAllowForSession: Bool}+/// The companion a Bot Session speaks for; drawn instead of the agent mark.+struct AgentIslandCompanion: Codable, Equatable {+ let name: String+ let groupName: String?+ let hue: String+ let imageJpeg: String?+ let glyph: String+ let glyphIsInitial: Bool+}+struct AgentIslandSession: Codable, Equatable, Identifiable {let sessionId: Stringlet title: String+ // Older main-process payloads have no companion field.+ var companion: AgentIslandCompanion? = nillet projectName: String?let detail: Stringlet compactDetail: String@@ -3444,22 +3456,49 @@ struct ExpandedSessionRow: View, Equatable {4}+ /// Every row shares one leading column, so titles and summaries line up whether the+ /// row speaks as a companion (avatar) or reports a task (agent mark / status icon).private var rowMainContent: some View {- VStack(alignment: .leading, spacing: rowSpacing) {- ExpandedSessionHeaderLine(- session: session,- strings: strings,- titleFontSize: 13,- mascotSkin: mascotSkin,- onFocus: onFocus- )- ExpandedRowSummaryLine(session: session, strings: strings)- .padding(.leading, 28)+ HStack(alignment: .center, spacing: 10) {+ Group {+ if let companion = session.companion {+ AgentIslandCompanionStatusAvatar(session: session, companion: companion, size: expandedRowLeadingSize)+ } else {+ StatusDot(+ session: session,+ compact: false,+ showsRunningAnimation: showsRunningIcon,+ mascotSkin: mascotSkin,+ size: 26+ )+ }+ }+ .frame(width: expandedRowLeadingSize, height: expandedRowLeadingSize)+ VStack(alignment: .leading, spacing: rowSpacing) {+ ExpandedSessionHeaderLine(+ session: session,+ strings: strings,+ titleFontSize: 13,+ onFocus: onFocus+ )+ ExpandedRowSummaryLine(session: session, strings: strings)+ }}.frame(maxWidth: .infinity, alignment: .leading)}++ private var showsRunningIcon: Bool {+ switch session.phase {+ case "needs-interaction", "completed":+ return false+ default:+ return true+ }+ }}+private let expandedRowLeadingSize: CGFloat = 32+func expandedCardFillOpacity(session: AgentIslandSession, hovered: Bool) -> Double {let base = session.phase == "needs-interaction" ? 0.065 : 0.035return hovered ? base + 0.035 : base@@ -3474,40 +3513,47 @@ struct ExpandedSessionHeaderLine: View {let session: AgentIslandSessionlet strings: AgentIslandStringslet titleFontSize: CGFloat- let mascotSkin: Stringlet onFocus: () -> Void- private var showsMascot: Bool {- switch session.phase {- case "needs-interaction", "completed":- return false- default:- return true- }+ /// A finished companion turn reads as a message: the reply is the content, no "Done" tag.+ private var isCompanionReply: Bool {+ session.companion != nil && session.phase == "completed"+ }++ private var titleText: Text {+ let title = Text(expandedPrimaryTitle(for: session, strings: strings))+ .foregroundColor(Color.white.opacity(0.92))+ guard let group = companionGroupName else { return title }+ // The group yields first when the line is too narrow: the speaker stays readable.+ return title + Text(" · \(group)").foregroundColor(Color.white.opacity(0.42))+ }++ private var titleHelp: String {+ let title = expandedPrimaryTitle(for: session, strings: strings)+ guard let group = companionGroupName else { return title }+ return "\(title) · \(group)"+ }++ private var companionGroupName: String? {+ let group = session.companion?.groupName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ return group.isEmpty ? nil : group}var body: some View {HStack(alignment: .center, spacing: 8) {- StatusDot(- session: session,- compact: false,- showsRunningAnimation: showsMascot,- mascotSkin: mascotSkin- )- Text(expandedPrimaryTitle(for: session, strings: strings))+ titleText.font(.system(size: titleFontSize, weight: .medium))- .foregroundColor(Color.white.opacity(0.92)).lineLimit(1).truncationMode(.tail).layoutPriority(1)- .help(expandedPrimaryTitle(for: session, strings: strings))+ .help(titleHelp)Spacer(minLength: 8)if session.phase == "needs-interaction", session.permissionAction == nil {InteractionInlineButton(label: strings.review, action: onFocus)- } else {+ } else if !isCompanionReply {SessionStatusLabel(session: session, strings: strings)}}@@ -3673,6 +3719,10 @@ struct ExpandedRowSummary {}func expandedPrimaryTitle(for session: AgentIslandSession, strings: AgentIslandStrings) -> String {+ // A companion is named by its owner; never filter it like a generic agent title.+ if let name = session.companion?.name.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty {+ return name+ }let title = session.title.trimmingCharacters(in: .whitespacesAndNewlines)if isMeaningfulExpandedTitle(title) {return title@@ -3950,27 +4000,39 @@ struct StatusDot: View {var showsRunningAnimation = truevar mascotSkin = defaultAgentIslandMascotSkinvar runningMascotNamespace: Namespace.ID?+ /// Overrides the default 18pt (compact) / 20pt slot; glyphs scale with it.+ var size: CGFloat? = nil++ private var side: CGFloat { size ?? (compact ? 18 : 20) }+ private var glyphScale: CGFloat { side / 20 }var body: some View {let accent = statusAccentColor(for: session)ZStack {- if usesExpandedVendorStatusIcon {+ if let companion = session.companion {+ AgentIslandCompanionStatusAvatar(+ session: session,+ companion: companion,+ size: side+ )+ } else if usesExpandedVendorStatusIcon {AgentIslandSessionVendorIcon(session: session,running: isRunningSession(session),- highlighted: session.phase == "completed" && session.attention+ highlighted: session.phase == "completed" && session.attention,+ size: side)} else if let mascotState = mascotAnimationState(for: session), showsRunningAnimation {if let runningMascotNamespace {RunningMascotIcon(skin: mascotSkin,state: mascotState,- size: compact ? 18 : 20,+ size: side,namespace: runningMascotNamespace)} else {- AgentIslandMascotView(skin: mascotSkin, state: mascotState, size: compact ? 18 : 20)- .frame(width: compact ? 18 : 20, height: compact ? 18 : 20)+ AgentIslandMascotView(skin: mascotSkin, state: mascotState, size: side)+ .frame(width: side, height: side)}} else {Circle().fill(accent.opacity(session.phase == "completed" ? 0.08 : 0.13))@@ -3978,7 +4040,7 @@ struct StatusDot: View {.foregroundColor(accent.opacity(session.phase == "completed" ? 0.78 : 0.96))}}- .frame(width: compact ? 18 : 20, height: compact ? 18 : 20)+ .frame(width: side, height: side)}private var usesExpandedVendorStatusIcon: Bool {@@ -3991,13 +4053,13 @@ struct StatusDot: View {switch session.phase {case "needs-interaction":Image(systemName: "questionmark.bubble")- .font(.system(size: 11, weight: .semibold))+ .font(.system(size: 11 * glyphScale, weight: .semibold))case "completed":Image(systemName: "checkmark")- .font(.system(size: 11, weight: .semibold))+ .font(.system(size: 11 * glyphScale, weight: .semibold))case "error":Image(systemName: "exclamationmark.triangle")- .font(.system(size: 10, weight: .semibold))+ .font(.system(size: 10 * glyphScale, weight: .semibold))default:EmptyView()}@@ -4046,6 +4108,7 @@ struct AgentIslandSessionVendorIcon: View {let session: AgentIslandSessionlet running: Boollet highlighted: Bool+ var size: CGFloat = 20@State private var isBreathing = false@Environment(\.agentIslandMascotAnimationsActive) private var animationsActive@@ -4054,7 +4117,7 @@ struct AgentIslandSessionVendorIcon: View {}private var markSize: CGFloat {- vendor == .cc ? 13 : 12+ (vendor == .cc ? 13 : 12) * size / 20}var body: some View {@@ -4087,7 +4150,7 @@ struct AgentIslandSessionVendorIcon: View {.onChange(of: running) { _, isRunning inisBreathing = isRunning && animationsActive}- .frame(width: 20, height: 20)+ .frame(width: size, height: size)}@ViewBuilder@@ -4102,6 +4165,124 @@ struct AgentIslandSessionVendorIcon: View {}}+/// Dark tints of the BotAvatar hue family (`--bot-avatar-*-bg`, dark); the island is always dark.+func agentIslandCompanionHueColor(_ hue: String) -> Color {+ let rgb: (Double, Double, Double)+ switch hue {+ case "red": rgb = (0x4a, 0x2e, 0x2a)+ case "orange": rgb = (0x4a, 0x35, 0x27)+ case "amber": rgb = (0x47, 0x3a, 0x22)+ case "green": rgb = (0x26, 0x40, 0x2a)+ case "teal": rgb = (0x21, 0x40, 0x3e)+ case "blue": rgb = (0x26, 0x34, 0x49)+ case "pink": rgb = (0x45, 0x2b, 0x39)+ case "graphite": rgb = (0x3c, 0x3c, 0x3a)+ default: rgb = (0x32, 0x2b, 0x48)+ }+ return Color(red: rgb.0 / 255, green: rgb.1 / 255, blue: rgb.2 / 255)+}++final class AgentIslandCompanionAvatarStore {+ static let shared = AgentIslandCompanionAvatarStore()++ // Keyed by the thumbnail itself: a changed avatar arrives as different bytes.+ private var cache: [String: NSImage?] = [:]++ func image(forJpegBase64 base64: String) -> NSImage? {+ if let cached = cache[base64] { return cached }+ let image = Data(base64Encoded: base64).flatMap { NSImage(data: $0) }+ if cache.count >= 16 { cache.removeAll() }+ cache[base64] = image+ return image+ }+}++struct AgentIslandCompanionAvatar: View {+ let companion: AgentIslandCompanion+ let size: CGFloat++ var body: some View {+ ZStack {+ Circle().fill(agentIslandCompanionHueColor(companion.hue))+ if let base64 = companion.imageJpeg,+ let image = AgentIslandCompanionAvatarStore.shared.image(forJpegBase64: base64) {+ Image(nsImage: image)+ .resizable()+ .interpolation(.high)+ .aspectRatio(contentMode: .fill)+ } else if companion.glyphIsInitial {+ Text(companion.glyph)+ .font(.system(size: size * 0.5, weight: .medium))+ .foregroundColor(Color.white.opacity(0.92))+ } else {+ Text(companion.glyph)+ .font(.system(size: size * 0.58))+ }+ }+ .frame(width: size, height: size)+ .clipShape(Circle())+ .accessibilityLabel(companion.name)+ }+}++/// Companion avatar plus the session state the agent mark would otherwise carry:+/// a breathing ring while it works, a corner dot when it waits, failed or replied unread.+struct AgentIslandCompanionStatusAvatar: View {+ let session: AgentIslandSession+ let companion: AgentIslandCompanion+ let size: CGFloat+ @State private var isBreathing = false+ @Environment(\.agentIslandMascotAnimationsActive) private var animationsActive++ private var running: Bool { isRunningSession(session) }++ private var badgeSize: CGFloat { max(6, min(size * 0.3, 10)) }++ private var badgeColor: Color? {+ switch session.phase {+ case "needs-interaction":+ return agentIslandBlue+ case "error":+ return agentIslandErrorRed+ case "completed":+ return session.attention ? agentIslandUnreadGreen : nil+ default:+ return nil+ }+ }++ var body: some View {+ AgentIslandCompanionAvatar(companion: companion, size: size)+ .overlay(+ Circle()+ .strokeBorder(agentIslandOrange, lineWidth: size >= 28 ? 2 : 1.5)+ .opacity(running ? (animationsActive ? (isBreathing ? 0.95 : 0.3) : 0.85) : 0)+ .animation(+ running && animationsActive ? .easeInOut(duration: 0.75).repeatForever(autoreverses: true) : .default,+ value: isBreathing+ )+ )+ .overlay(alignment: .bottomTrailing) {+ if let badgeColor {+ Circle()+ .fill(badgeColor)+ .frame(width: badgeSize, height: badgeSize)+ .overlay(Circle().strokeBorder(Color.black, lineWidth: size >= 28 ? 1.5 : 1.2))+ }+ }+ .frame(width: size, height: size)+ .onAppear {+ isBreathing = running && animationsActive+ }+ .onChange(of: animationsActive) { _, active in+ isBreathing = running && active+ }+ .onChange(of: running) { _, isRunning in+ isBreathing = isRunning && animationsActive+ }+ }+}+struct RunningMascotIcon: View {let skin: Stringlet state: AgentIslandMascotAnimationStatediff --git a/apps/desktop/src/renderer/assets/bot-presets/cindy.png b/apps/desktop/resources/companion-preset-avatars/cindy.pngsimilarity index 100%rename from apps/desktop/src/renderer/assets/bot-presets/cindy.pngrename to apps/desktop/resources/companion-preset-avatars/cindy.pngdiff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex 0196227e22..b20a7c3a67 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -29,6 +29,7 @@ import { AGENT_ISLAND_DISPLAY_CONFIG } from '../displayConfig.js';import type { AgentIslandNativeFrame } from '../MacAgentIslandNativeHost.js';import { markAppContentWindow } from '../../windowFocusClassifier.js';import type { AgentIslandService } from '../service.js';+import type { AgentIslandCompanionIdentity } from '../companionIdentity.js';import { setDeepLinkMainWindow, takePendingDeepLink } from '../../deepLink.js';const REMOTE_DAEMON_CLOSED_REASON = 'remote_daemon_closed';@@ -61,7 +62,9 @@ const mocks = vi.hoisted(() => ({userSendAt: number | null;workingDir: string | null;workspaceKind: string | null;+ source?: string | null;} | null>>(() => Promise.resolve(null)),+ readAgentIslandCompanion: vi.fn<(sessionId: string) => Promise<AgentIslandCompanionIdentity | null>>(() => Promise.resolve(null)),primaryDisplay: {id: 1,label: 'Built-in Retina Display',@@ -137,6 +140,10 @@ vi.mock('../../localDb/ipc/sessions.js', () => ({getSessionRowSnapshot: mocks.getSessionRowSnapshot,}));+vi.mock('../companionIdentity.js', () => ({+ readAgentIslandCompanion: mocks.readAgentIslandCompanion,+}));+vi.mock('../layoutPreferenceStore.js', () => ({readAgentIslandDetachedLayoutPreferences: mocks.readDetachedLayoutPreferences,readAgentIslandLayoutPreferences: mocks.readLayoutPreferences,@@ -156,6 +163,8 @@ beforeEach(() => {takePendingDeepLink();mocks.getSessionRowSnapshot.mockReset();mocks.getSessionRowSnapshot.mockResolvedValue(null);+ mocks.readAgentIslandCompanion.mockReset();+ mocks.readAgentIslandCompanion.mockResolvedValue(null);mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay);mocks.getPrimaryDisplay.mockReset();mocks.getDisplayMatching.mockReset();@@ -1713,6 +1722,52 @@ describe('AgentIslandService native publishing', () => {});});+ // Companion Sessions are Bot Sessions whose title and home folder are not what the user+ // knows them by; the island must load the companion and follow its renames.+ it('loads a companion identity for Bot Sessions and refreshes it when the companion changes', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const workingDir = '/Users/alice/Library/Application Support/Cindy/owners/o1/bots/b1/workspace';+ const identity = (name: string): AgentIslandCompanionIdentity => ({+ botId: 'b1',+ companion: { name, hue: 'violet', glyph: name[0]!, glyphIsInitial: true },+ });+ mocks.getSessionRowSnapshot.mockImplementation(async () => ({+ status: 'active', title: 'Opus', userSendAt: null, workingDir, workspaceKind: null, source: 'bot',+ }));+ mocks.readAgentIslandCompanion.mockResolvedValue(identity('Opus'));+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish },+ });+ syncEnabledForTest(service, publish);++ service.handleUserPrompt({ sessionId: 's1', agentKind: 'claude-code', workingDir }, 'hi');+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ title: 'Opus',+ projectName: null,+ companion: identity('Opus').companion,+ }));++ // A title patch must not drop the companion that was already resolved.+ service.handleSessionMetadataPatch('s1', { title: 'Renamed task' });+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.companion?.name).toBe('Opus');++ service.handleCompanionProfileChanged('another-bot');+ expect(mocks.readAgentIslandCompanion).toHaveBeenCalledTimes(1);++ mocks.readAgentIslandCompanion.mockResolvedValue(identity('Sonnet'));+ service.handleCompanionProfileChanged('b1');+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ title: 'Sonnet',+ companion: { name: 'Sonnet' },+ }));+ });+it('refreshes placeholder titles and hides dialogue workspace folders', async () => {const { AgentIslandService } = await import('../service.js');const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.tsindex bd89f6bf38..def9f3fdb3 100644--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts@@ -933,6 +933,33 @@ describe('Agent Island display state', () => {expect(display.pillSnapshot.priorityCompactTitle).toBe('目标模式测试');});+ // Companion Sessions run in the companion's private home: before companion identity the+ // island titled them by a filtered task title and labelled the home folder "workspace".+ it.each([+ { name: 'own chat', groupName: undefined, projectName: null },+ { name: 'group line', groupName: 'Cindy开发', projectName: 'Cindy开发' },+ ])('shows a companion Session by its companion, not its home folder ($name)', ({ groupName, projectName }) => {+ const state = createAgentIslandState();+ const companion = {+ name: 'Claude',+ ...(groupName ? { groupName } : {}),+ hue: 'teal' as const,+ glyph: 'C',+ glyphIsInitial: true,+ };+ const workingDir = '/Users/alice/Library/Application Support/Cindy/owners/o1/bots/b1/workspace';++ applyAgentIslandUserPrompt(state, { sessionId: 's1', agentKind: 'claude-code', workingDir }, 'hi', 1_000);+ applyAgentIslandMetadata(state, { sessionId: 's1', title: 'Group title', workingDir, companion }, 1_100);+ // Later events keep re-sending the home folder; the companion context must win.+ applyAgentIslandEvent(state, { sessionId: 's1', workingDir }, finalTextEvent('你好'), 1_200);++ const display = buildAgentIslandDisplayState(state, 1_250);++ expect(display.sessions[0]).toMatchObject({ title: 'Claude', projectName, companion });+ expect(display.pillSnapshot.priorityCompactTitle).toBe('Claude');+ });+it('keeps only the latest three activity preview lines', () => {const state = createAgentIslandState();diff --git a/apps/desktop/src/main/agent-island/companionIdentity.ts b/apps/desktop/src/main/agent-island/companionIdentity.tsnew file mode 100644index 0000000000..3c7a4e8e17--- /dev/null+++ b/apps/desktop/src/main/agent-island/companionIdentity.ts@@ -0,0 +1,101 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { app } from 'electron';+import { and, eq, inArray } from 'drizzle-orm';+import sharp from 'sharp';+import type { AgentIslandCompanionSnapshot } from '../../shared/agentIsland.js';+import { botAvatarInitial, normalizeBotAvatarHue } from '../../shared/botAvatarHue.js';+import { BOT_AVATAR_MAX_BYTES, isManagedBotAvatarUrl, isSingleBotAvatarGrapheme } from '../../shared/botAvatarValue.js';+import { resolveSafe } from '../cindy-media/blobStore.js';+import { getDbClient } from '../localDb/client/current.js';+import { botGroups, botProfiles, botSessionLinks } from '../localDb/schema.js';+import { encodeNotificationAvatar } from '../notificationAvatar.js';++export interface AgentIslandCompanionIdentity {+ botId: string;+ companion: AgentIslandCompanionSnapshot;+}++/** Links that speak as the companion; delegated executions stay ordinary tasks. */+const COMPANION_SPEAKING_ROLES = ['canonical', 'history', 'group', 'channel'] as const;++/** Bundled preset artwork, relative to the packaged resources directory. */+const PRESET_AVATAR_FILES: Readonly<Record<string, string>> = {+ 'cindy://avatar/preset/cindy': 'companion-preset-avatars/cindy.png',+ 'cindy://avatar/preset/dash': 'legacy-teammate-avatars/dash.png',+ 'cindy://avatar/preset/lizi': 'legacy-teammate-avatars/lizi.png',+};++const THUMBNAIL_CACHE_LIMIT = 32;+// Content-addressed avatar values: a changed avatar is a new key, never a stale hit.+const thumbnails = new Map<string, Promise<string | undefined>>();++/** The companion a Bot Session speaks for, or null for every other Session. */+export async function readAgentIslandCompanion(sessionId: string): Promise<AgentIslandCompanionIdentity | null> {+ const db = getDbClient().drizzle;+ const row = await db+ .select({+ botId: botProfiles.id,+ name: botProfiles.displayName,+ avatar: botProfiles.avatar,+ avatarColor: botProfiles.avatarColor,+ role: botSessionLinks.role,+ routeKey: botSessionLinks.routeKey,+ })+ .from(botSessionLinks)+ .innerJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))+ .where(and(+ eq(botSessionLinks.sessionId, sessionId),+ inArray(botSessionLinks.role, [...COMPANION_SPEAKING_ROLES]),+ ))+ .get();+ if (!row) return null;+ const groupId = row.role === 'group' && row.routeKey?.startsWith('group:') ? row.routeKey.slice('group:'.length) : null;+ const group = groupId+ ? await db.select({ name: botGroups.name }).from(botGroups).where(eq(botGroups.id, groupId)).get()+ : undefined;+ const avatar = row.avatar.trim();+ const emoji = isSingleBotAvatarGrapheme(avatar) ? avatar : null;+ const imageJpeg = emoji ? undefined : await avatarThumbnail(avatar);+ const groupName = group?.name.trim();+ return {+ botId: row.botId,+ companion: {+ name: row.name,+ ...(groupName ? { groupName } : {}),+ hue: normalizeBotAvatarHue(row.avatarColor),+ ...(imageJpeg ? { imageJpeg } : {}),+ glyph: emoji ?? botAvatarInitial(row.name),+ glyphIsInitial: !emoji,+ },+ };+}++function avatarThumbnail(avatar: string): Promise<string | undefined> {+ const cached = thumbnails.get(avatar);+ if (cached) return cached;+ const pending = encodeAvatarThumbnail(avatar).catch(() => undefined);+ thumbnails.set(avatar, pending);+ if (thumbnails.size > THUMBNAIL_CACHE_LIMIT) thumbnails.delete(thumbnails.keys().next().value!);+ // Artwork is optional: a failed read falls back to the glyph and retries on the next lookup.+ void pending.then((value) => { if (!value && thumbnails.get(avatar) === pending) thumbnails.delete(avatar); });+ return pending;+}++async function encodeAvatarThumbnail(avatar: string): Promise<string | undefined> {+ const bytes = await readAvatarBytes(avatar);+ if (!bytes) return undefined;+ const encoded = await encodeNotificationAvatar(bytes, sharp);+ return encoded?.kind === 'jpeg' ? encoded.value : undefined;+}++async function readAvatarBytes(avatar: string): Promise<Buffer | undefined> {+ const preset = PRESET_AVATAR_FILES[avatar.toLowerCase()];+ if (preset) {+ const root = app.isPackaged ? process.resourcesPath : path.join(app.getAppPath(), 'resources');+ return readFile(path.join(root, preset));+ }+ if (!isManagedBotAvatarUrl(avatar)) return undefined;+ const bytes = await readFile(resolveSafe(avatar).absPath);+ return bytes.length > BOT_AVATAR_MAX_BYTES ? undefined : bytes;+}diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 8941ed568b..18f6b9a9b4 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -64,6 +64,7 @@ import {type AgentIslandDisplayState,type AgentIslandPillSnapshot,type AgentIslandRemoteSessionInput,+ type AgentIslandCompanionSnapshot,type AgentIslandSessionActivity,type AgentIslandSessionSnapshot,type AgentIslandDisplayTarget,@@ -75,6 +76,7 @@ import {type AgentIslandScreenLayoutMetrics,} from '../../shared/agentIsland.js';import { getSessionRowSnapshot } from '../localDb/ipc/sessions.js';+import { readAgentIslandCompanion, type AgentIslandCompanionIdentity } from './companionIdentity.js';import { createLogger } from '../logger.js';import { t } from '../i18n.js';import { isAppContentWindow, isFocusedAppContentWindow } from '../windowFocusClassifier.js';@@ -171,6 +173,14 @@ interface AgentIslandSessionMeta {workspaceKind?: string | null;}+interface AgentIslandCachedMetadata {+ title: string | null;+ workingDir: string | null;+ workspaceKind: string | null;+ /** undefined until the Session row has been read; null for non-companion Sessions. */+ companion?: AgentIslandCompanionIdentity | null;+}+interface AgentIslandPermissionAction {requestId: string;action: 'allow' | 'allowForSession' | 'deny';@@ -313,11 +323,7 @@ export class AgentIslandService {private readonly nativeHost: AgentIslandNativeRenderer;private readonly headless: boolean;private publishTimer: ReturnType<typeof setTimeout> | null = null;- private readonly metadataCache = new Map<string, {- title: string | null;- workingDir: string | null;- workspaceKind: string | null;- }>();+ private readonly metadataCache = new Map<string, AgentIslandCachedMetadata>();private readonly metadataLoading = new Set<string>();private readonly layoutPreferencesByDisplayId: Map<number, AgentIslandLayoutPreference>;private readonly detachedLayoutPreferences: AgentIslandLayoutPreference[];@@ -1339,12 +1345,13 @@ export class AgentIslandService {sessionId: string,patch: { title?: string | null; workingDir?: string | null; workspaceKind?: string | null },): void {- const current = this.metadataCache.get(sessionId) ?? {+ const current: AgentIslandCachedMetadata = this.metadataCache.get(sessionId) ?? {title: null,workingDir: null,workspaceKind: null,};const next = {+ ...current,title: patch.title !== undefined ? patch.title : current.title,workingDir: patch.workingDir !== undefined ? patch.workingDir : current.workingDir,workspaceKind: patch.workspaceKind !== undefined ? patch.workspaceKind : current.workspaceKind,@@ -1352,6 +1359,24 @@ export class AgentIslandService {this.commitMetadata(sessionId, next);}+ /** A companion's name or avatar changed: redraw the Sessions that speak as it. */+ handleCompanionProfileChanged(botId: string): void {+ for (const [sessionId, cached] of this.metadataCache) {+ if (cached.companion?.botId !== botId) continue;+ void readAgentIslandCompanion(sessionId)+ .then((companion) => {+ const latest = this.metadataCache.get(sessionId);+ if (latest) this.commitMetadata(sessionId, { ...latest, companion });+ })+ .catch((err) => {+ log.warn('companion identity refresh failed', {+ sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ });+ }+ }+/*** 按需重放当前会话活动快照。`emit` 由调用方(bootstrap)注入定向 sink 时,* 快照只投给刚完成 sessions 订阅的那一台控制端;不传则沿默认广播通道扇出。@@ -1374,16 +1399,20 @@ export class AgentIslandService {* 兜底文案,直到下一次 metadata 事件才纠正(PR #1031 review P1)。存原始值 +* publish 时投影,切语言后的那次 republish 自然就是新语言,不需要任何重投影逻辑。*/- private commitMetadata(- sessionId: string,- meta: { title: string | null; workingDir: string | null; workspaceKind: string | null },- ): void {+ private commitMetadata(sessionId: string, meta: AgentIslandCachedMetadata): void {this.metadataCache.set(sessionId, meta);- if (!patchAgentIslandMetadata(this.state, { sessionId, ...meta })) return;+ const { companion, ...rest } = meta;+ if (!patchAgentIslandMetadata(this.state, {+ sessionId,+ ...rest,+ ...(companion !== undefined ? { companion: companion?.companion ?? null } : {}),+ })) return;this.publish();}- private hydrateMeta(meta: AgentIslandSessionMeta): AgentIslandSessionMeta & { title?: string | null } {+ private hydrateMeta(+ meta: AgentIslandSessionMeta,+ ): AgentIslandSessionMeta & { title?: string | null; companion?: AgentIslandCompanionSnapshot | null } {const cached = this.metadataCache.get(meta.sessionId);return {...meta,@@ -1391,6 +1420,7 @@ export class AgentIslandService {title: cached?.title ?? null,workingDir: cached?.workingDir ?? meta.workingDir,workspaceKind: cached?.workspaceKind ?? meta.workspaceKind,+ ...(cached?.companion !== undefined ? { companion: cached.companion?.companion ?? null } : {}),};}@@ -1448,14 +1478,28 @@ export class AgentIslandService {private ensureMetadata(sessionId: string): void {const cached = this.metadataCache.get(sessionId);- if (this.metadataLoading.has(sessionId) || (cached && !isPlaceholderSessionTitle(cached.title))) return;+ if (+ this.metadataLoading.has(sessionId)+ || (cached && cached.companion !== undefined && !isPlaceholderSessionTitle(cached.title))+ ) return;this.metadataLoading.add(sessionId);void getSessionRowSnapshot(sessionId)- .then((row) => {+ .then(async (row) => {+ // Only Bot Sessions can speak as a companion; others skip the extra lookup.+ const companion = row?.source === 'bot'+ ? await readAgentIslandCompanion(sessionId).catch((err) => {+ log.warn('companion identity load failed', {+ sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ return null;+ })+ : null;this.commitMetadata(sessionId, {title: row?.title ?? null,workingDir: row?.workingDir ?? null,workspaceKind: row?.workspaceKind ?? null,+ companion,});}).catch((err) => {diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex 5407301d1a..b99219c976 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -32,6 +32,7 @@ import {DEFAULT_AGENT_ISLAND_STRINGS,type AgentIslandActivityLine,type AgentIslandActivityLineKind,+ type AgentIslandCompanionSnapshot,type AgentIslandDisplayPolicy,type AgentIslandDisplaySurface,type AgentIslandDisplayState,@@ -109,6 +110,8 @@ interface AgentIslandSessionMeta {workingDir?: string | null;title?: string | null;workspaceKind?: string | null;+ /** undefined = not resolved yet; null = not a companion's Session. */+ companion?: AgentIslandCompanionSnapshot | null;}interface ApplyAgentIslandEventOptions {@@ -123,6 +126,7 @@ interface AgentIslandSessionState {pendingDeviceCompletionNotification?: boolean;sessionId: string;title: string | null;+ companion: AgentIslandCompanionSnapshot | null;projectName: string | null;detail: string;detailSource: 'tool' | 'status' | 'interaction' | null;@@ -504,10 +508,12 @@ export function patchAgentIslandMetadata(const session = state.sessions.get(meta.sessionId);if (!session) return false;const previousTitle = session.title;+ const previousCompanion = session.companion;const previousProjectName = session.projectName;const previousAgentKind = session.agentKind;applyMeta(session, meta);return previousTitle !== session.title+ || previousCompanion !== session.companion|| previousProjectName !== session.projectName|| previousAgentKind !== session.agentKind;}@@ -2427,7 +2433,9 @@ function buildPillSnapshot(}function pillTitle(session: AgentIslandSessionState, mode: 'micro' | 'compact'): string {- const title = meaningfulSessionTitle(session)+ // A companion is named by its owner; never filter it like a generic agent title.+ const title = normalizeInlineText(session.companion?.name ?? '')+ || meaningfulSessionTitle(session)|| session.projectName|| latestUserActivityTitle(session)|| session.sessionId.slice(0, 8);@@ -2529,6 +2537,7 @@ function getOrCreateSession(session = {sessionId: meta.sessionId,title: meta.title?.trim() || null,+ companion: null,projectName: projectNameFromWorkingDir(meta.workingDir, meta.workspaceKind),detail: '',detailSource: null,@@ -2632,7 +2641,11 @@ function applyMeta(session: AgentIslandSessionState, meta: AgentIslandSessionMetif (meta.agentKind) session.agentKind = meta.agentKind;const title = meta.title?.trim();if (title) session.title = title;- if (meta.workingDir !== undefined || meta.workspaceKind !== undefined) {+ if (meta.companion !== undefined) session.companion = meta.companion;+ if (session.companion) {+ // A companion's working directory is its private home, not a project the user chose.+ session.projectName = session.companion.groupName ?? null;+ } else if (meta.workingDir !== undefined || meta.workspaceKind !== undefined) {session.projectName = projectNameFromWorkingDir(meta.workingDir, meta.workspaceKind);}}@@ -2642,7 +2655,8 @@ function toSnapshot(session: AgentIslandSessionState): AgentIslandSessionSnapshoreturn {...(session.phase === 'completed' && session.completionNotification ? { completionNotification: session.completionNotification } : {}),sessionId: session.sessionId,- title: session.title || session.projectName || session.sessionId.slice(0, 8),+ title: session.companion?.name || session.title || session.projectName || session.sessionId.slice(0, 8),+ ...(session.companion ? { companion: session.companion } : {}),projectName: session.projectName,detail: reconnectStatus ?? session.detail,compactDetail: compactDetailForSession(session),diff --git a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts b/apps/desktop/src/main/localDb/agentIslandSessionPatch.tsindex 04bff19d93..801aa7bdb7 100644--- a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts+++ b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts@@ -43,3 +43,10 @@ function toNullableString(value: unknown): string | null | undefined {if (value === null || typeof value === 'string') return value;return undefined;}++/** 伙伴改名或换头像后,让灵动岛重画以它身份说话的任务。 */+export function notifyAgentIslandCompanionChanged(botId: string): void {+ void import('../agent-island/service.js')+ .then(({ getAgentIslandService }) => getAgentIslandService()?.handleCompanionProfileChanged(botId))+ .catch(() => undefined);+}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 29b0eb1c1d..c2ed5e6679 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1181,7 +1181,7 @@ describe('Bot canonical Session lifecycle', () => {if (state === 'deleted') h.providers = [];if (state === 'empty') readDefault.mockResolvedValue([]);const sharp = (await import('sharp')).default;- const bytes = await sharp(resolve(__dirname, '../../../../renderer/assets/bot-presets/cindy.png')).resize(256, 256).jpeg({ quality: 80 }).toBuffer();+ const bytes = await sharp(resolve(__dirname, '../../../../../resources/companion-preset-avatars/cindy.png')).resize(256, 256).jpeg({ quality: 80 }).toBuffer();await expect(botRemoteManagement.invoke(context, {collectionId: 'teammates', resourceRef: resource.ref, actionId: resource.actions![0].id,client: { protocolVersion: 1, primitives: ['form'], locale: 'en' },@@ -1194,7 +1194,7 @@ describe('Bot canonical Session lifecycle', () => {it('reconciles mobile creation after a lost receipt without bypassing invitation preparation', async () => {const { botRemoteManagement } = await import('../botRemoteManagement');const sharp = (await import('sharp')).default;- const bytes = await sharp(resolve(__dirname, '../../../../renderer/assets/bot-presets/cindy.png')).resize(256, 256).jpeg({ quality: 80 }).toBuffer();+ const bytes = await sharp(resolve(__dirname, '../../../../../resources/companion-preset-avatars/cindy.png')).resize(256, 256).jpeg({ quality: 80 }).toBuffer();const context = { controllerDeviceId: 'mobile-creation-test' };const client = { protocolVersion: 1, primitives: ['form'], locale: 'zh-CN' };const input = { name: '手机创建的伙伴', avatarImageBase64: bytes.toString('base64'), requestId: 'mobile-creation-intent-001' };@@ -1243,7 +1243,7 @@ describe('Bot canonical Session lifecycle', () => {await invoke('local-db:bots:create', { id: 'removed-cindy', name: 'Cindy', templateId: 'cindy' });h.sqlite!.prepare("UPDATE bot_profiles SET status = 'archived' WHERE id = 'removed-cindy'").run();await h.tx!('bots.deleteProfile', { botId: 'removed-cindy', sessionIds: [], keepTaskHistory: true, at: Date.now() });- const bytes = readFileSync(resolve(__dirname, '../../../../renderer/assets/bot-presets/cindy.png'));+ const bytes = readFileSync(resolve(__dirname, '../../../../../resources/companion-preset-avatars/cindy.png'));const created = await invoke('local-db:bots:create', {id: 'new-cindy', name: 'Cindy', avatarImageBase64: bytes.toString('base64'),});@@ -1261,7 +1261,7 @@ describe('Bot canonical Session lifecycle', () => {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,});const before = await invoke('local-db:bots:get', 'bot-1');- const bytes = readFileSync(resolve(__dirname, '../../../../renderer/assets/bot-presets/cindy.png'));+ const bytes = readFileSync(resolve(__dirname, '../../../../../resources/companion-preset-avatars/cindy.png'));const result = await invoke('local-db:bots:choose-avatar', {botId: 'bot-1', avatarImageBase64: bytes.toString('base64'),});diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex ee72638fea..59b44a1ee4 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -17,6 +17,7 @@ import type { OpenDialogOptions } from 'electron';import { and, desc, eq, gt, inArray, isNull, ne, or, sql } from 'drizzle-orm';import { getDbClient, tryGetDbClient } from '../client/current';+import { notifyAgentIslandCompanionChanged } from '../agentIslandSessionPatch.js';import type {BotsReparentDelegationsResult,BotsReplaceCanonicalSessionResult,@@ -1355,6 +1356,7 @@ export function broadcastBotProfileChanged(payload: {broadcastBotRemoteResourceChanged(payload.botId);// 伙伴自主跟进:新建伙伴、改「它开的任务也交给总调度跟」立即生效。signalBotAutonomyBotsChanged();+ if (payload.change === 'updated') notifyAgentIslandCompanionChanged(payload.botId);for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {diff --git a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx b/apps/desktop/src/renderer/features/bots/BotAvatar.tsxindex 57f5cf15f6..117a6b744f 100644--- a/apps/desktop/src/renderer/features/bots/BotAvatar.tsx+++ b/apps/desktop/src/renderer/features/bots/BotAvatar.tsx@@ -24,12 +24,19 @@import { rewriteToRemoteMediaOrigin } from '@/../shared/remoteMediaUrl';import { useEffect, useState } from 'react';-import cindyPresetAvatar from '@/assets/bot-presets/cindy.png';+import cindyPresetAvatar from '../../../../resources/companion-preset-avatars/cindy.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, isSingleBotAvatarGrapheme } from '../../../shared/botAvatarValue';+import {+ BOT_AVATAR_HUES,+ botAvatarHueForSeed,+ botAvatarInitial,+ normalizeBotAvatarHue,+ type BotAvatarHue,+} from '../../../shared/botAvatarHue';import { CINDY_AVATAR_SCHEME_PREFIX, isCindyAvatarSentinel } from './botAvatarIdentity';import { useCachedCompanionAvatar, type CompanionAvatarSource } from './companionAvatarCache';@@ -37,21 +44,8 @@ import { useCachedCompanionAvatar, type CompanionAvatarSource } from './companio// stays part of this module's public surface: UI code imports the avatar// vocabulary from BotAvatar.export { CINDY_AVATAR_SCHEME_PREFIX, isCindyAvatarSentinel };--/** Registered hue family. Order is stable — hash assignment depends on it. */-export const BOT_AVATAR_HUES = [- 'red',- 'orange',- 'amber',- 'green',- 'teal',- 'blue',- 'violet',- 'pink',- 'graphite',-] as const;--export type BotAvatarHue = (typeof BOT_AVATAR_HUES)[number];+// Hue and initial are shared with the main process (Agent Island) and re-exported here.+export { BOT_AVATAR_HUES, botAvatarHueForSeed, botAvatarInitial, normalizeBotAvatarHue, type BotAvatarHue };const HUE_TOKENS: Record<BotAvatarHue, string> = {red: 'var(--bot-avatar-red-bg)',@@ -83,20 +77,6 @@ const SIZE_CLASSES = {export type BotAvatarSize = keyof typeof SIZE_CLASSES;-/** FNV-1a over UTF-16 code units: stable across runs, platforms and locales. */-function hashSeed(seed: string): number {- let hash = 0x811c9dc5;- for (let index = 0; index < seed.length; index += 1) {- hash ^= seed.charCodeAt(index);- hash = Math.imul(hash, 0x01000193) >>> 0;- }- return hash >>> 0;-}--export function botAvatarHueForSeed(seed: string): BotAvatarHue {- return BOT_AVATAR_HUES[hashSeed(seed) % BOT_AVATAR_HUES.length];-}-export interface BotAvatarAssignment {hue: BotAvatarHue;/** Grapheme or reserved sentinel — the same shape as `BotProfile.avatar`. */@@ -113,34 +93,10 @@ export function botAvatarAssignment(seed: string): BotAvatarAssignment {return { hue: botAvatarHueForSeed(seed), emoji: '' };}-export function normalizeBotAvatarHue(value: string | null | undefined): BotAvatarHue {- const candidate = typeof value === 'string' ? value.trim().toLowerCase() : '';- if ((BOT_AVATAR_HUES as readonly string[]).includes(candidate)) return candidate as BotAvatarHue;- // Historical rows only ever stored the four names above, all of which are- // family members. Keep unknown values deterministic rather than defaulting- // every one of them to a single hue.- if (!candidate) return 'violet';- return botAvatarHueForSeed(candidate);-}-export function botAvatarHueToken(value: string | null | undefined): string {return HUE_TOKENS[normalizeBotAvatarHue(value)];}-/** First grapheme of the name, uppercased — the fallback when avatar is empty. */-export function botAvatarInitial(name: string | null | undefined): string {- const trimmed = (name ?? '').trim();- if (!trimmed) return '?';- const segmenter =- typeof Intl !== 'undefined' && 'Segmenter' in Intl- ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })- : null;- const first = segmenter- ? (segmenter.segment(trimmed)[Symbol.iterator]().next().value?.segment ?? '')- : (Array.from(trimmed)[0] ?? '');- return first.toUpperCase();-}-export interface BotAvatarProps {/** Bot-shaped source; only these three fields are read. */bot: { avatarUrl?: string | null; deviceId?: string; name: string; avatar?: string | null; avatarColor?: string | null };diff --git a/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx b/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsxindex 6efd0aa2c9..d2b9cdacc3 100644--- a/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx+++ b/apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx@@ -3,7 +3,7 @@ import * as Popover from '@radix-ui/react-popover';import { useEffect, useRef, useState, type ReactElement, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { Camera, Check, ChevronDown, Plus } from 'lucide-react';-import cindyPortrait from '@/assets/bot-presets/cindy.png';+import cindyPortrait from '../../../../resources/companion-preset-avatars/cindy.png';import { Tip } from '@/components/ui/tooltip';import gallery from '../../../../resources/teammate-portrait-gallery.png';import { BOT_AVATAR_MAX_BYTES } from '../../../shared/botAvatarValue';diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex dae4aa672d..df44dcfbf3 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -1,5 +1,6 @@import { BRAND_NAME } from '@cindy/maker-shared/branding';import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';+import type { BotAvatarHue } from './botAvatarHue.js';export type AgentIslandSessionPhase = 'running' | 'needs-interaction' | 'completed' | 'error';@@ -20,6 +21,23 @@ export interface AgentIslandActivityLine {text: string;}+/**+ * The companion a Bot Session speaks for. The island draws this identity instead+ * of the task's title, working directory and agent mark.+ */+export interface AgentIslandCompanionSnapshot {+ name: string;+ /** Group the member speaks in; absent for the companion's own chat. */+ groupName?: string;+ /** BotAvatar hue family member; the island resolves it to its dark tint. */+ hue: BotAvatarHue;+ /** Bounded JPEG thumbnail (base64) when the companion has artwork. */+ imageJpeg?: string;+ /** Emoji, or the name's initial, painted when there is no artwork. */+ glyph: string;+ glyphIsInitial: boolean;+}+/*** Renderer-facing session snapshot for the macOS Agent Island overlay.*/@@ -28,6 +46,7 @@ export interface AgentIslandSessionSnapshot {completionNotification?: 'silent';sessionId: string;title: string;+ companion?: AgentIslandCompanionSnapshot;projectName: string | null;detail: string;compactDetail: string;diff --git a/apps/desktop/src/shared/botAvatarHue.ts b/apps/desktop/src/shared/botAvatarHue.tsnew file mode 100644index 0000000000..14ef91afdb--- /dev/null+++ b/apps/desktop/src/shared/botAvatarHue.ts@@ -0,0 +1,59 @@+/**+ * Bot avatar hue and initial — the asset-free half of BotAvatar, shared so the+ * main process can paint the same identity mark outside the renderer (the macOS+ * Agent Island). Colors stay with their consumers: the renderer resolves the+ * registered `--bot-avatar-*-bg` tokens, the native island its own dark palette.+ */++/** Registered hue family. Order is stable — hash assignment depends on it. */+export const BOT_AVATAR_HUES = [+ 'red',+ 'orange',+ 'amber',+ 'green',+ 'teal',+ 'blue',+ 'violet',+ 'pink',+ 'graphite',+] as const;++export type BotAvatarHue = (typeof BOT_AVATAR_HUES)[number];++/** FNV-1a over UTF-16 code units: stable across runs, platforms and locales. */+function hashSeed(seed: string): number {+ let hash = 0x811c9dc5;+ for (let index = 0; index < seed.length; index += 1) {+ hash ^= seed.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash >>> 0;+}++export function botAvatarHueForSeed(seed: string): BotAvatarHue {+ return BOT_AVATAR_HUES[hashSeed(seed) % BOT_AVATAR_HUES.length];+}++export function normalizeBotAvatarHue(value: string | null | undefined): BotAvatarHue {+ const candidate = typeof value === 'string' ? value.trim().toLowerCase() : '';+ if ((BOT_AVATAR_HUES as readonly string[]).includes(candidate)) return candidate as BotAvatarHue;+ // Historical rows only ever stored the four names above, all of which are+ // family members. Keep unknown values deterministic rather than defaulting+ // every one of them to a single hue.+ if (!candidate) return 'violet';+ return botAvatarHueForSeed(candidate);+}++/** First grapheme of the name, uppercased — the fallback when avatar is empty. */+export function botAvatarInitial(name: string | null | undefined): string {+ const trimmed = (name ?? '').trim();+ if (!trimmed) return '?';+ const segmenter =+ typeof Intl !== 'undefined' && 'Segmenter' in Intl+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })+ : null;+ const first = segmenter+ ? (segmenter.segment(trimmed)[Symbol.iterator]().next().value?.segment ?? '')+ : (Array.from(trimmed)[0] ?? '');+ return first.toUpperCase();+}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex c7d39c81d8..327c238ed5 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -606,6 +606,10 @@ Session 任务遵守同一套机制与呈现契约:- 通知、灵动岛与任务深链点击立即按内存里的伙伴投影跳转,不等待重读伙伴列表。投影还不认识的任务先打开普通任务页,同时在后台重读一次投影;若它其实是伙伴的主任务、历史或群专线,再转到对应页面——前提是用户这期间没有去过别处(离开后又回来也算)。新挂上的伙伴任务因此可能先短暂显示普通任务页,换来普通任务点击即达。+- macOS 灵动岛把伙伴的主任务、历史任务、群专线与渠道任务显示为伙伴本人:名字与头像代替任务标题和+ Agent 标识,群专线在名字后附群名,不显示伙伴工作目录;回复完成时以消息样式呈现(头像跨两行、+ 不标「完成」),运行中、待处理、报错与未读回复由头像上的光环和角标表示。委派执行仍是普通任务。+ 伙伴改名或换头像后灵动岛立即更新;头像只在本机生成有界缩略图,读不到时回退底色加 emoji 或名字首字。- iOS 的伙伴正常回复使用系统通信通知:伙伴名字、头像与回复摘要,应用角标由系统绘制。普通任务、报错和待处理事项保留原通知语义。头像仅携带有界缩略图、内置头像标识或单个字符,不上传公开头像地址;缺失头像回退名字首字,扩展失败仍交付原通知。