Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 将本群头像与账号头像隔离
nanac6ebef57191d
diff --git a/apps/desktop/scripts/fixtures/group-avatar/group-avatar-fixture.tsx b/apps/desktop/scripts/fixtures/group-avatar/group-avatar-fixture.tsxnew file mode 100644index 0000000000..380ff5f316--- /dev/null+++ b/apps/desktop/scripts/fixtures/group-avatar/group-avatar-fixture.tsx@@ -0,0 +1,23 @@+import { mountPage, forbid } from '../../ui-page/harness';+import { ChatGroupSettings } from '../../../src/renderer/features/bots/ChatGroupSettings';+import type { BotGroupSummary } from '../../../src/shared/botGroupChat';++const group = {+ id: 'group-avatar-fixture', name: 'Design team', serverBacked: true, supportsMemberAvatar: true,+ revision: 1, replyMode: 'all', speakingMode: 'auto', selfActorId: 'me',+ members: [+ { actorId: 'me', botId: 'me', actorKind: 'human', isSelf: true, isOwned: true,+ name: 'Nana', displayName: 'Nana', role: 'member', groupAvatar: null, avatarUrl: null },+ { actorId: 'peer', botId: 'peer', actorKind: 'human', name: 'Alex', displayName: 'Alex', role: 'owner' },+ ],+} as BotGroupSummary;++mountPage({+ route: '/bots/groups/group-avatar-fixture',+ host: {+ maker: { chatServer: { ownedBots: async () => ({ ok: true, bots: [] }), manage: forbid('chatServer.manage') } },+ profileGetState: forbid('profileGetState'),+ profileUpdate: forbid('profileUpdate'),+ },+ render: () => <ChatGroupSettings group={group} />,+});diff --git a/apps/desktop/scripts/fixtures/group-avatar/ui-page.mjs b/apps/desktop/scripts/fixtures/group-avatar/ui-page.mjsnew file mode 100644index 0000000000..2c2f0b5140--- /dev/null+++ b/apps/desktop/scripts/fixtures/group-avatar/ui-page.mjs@@ -0,0 +1,23 @@+import assert from 'node:assert/strict';++export default {+ name: 'group-avatar',+ entry: './group-avatar-fixture.tsx',+ viewport: { width: 560, height: 900 },+ real: 'ChatGroupSettings and ProfileEditDialog, real controls, translations and Light/Dark themes',+ notCovered: 'Real login, image uploads, server persistence and mobile rendering; network and stores use fixture data',+ stubs: {+ 'src/renderer/features/bots/botStore': 'export const useBotProfiles = () => [];',+ 'src/renderer/features/bots/botGroupStore': 'export const refreshBotGroups = () => {};',+ 'src/renderer/features/bots/ChatServerControls': 'export const chatErrorKey = () => "bots.groupChat.server.requestFailed";',+ },+ cases: { default: { about: 'Group-only avatar editor, without account profile controls' } },+ async check(page, ui) {+ const key = 'bots.groupChat.server.settings.';+ const edit = page.getByRole('button', { name: await ui.t(key + 'groupAvatar'), exact: true });+ await edit.click();+ await page.getByText(await ui.t(key + 'groupAvatarHint'), { exact: true }).waitFor();+ assert.equal(await page.getByRole('alertdialog').getByRole('textbox').count(), 0);+ await ui.capture('group-avatar-dialog');+ },+};diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 4c4018532f..0676c2f4b3 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -1,4 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+const avatarUpload = vi.hoisted(() => vi.fn());+vi.mock('../../ossPublicUpload.js', () => ({ uploadPublicAsset: avatarUpload }));const fixture = vi.hoisted(() => ({ upload: vi.fn(async (): Promise<unknown[]> => []), download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[], token: 'isolated-test-token', refresh: vi.fn(async () => true), requests: [] as Array<{ url: string; token: string; actor?: string }> }));vi.mock('../../authManager.js', () => ({ getAccessToken: () => fixture.token, refresh: fixture.refresh }));vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));@@ -15,7 +17,8 @@ vi.mock('../botGroupTaskPostSnapshot.js', () => ({ prepareBotGroupTaskPost: asynvi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));const migration = vi.hoisted(() => ({ read: vi.fn<(_groupId: string) => { roomId: string; sequence: number; version: 2 } | null>(() => null) }));vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: migration.read, save: vi.fn() }) }));-vi.mock('electron', () => ({ app: { get isPackaged() { return fixture.packaged; }, getPath: () => '/isolated' } }));+vi.mock('electron', () => ({ app: { get isPackaged() { return fixture.packaged; }, getPath: () => '/isolated' },+ nativeImage: { createFromBuffer: () => ({ isEmpty: () => false, getSize: () => ({ width: 1, height: 1 }) }) } }));// The real filesystem, except an `lstat` failure a test injects for a delivery file.const fsFault = vi.hoisted(() => ({ lstat: null as Error | null }));vi.mock('node:fs/promises', async (importOriginal) => {@@ -163,6 +166,45 @@ describe('Chat Server result delivery and refresh', () => {await service.updateGroup({ groupId: roomId, name: 'Draft', expectedRevision: 7 });expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}`, 'PATCH', expect.objectContaining({ name: 'Draft', expectedRevision: 7 }));});+ // Group avatar regression: exercise the production manage entry, real image+ // validation and HTTP payload, with only the network/image decoder faked.+ it.each(['set', 'reset', 'keep', 'invalid', 'unsupported', 'upload-failure', 'account-change'] as const)(+ 'keeps group avatar %s scoped to the current room and account', async mode => {+ let currentAccount = true;+ service.dispose();+ deps.captureOwnerScope = () => ({}) as ReturnType<NonNullable<typeof deps.captureOwnerScope>>;+ deps.isOwnerScopeCurrent = () => currentAccount;+ service = withChatServer({ listGroups: async () => ({ ok: true, groups: [] }), dispose: vi.fn() } as unknown as BotGroupChatService, deps);+ fixture.handle.mockImplementation(route => {+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupMemberAvatar: mode === 'unsupported' ? undefined : 1 } } };+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members: [+ { id: selfId, kind: 'human', name: 'Me', displayName: 'Account me', ownerActorId: selfId, state: 'joined', role: 'owner',+ avatar: 'https://example.com/group.png', groupAvatar: 'https://example.com/group.png', defaultAvatarUrl: 'https://example.com/account.png' },+ ], messages: [], cursor: '1' } };+ return response(route);+ });+ avatarUpload.mockImplementation(async () => {+ if (mode === 'account-change') currentAccount = false;+ return mode === 'upload-failure' ? { ok: false, stage: 'put', status: 500 }+ : { ok: true, publicUrl: 'https://example.com/new-group.png' };+ });+ const bytes = new Uint8Array(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6sQAAAABJRU5ErkJggg==', 'base64'));+ const avatar = mode === 'reset' || mode === 'keep' ? { type: mode }+ : { type: 'set' as const, data: mode === 'invalid' ? new Uint8Array([1]) : bytes, mimeType: 'image/png' };+ const result = await service.chatServer!.manage({ groupId: roomId, action: { type: 'avatar', actorId: selfId, avatar } });+ const writes = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/nickname` && method === 'POST');+ if (mode === 'set' || mode === 'reset') {+ expect(result).toEqual({ ok: true });+ expect(writes).toEqual([[`/conversations/${roomId}/nickname`, 'POST', {+ operationId: expect.any(String), actorId: selfId, avatar: mode === 'reset' ? null : 'https://example.com/new-group.png',+ }]]);+ } else {+ expect(writes).toEqual([]);+ expect(result.ok).toBe(mode === 'keep');+ }+ if (['keep', 'reset', 'invalid', 'unsupported'].includes(mode)) expect(avatarUpload).not.toHaveBeenCalled();+ expect(fixture.urls.some(url => url.includes('/api/me/profile'))).toBe(false);+ });it('preserves a server revision conflict after the host precheck', async () => {fixture.handle.mockImplementation((route, method) => method === 'PATCH'? { status: 409, body: { error: { code: 'REVISION_CONFLICT', message: 'private server detail' } } }diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex e579a5c70d..c131dc7eaf 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1,7 +1,8 @@import { createConversationListState } from '@cindy/maker-shared/chatConversationList';/** Production chat transport. The server owns messages and execution leases;* local group rows only supply Agent lane metadata and the upgrade source. */-import { app, net } from 'electron';+import { app, net, nativeImage } from 'electron';+import { validateAvatarUpload } from '../profileEdit.js';import { uploadPublicAsset } from '../ossPublicUpload.js';import { getClientEndpoint } from '../clientEndpointsService.js';import { t } from '../i18n.js';@@ -53,7 +54,7 @@ import { DIRECT_ROOM_COMPLETION, deliverDirectRoomMessage, directRoomClientId }interface Actor { id: string; kind: string; externalId: string; name: string; avatar?: string | null; avatarSource?: string | null; homeDeviceId?: string | null; disabled?: boolean }interface Member { id: string; kind: 'human' | 'bot' | 'integration'; name: string; state: string; role: 'owner' | 'admin' | 'member' | 'guest';- displayName: string; avatar: string | null; nickname: string | null; ownerActorId: string; ownerName: string;+ displayName: string; avatar: string | null; groupAvatar?: string | null; defaultAvatarUrl?: string | null; nickname: string | null; ownerActorId: string; ownerName: string;guestAccess: 'none' | 'chat' | 'tools'; accessRevision: number }interface Message {id: string; seq: string; authorId: string; replyCount?: number; reactions?: Array<{ emoji: string; count: number; me: boolean }>; author: { kind: string; name: string };@@ -323,6 +324,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet selfId = '';let supportsDissolve = false;let supportsListRemoval = false;+ let supportsMemberAvatar = false;const personalList = createConversationListState();const syncPersonalList = async (force = false) => {if (supportsListRemoval) await (force ? personalList.sync(api) : personalList.ensureSynced(api));@@ -738,9 +740,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDrefreshActors = (async () => {actorsStale = false;profiles = await getDbClient().drizzle.select().from(botProfiles).where(undefined);- const me = await api<{ actor: Actor; deviceId?: string | null; capabilities?: { groupDiscussionParity?: number; groupSingleSpeaker?: number; companionHome?: boolean; directRoomClaim?: boolean; groupLifecycleVersion?: number; conversationListStateVersion?: number } }>('/me'); selfId = me.actor.id;+ const me = await api<{ actor: Actor; deviceId?: string | null; capabilities?: { groupDiscussionParity?: number; groupSingleSpeaker?: number; companionHome?: boolean; directRoomClaim?: boolean; groupLifecycleVersion?: number; conversationListStateVersion?: number; groupMemberAvatar?: number } }>('/me'); selfId = me.actor.id;supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;+ supportsMemberAvatar = me.capabilities?.groupMemberAvatar === 1;groupDiscussionParity = me.capabilities?.groupDiscussionParity === 1;singleSpeaker = me.capabilities?.groupSingleSpeaker === 1;selfDeviceId = typeof me.deviceId === 'string' && me.deviceId ? me.deviceId : null;@@ -1303,17 +1306,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst lastView = last ? messageView(last, s.members) : null;// The sidebar never resolves shares: it names the sharer and never quotes the card's text.const lastIsShare = !!last && !!readBotGroupThreadShareCard(last);- return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: true, supportsDissolve, supportsListRemoval, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: singleSpeaker && !!managementActor(s), ...(singleSpeaker ? { singleSpeaker: true } : {}), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,+ return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: true, supportsDissolve, supportsListRemoval, supportsMemberAvatar, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: singleSpeaker && !!managementActor(s), ...(singleSpeaker ? { singleSpeaker: true } : {}), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,members: s.members.filter(m => m.state === 'joined').map(m => {const p = localBot(m.id);return { botId: p?.id ?? m.id, actorId: m.id, actorKind: m.kind, isSelf: m.id === selfId,- role: m.role, nickname: m.nickname, displayName: m.displayName, ownerActorId: m.ownerActorId, ownerName: m.ownerName,+ role: m.role, nickname: m.nickname, groupAvatar: m.groupAvatar ?? null, defaultAvatarUrl: m.defaultAvatarUrl ?? null, displayName: m.displayName, ownerActorId: m.ownerActorId, ownerName: m.ownerName,isOwned: m.ownerActorId === selfId, guestAccess: m.guestAccess, accessRevision: m.accessRevision,// Which computer runs my companion: a phone reaching this group through this computer// reads the companion's tasks there, not here (bot-group-chat.md §10)....(m.ownerActorId === selfId && m.kind === 'bot' ? { homeDeviceId: actors.find(a => a.id === m.id)?.homeDeviceId ?? null } : {}),avatarUrl: m.avatar?.startsWith('https://') ? m.avatar : null,- name: memberName(m), avatar: p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };+ name: memberName(m), avatar: m.groupAvatar ? '' : p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };}), organizerBotId: s.room.organizer_id ? localBot(s.room.organizer_id)?.id ?? s.room.organizer_id : s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id ?? null, projectDir: workspace?.projectDir ?? null, lastMessage: last && lastView ? {isSelf: lastView.isSelf, authorKind: lastView.authorKind, authorName: lastView.authorName, noticeCode: lastView.noticeCode,preview: lastIsShare ? '' : (botGroupMessageSummaryText(lastView) || mediaNames(last)).slice(0, 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),@@ -2160,6 +2163,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst actorAction = z.object({ actorId: id });const action = z.discriminatedUnion('type', [z.object({ type: z.literal('update'), name: z.string().trim().min(1).max(40), topic: z.string().max(250), description: z.string().max(2000), responseMode: z.enum(['all', 'mentioned']).optional(), speakingMode: z.enum(['auto', 'sequential']).optional(), expectedRevision: z.number().int().positive() }).strict(),+ actorAction.extend({ type: z.literal('avatar'), avatar: z.discriminatedUnion('type', [+ z.object({ type: z.literal('keep') }).strict(), z.object({ type: z.literal('reset') }).strict(),+ z.object({ type: z.literal('set'), data: z.instanceof(Uint8Array), mimeType: z.string() }).strict(),+ ]) }).strict(),actorAction.extend({ type: z.literal('nickname'), nickname: z.string().trim().max(40).nullable() }).strict(),actorAction.extend({ type: z.literal('member'), action: z.enum(['invite', 'leave', 'remove', 'ban', 'unban', 'role']), role: z.enum(['admin', 'member']).optional() }).strict(),actorAction.extend({ type: z.literal('transfer') }).strict(),@@ -2168,6 +2175,29 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDz.object({ type: z.literal('dissolve'), expectedRevision: z.number().int().positive() }).strict(),z.object({ type: z.literal('archive'), archived: z.boolean(), expectedRevision: z.number().int().positive() }).strict(),]).parse(input.action);+ if (action.type === 'avatar') {+ if (!supportsMemberAvatar) throw new Error('CHAT_UNAVAILABLE');+ const snapshot = await groupSnapshot(target);+ const member = snapshot.members.find(m => m.id === action.actorId && m.state === 'joined');+ if (!member || (member.id !== selfId && member.ownerActorId !== selfId)) throw new Error('ACTOR_NOT_OWNED');+ if (action.avatar.type === 'keep') return {};+ let avatar: string | null = null;+ if (action.avatar.type === 'set') {+ validateAvatarUpload(action.avatar, ({ buffer }) => {+ const image = nativeImage.createFromBuffer(Buffer.from(buffer));+ return image.isEmpty() ? null : image.getSize();+ });+ if (!current()) throw new Error('OWNER_CHANGED');+ const uploaded = await uploadPublicAsset({ fetchImpl: (input, init) => net.fetch(input, init),+ getBaseUrl: () => getClientEndpoint('ossApiBaseUrl'), getToken: () => current() ? getAccessToken() : null },+ { scene: 'avatar', contentType: action.avatar.mimeType, body: action.avatar.data });+ if (!current()) throw new Error('OWNER_CHANGED');+ if (!uploaded.ok) throw new Error('PROFILE_AVATAR_UPLOAD_FAILED');+ avatar = uploaded.publicUrl;+ }+ await api(`/conversations/${target}/nickname`, 'POST', { operationId: randomUUID(), actorId: action.actorId, avatar });+ changed(target); return {};+ }if (action.type === 'hide') {if (!supportsListRemoval) throw new Error('LIFECYCLE_UNAVAILABLE');// Deliberately no snapshot read: historical members can remove after leaving.diff --git a/apps/desktop/src/main/profileEdit.ts b/apps/desktop/src/main/profileEdit.tsindex 81e25ea22f..1a9e4b7a20 100644--- a/apps/desktop/src/main/profileEdit.ts+++ b/apps/desktop/src/main/profileEdit.ts@@ -260,6 +260,37 @@ export async function chooseAvatarFile(deps: ProfileEditDeps): Promise<ChooseAva};}+/** Validate cropped avatar bytes before either account or group upload. */+export function validateAvatarUpload(+ { data, mimeType }: Extract<AvatarAction, { type: 'set' }>,+ decodeAvatarImage: ProfileEditDeps['decodeAvatarImage'],+): void {+ if (data.byteLength === 0 || data.byteLength > AVATAR_MAX_BYTES) {+ throwIpcError('INVALID_PARAMS', `avatar data size out of range: ${data.byteLength}`);+ }+ if (!avatarBytesMatchMime(data, mimeType)) {+ throwIpcError('INVALID_PARAMS', `avatar data does not match type: ${mimeType}`);+ }+ // renderer 不是安全边界:先按文件头限尺寸,再在 main 完整解码,尺寸一致才上传。+ const declared = readAvatarDimensions(data, mimeType);+ if (+ !declared ||+ declared.width < 1 ||+ declared.height < 1 ||+ declared.width > AVATAR_UPLOAD_MAX_EDGE_PX ||+ declared.height > AVATAR_UPLOAD_MAX_EDGE_PX+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ `avatar dimensions out of range: ${declared ? `${declared.width}x${declared.height}` : '<unreadable>'}`,+ );+ }+ const decoded = decodeAvatarImage({ buffer: data, mimeType });+ if (!decoded || decoded.width !== declared.width || decoded.height !== declared.height) {+ throwIpcError('INVALID_PARAMS', 'avatar data failed to decode');+ }+}+/*** 保存资料:name 与 avatar 各自收敛成 PATCH 字段,一次提交服务端。* - name:trim 后为空或与当前一致 → 不改;否则 displayName;@@ -303,30 +334,7 @@ export async function updateProfile(let nextAvatarUrl: string | null | undefined;if (avatarAction.type === 'set') {const { data, mimeType } = avatarAction;- if (data.byteLength === 0 || data.byteLength > AVATAR_MAX_BYTES) {- throwIpcError('INVALID_PARAMS', `avatar data size out of range: ${data.byteLength}`);- }- if (!avatarBytesMatchMime(data, mimeType)) {- throwIpcError('INVALID_PARAMS', `avatar data does not match type: ${mimeType}`);- }- // renderer 不是安全边界:先按文件头限尺寸,再在 main 完整解码,尺寸一致才上传。- const declared = readAvatarDimensions(data, mimeType);- if (- !declared ||- declared.width < 1 ||- declared.height < 1 ||- declared.width > AVATAR_UPLOAD_MAX_EDGE_PX ||- declared.height > AVATAR_UPLOAD_MAX_EDGE_PX- ) {- throwIpcError(- 'INVALID_PARAMS',- `avatar dimensions out of range: ${declared ? `${declared.width}x${declared.height}` : '<unreadable>'}`,- );- }- const decoded = deps.decodeAvatarImage({ buffer: data, mimeType });- if (!decoded || decoded.width !== declared.width || decoded.height !== declared.height) {- throwIpcError('INVALID_PARAMS', 'avatar data failed to decode');- }+ validateAvatarUpload(avatarAction, deps.decodeAvatarImage);requireSameAccount(deps, accountScope);const uploaded = await deps.uploadAvatar({ buffer: data, mimeType });if (!uploaded.ok) {diff --git a/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx b/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsxindex 7f64ba4762..228acfb320 100644--- a/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx@@ -36,6 +36,13 @@ import {interface ProfileEditDialogProps {open: boolean;onOpenChange: (open: boolean) => void;+ /** Explicit group destination; no account reads or writes in this mode. */+ avatarEditor?: {+ title: string;+ hint: string;+ getState(): Promise<ProfileState>;+ save(avatar: Parameters<Window['electronAPI']['profileUpdate']>[0]['avatar']): Promise<void>;+ };}type AvatarDraft =@@ -60,12 +67,13 @@ interface CropSession {interface ProfileState {name: string;avatarUrl: string | null;+ defaultAvatarUrl?: string | null;}// Tooltip 默认 z-[60],会被 z-[10000] 的弹窗盖住(DESIGN §4 Dialog & Modal)。const DIALOG_TIP_CLASS = 'z-[10001]';-export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogProps) {+export function ProfileEditDialog({ open, onOpenChange, avatarEditor }: ProfileEditDialogProps) {const { t } = useTranslation();const [state, setState] = useState<ProfileState | null>(null);const [name, setName] = useState('');@@ -145,8 +153,8 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropssetAvatarDraft({ type: 'keep' });}, [endCropSession, setAvatarDraft]);- // 打开时拉预填数据并复位草稿(异步取数期间不渲染内容,避免半空帧;- // 数据都在本地 main,毫秒级返回,无需 loading 态 —— 规则 7)。+ // 打开时拉预填数据;群资料刷新只更新默认值,保留正在编辑的头像。+ // 草稿由关闭 / 卸载清理;切换群时父组件通过 key 重新挂载编辑器。useEffect(() => {if (!open) {chooseGenerationRef.current += 1;@@ -156,13 +164,11 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogProps}setStepSwitched(false);let stale = false;- void window.electronAPI- .profileGetState()+ void (avatarEditor ? avatarEditor.getState() : window.electronAPI.profileGetState()).then((s) => {if (stale) return;setState(s);setName(s.name);- releaseAll();}).catch(() => {if (!stale) onOpenChange(false);@@ -170,7 +176,7 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropsreturn () => {stale = true;};- }, [open, onOpenChange, releaseAll]);+ }, [open, onOpenChange, releaseAll, avatarEditor]);useEffect(() => () => {@@ -256,13 +262,11 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropstry {const trimmed = name.trim();const draft = draftRef.current;- await window.electronAPI.profileUpdate({- name: trimmed === '' ? null : trimmed,- avatar:- draft.type === 'set'- ? { type: 'set', data: draft.exported.bytes, mimeType: draft.exported.mimeType }- : { type: draft.type },- });+ const avatar = draft.type === 'set'+ ? { type: 'set' as const, data: draft.exported.bytes, mimeType: draft.exported.mimeType }+ : { type: draft.type };+ if (avatarEditor) await avatarEditor.save(avatar);+ else await window.electronAPI.profileUpdate({ name: trimmed === '' ? null : trimmed, avatar });savingRef.current = false;setSaving(false);onOpenChange(false);@@ -271,7 +275,7 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropssetSaving(false);toast.error(t('settings.userProfile.edit.saveFailed'));}- }, [state, name, onOpenChange, t]);+ }, [state, name, onOpenChange, t, avatarEditor]);if (!state) return null;@@ -319,8 +323,8 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropsavatarDraft.type === 'set'? avatarDraft.previewUrl: avatarDraft.type === 'reset'- ? null- : state.avatarUrl;+ ? state.defaultAvatarUrl ?? null+ : state.avatarUrl ?? state.defaultAvatarUrl ?? null;const effectiveName =name.trim() !== '' ? name.trim() : state.name || t('settings.userProfile.fallbackName');const initial = effectiveName.charAt(0).toUpperCase();@@ -336,7 +340,7 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogProps<ConfirmDialogopen={open}onOpenChange={handleOpenChange}- title={t('settings.userProfile.edit.title')}+ title={avatarEditor?.title ?? t('settings.userProfile.edit.title')}confirmText={t('settings.userProfile.edit.save')}cancelText={t('settings.userProfile.edit.cancel')}autoFocusConfirm@@ -407,7 +411,7 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogProps</div>{/* 名字行:预填当前名字,留空 = 不改名 */}- <label className="flex flex-col gap-1.5">+ {!avatarEditor && <label className="flex flex-col gap-1.5"><span className="text-12 text-[var(--text-secondary)]">{t('settings.userProfile.edit.nameLabel')}</span>@@ -426,11 +430,11 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogProps<span className="text-11 text-[var(--text-tertiary)]">{t('settings.userProfile.edit.nameHint')}</span>- </label>+ </label>}{/* 资料跨设备同步的透明化说明 */}<p className="text-11 leading-relaxed text-[var(--text-tertiary)]">- {t('settings.userProfile.edit.syncHint')}+ {avatarEditor?.hint ?? t('settings.userProfile.edit.syncHint')}</p></div>}diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ProfileEditDialog.avatarCrop.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ProfileEditDialog.avatarCrop.test.tsxindex b0f83cf337..cd67ca1e75 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/ProfileEditDialog.avatarCrop.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/ProfileEditDialog.avatarCrop.test.tsx@@ -96,6 +96,81 @@ afterEach(() => {});describe('ProfileEditDialog 头像调整', () => {+ // Regression: a group editor must never load or save the global account profile.+ // Existing crop tests cover only account editing; this exercises the same real+ // dialog with a group-scoped destination (unit/jsdom).+ it('saves a cropped group avatar without reading or writing the account profile', async () => {+ const avatarEditor = {+ title: 'Group avatar', hint: 'Only this group',+ getState: vi.fn(async () => ({ name: 'Group me', avatarUrl: 'https://example.com/group.png', defaultAvatarUrl: 'https://example.com/account.png' })),+ save: vi.fn(async () => {}),+ };+ render(<ProfileEditDialog open onOpenChange={vi.fn()} avatarEditor={avatarEditor} />);+ await screen.findByText('Group avatar');+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(api.profileGetState).not.toHaveBeenCalled();+ await chooseImage();+ fireEvent.click(screen.getByRole('button', { name: 'settings.userProfile.edit.crop.done' }));+ fireEvent.click(await screen.findByRole('button', { name: 'settings.userProfile.edit.save' }));+ await waitFor(() => expect(avatarEditor.save).toHaveBeenCalledWith({ type: 'set', data: EXPORTED, mimeType: 'image/jpeg' }));+ expect(api.profileUpdate).not.toHaveBeenCalled();+ });++ // Review regression (unit/jsdom): existing group tests never refreshed member+ // metadata mid-edit. A new nickname must not discard the crop or saved draft.+ it.each(['cropping', 'preview'] as const)('preserves the group avatar during %s when member metadata refreshes', async (step) => {+ const onOpenChange = vi.fn();+ const save = vi.fn(async () => {});+ const editor = (name: string) => ({+ title: 'Group avatar', hint: 'Only this group', save,+ getState: async () => ({ name, avatarUrl: 'https://example.com/group.png', defaultAvatarUrl: null }),+ });+ const view = render(<ProfileEditDialog open onOpenChange={onOpenChange} avatarEditor={editor('Before')} />);+ await chooseImage();+ if (step === 'preview') {+ fireEvent.click(screen.getByRole('button', { name: 'settings.userProfile.edit.crop.done' }));+ await screen.findByRole('button', { name: 'settings.userProfile.edit.save' });+ }++ const refreshed = editor('After');+ view.rerender(<ProfileEditDialog open onOpenChange={onOpenChange} avatarEditor={refreshed} />);+ await act(async () => {});+ expect(source.bitmap.close).not.toHaveBeenCalled();+ if (step === 'cropping') {+ expect(screen.getByRole('group', { name: 'settings.userProfile.edit.crop.stageLabel' })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'settings.userProfile.edit.crop.done' }));+ await screen.findByRole('button', { name: 'settings.userProfile.edit.save' });+ }+ expect((screen.getByRole('img') as HTMLImageElement).src).toBe('blob:avatar-1');+ fireEvent.click(screen.getByRole('button', { name: 'settings.userProfile.edit.save' }));+ await waitFor(() => expect(save).toHaveBeenCalledWith({ type: 'set', data: EXPORTED, mimeType: 'image/jpeg' }));+ expect(api.profileUpdate).not.toHaveBeenCalled();++ // Closing still releases the draft; reopening starts with server data.+ view.rerender(<ProfileEditDialog open={false} onOpenChange={onOpenChange} avatarEditor={refreshed} />);+ expect(source.bitmap.close).toHaveBeenCalledTimes(1);+ view.rerender(<ProfileEditDialog open onOpenChange={onOpenChange} avatarEditor={refreshed} />);+ await act(async () => {});+ expect((screen.getByRole('img') as HTMLImageElement).src).toBe('https://example.com/group.png');+ });++ it('previews the account avatar on group reset and keeps the editor open if saving fails', async () => {+ const onOpenChange = vi.fn();+ const avatarEditor = {+ title: 'Group avatar', hint: 'Only this group',+ getState: async () => ({ name: 'Group me', avatarUrl: 'https://example.com/group.png', defaultAvatarUrl: 'https://example.com/account.png' }),+ save: vi.fn(async () => { throw new Error('REQUEST_FAILED'); }),+ };+ render(<ProfileEditDialog open onOpenChange={onOpenChange} avatarEditor={avatarEditor} />);+ fireEvent.click(await screen.findByRole('button', { name: 'settings.userProfile.edit.resetAvatar' }));+ expect((screen.getByRole('img') as HTMLImageElement).src).toBe('https://example.com/account.png');+ fireEvent.click(screen.getByRole('button', { name: 'settings.userProfile.edit.save' }));+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('settings.userProfile.edit.saveFailed'));+ expect(avatarEditor.save).toHaveBeenCalledWith({ type: 'reset' });+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ expect(api.profileUpdate).not.toHaveBeenCalled();+ });+it('选图后进入调整步骤;取消回到表单且不改旧头像,保存不上传', async () => {const { onOpenChange } = renderDialog();await chooseImage();diff --git a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsxindex 25b03b661e..c4398970ea 100644--- a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { ChevronDown, ChevronUp, Crown, Shield } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -83,17 +83,20 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {if (await confirm({ presentation: 'standard', title, description: note, confirmText,cancelText: t('bots.cancel'), confirmVariant: 'destructive' }) && mounted.current && isDataOwnerGenerationCurrent(owner)) await mutate(action, exit);}- const profileOpenChange = useCallback((open: boolean) => {- setEditingProfile(open);- if (!open) {- const owner = getDataOwnerGeneration();- void api().refreshProfile().then(result => {- if (!isDataOwnerGenerationCurrent(owner)) return;- if (!result.ok) setError(t(chatErrorKey(result.errorCode)));- else refreshBotGroups();- }).catch(() => { if (mounted.current && isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); });- }- }, [t]);+ const profileOpenChange = useCallback((open: boolean) => setEditingProfile(open), []);+ const avatarEditor = useMemo(() => ({+ title: t(key('groupAvatar')),+ hint: t(key('groupAvatarHint')),+ getState: async () => ({ name: me?.name ?? '', avatarUrl: me?.groupAvatar ?? null, defaultAvatarUrl: me?.defaultAvatarUrl ?? null }),+ save: async (avatar: Parameters<Window['electronAPI']['profileUpdate']>[0]['avatar']) => {+ if (!me?.actorId) throw new Error('MEMBER_NOT_FOUND');+ const generation = getDataOwnerGeneration();+ const result = await api().manage({ groupId: group.id, action: { type: 'avatar', actorId: me.actorId, avatar } });+ if (!mounted.current || !isDataOwnerGenerationCurrent(generation)) throw new Error('OWNER_CHANGED');+ if (!result.ok) throw new Error(result.errorCode);+ refreshBotGroups();+ },+ }), [group.id, me?.actorId, me?.name, me?.groupAvatar, me?.defaultAvatarUrl, t]);async function updateWorkSettings(input: { organizerBotId?: string; projectDir?: string | null }) {if (busyRef.current) return;busyRef.current = true; setBusy(true); setError('');@@ -154,7 +157,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {<section className="space-y-3 border-t border-[var(--border-default)] pt-5"><div className="flex items-center justify-between gap-3"><h3 className="text-14 font-medium text-[var(--text-primary)]">{t(key('myProfile'))}</h3>- <Button size="sm" variant="secondary" onClick={() => setEditingProfile(true)}>{t(key('editProfile'))}</Button>+ {group.supportsMemberAvatar && <Button size="sm" variant="secondary" disabled={busy || !me || !!group.dissolvedAt} onClick={() => setEditingProfile(true)}>{t(key('groupAvatar'))}</Button>}</div><form className="flex items-end gap-2" onSubmit={event => {event.preventDefault();@@ -230,6 +233,6 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {</div></div></div>- <ProfileEditDialog open={editingProfile} onOpenChange={profileOpenChange} />+ <ProfileEditDialog key={group.id} open={editingProfile} onOpenChange={profileOpenChange} avatarEditor={avatarEditor} /></div>;}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsxindex 7da9c3c21f..40ce96abd5 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx@@ -7,7 +7,9 @@ import type { BotGroupSummary } from '../../../../shared/botGroupChat';const mocks = vi.hoisted(() => ({ manage: vi.fn(), ownedBots: vi.fn(), refresh: vi.fn(), confirm: vi.fn() }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: mocks.confirm }) }));-vi.mock('@/components/settings/ProfileEditDialog', () => ({ ProfileEditDialog: () => null }));+vi.mock('@/components/settings/ProfileEditDialog', () => ({ ProfileEditDialog: ({ open, avatarEditor }: {+ open: boolean; avatarEditor?: { hint: string; save(avatar: { type: 'reset' }): Promise<void> };+}) => open && avatarEditor ? <button onClick={() => void avatarEditor.save({ type: 'reset' })}>{avatarEditor.hint}</button> : null }));vi.mock('../botStore', () => ({ useBotProfiles: () => [{ id: 'bot' }] }));vi.mock('../BotAvatar', () => ({ BotAvatar: () => null }));vi.mock('../botGroupStore', () => ({ refreshBotGroups: mocks.refresh }));@@ -54,6 +56,20 @@ it('keeps a sole archived owner in the group and offers restoring its history',}));});afterEach(cleanup);+// The actual dialog is covered by ProfileEditDialog.avatarCrop.test.tsx.+// Here the real group settings must supply a group destination, never account editing.+it('edits only this member avatar and hides editing on older servers', async () => {+ const view = render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);+ expect(screen.queryByRole('button', { name: key('editProfile') })).toBeNull();+ expect(screen.queryByRole('button', { name: key('groupAvatar') })).toBeNull();+ view.rerender(<MemoryRouter><ChatGroupSettings group={{ ...group(), supportsMemberAvatar: true }} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: key('groupAvatar') }));+ fireEvent.click(screen.getByRole('button', { name: key('groupAvatarHint') }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({+ groupId: 'room', action: { type: 'avatar', actorId: 'me', avatar: { type: 'reset' } },+ }));+ expect(mocks.refresh).toHaveBeenCalledOnce();+});it('lets a member change their own nickname while keeping another owner’s grant read-only', async () => {render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);expect((screen.getByRole('textbox', { name: key('name') }) as HTMLInputElement).disabled).toBe(true);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e5e321e289..a90d4bc26e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9728,7 +9728,9 @@"topic": "Topic","description": "Description","save": "Save",- "myProfile": "My profile",+ "myProfile": "My profile in this group",+ "groupAvatar": "Change group avatar",+ "groupAvatarHint": "Only shown in this group. Your account and other groups stay unchanged. Reset to use your account avatar.","editProfile": "Edit name and photo","nickname": "My name in this group","nicknameHint": "Only shown here. Leave empty to use your profile name.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c634b6c660..6c6f7de92c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9694,7 +9694,9 @@"topic": "トピック","description": "説明","save": "保存",- "myProfile": "自分のプロフィール",+ "myProfile": "このグループでのプロフィール",+ "groupAvatar": "グループ内のアバターを変更",+ "groupAvatarHint": "このグループにのみ表示されます。アカウントや他のグループには影響しません。リセットするとアカウントのアバターに戻ります。","editProfile": "名前と画像を編集","nickname": "このグループでの名前","nicknameHint": "このグループだけに表示。空欄ならプロフィール名を使用します。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 66f9c9d783..e3ff98bed1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9694,7 +9694,9 @@"topic": "주제","description": "설명","save": "저장",- "myProfile": "내 프로필",+ "myProfile": "이 그룹의 내 프로필",+ "groupAvatar": "그룹 아바타 변경",+ "groupAvatarHint": "이 그룹에만 표시되며 계정이나 다른 그룹에는 영향을 주지 않습니다. 초기화하면 계정 아바타를 사용합니다.","editProfile": "이름과 사진 수정","nickname": "이 그룹에서의 이름","nicknameHint": "이 그룹에만 표시됩니다. 비워 두면 프로필 이름을 사용합니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0f0fe7389c..238e9b38b5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9694,7 +9694,9 @@"topic": "群主题","description": "群简介","save": "保存",- "myProfile": "我的资料",+ "myProfile": "我在本群的资料",+ "groupAvatar": "修改本群头像",+ "groupAvatarHint": "仅在本群显示,不影响账号或其他群。恢复默认后使用账号头像。","editProfile": "修改昵称与头像","nickname": "我在本群的昵称","nicknameHint": "仅在本群显示;留空使用个人昵称。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d6cdcbde1a..1e21ff4a49 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9694,7 +9694,9 @@"topic": "群組主題","description": "群組簡介","save": "儲存",- "myProfile": "我的資料",+ "myProfile": "我在本群的資料",+ "groupAvatar": "修改本群頭像",+ "groupAvatarHint": "僅在本群顯示,不影響帳號或其他群。恢復預設後使用帳號頭像。","editProfile": "修改暱稱與頭像","nickname": "我在本群的暱稱","nicknameHint": "僅在本群顯示;留空使用個人暱稱。",diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 43bb327b6d..9b3bbee0fd 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,18 @@# 跨端协议兼容+## 群内独立头像++Chat Server 的 `/me.capabilities` 新增可选 `groupMemberAvatar: 1`;Desktop 的群投影对应+`supportsMemberAvatar`,未声明时不展示换头像入口,也不退回账号头像编辑器。+成员投影沿用 `avatar` 返回当前群的有效头像,并新增可选 `groupAvatar`(可空覆盖值)和+`defaultAvatarUrl`(账号头像)。旧桌面与手机忽略新增字段,沿既有 `avatar` 显示路径读取。+Desktop 既有 `chatServer.manage` 增加 `avatar` action;本机校验裁剪字节后复用 OSS 头像上传,+复用 `POST /conversations/:id/nickname`,仅提交当前成员与可选 `avatar` 公开地址,`null` 恢复账号头像。+该接口的 `nickname` 与 `avatar` 均为可选,至少提供一项;未传的字段保持原值,不回传缓存昵称。+昵称请求的旧字段、空串归一化、响应和幂等摘要保持兼容;不新增头像 HTTP 路由。+不新增 IPC channel 或设备互联权限。新服务端先部署,客户端随后发布;旧客户端在新服务端仍可读,+旧服务端拒绝新 action,不能写入全局账号资料。服务端新增可空列,回滚保留列与已保存头像。+## 限额恢复时间查询既有 `maker:usage:claude-subscription` 请求可选在 providerId 后追加 `true`,表示等待同一余量diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 4b999abd63..7d6aebe4dc 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -485,7 +485,7 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授每次启动或恢复专线时,服务端分工从本机 `sessions.working_dir` 读取创建专线时登记的目录,目录不可用就失败,不依赖旧 `bot_group_plans` 行或回退伙伴 Home。仅聊天授权先于分工目录解析,始终使用与创建期相同的账号/伙伴/授权专线隔离目录和 `dialogue` 类型;即使旧本地计划存在同名 ID,也不能取得其项目目录。创建事务到启动期的回归见 `botGroupLaneTx.test.ts`,旧本地计划目录校验见 `botWorkspaceRuntimePlan.test.ts`。-群主可以是伙伴,主人可代该伙伴管理群;最后群主不能直接退出。个人账号资料、群内昵称、群角色与伙伴归属是四个不同字段,禁止互相覆盖。群内昵称只由本人/伙伴主人修改;个人头像与名字走既有账号服务,Chat Server 只保存受认证的显示投影。+群主可以是伙伴,主人可代该伙伴管理群;最后群主不能直接退出。个人账号资料、群内昵称、群角色与伙伴归属是四个不同字段,禁止互相覆盖。群内昵称只由本人/伙伴主人修改;个人头像与名字走既有账号服务,Chat Server 只保存受认证的显示投影。群成员可另设本群头像,仅覆盖当前群内的显示;未设置或恢复默认时使用最新账号头像,账号资料与其他群不受影响。Desktop 群设置只提供群内昵称与头像,不打开账号资料编辑器;裁剪复用现有编辑器,保存复用群昵称接口的可选头像字段,未传的昵称或头像保持不变。服务端通过 `groupMemberAvatar: 1` 声明支持,旧服务端不展示换头像入口;移动端沿现有成员头像投影显示相同结果。实现与回归见 `ChatGroupSettings.tsx`、`ProfileEditDialog.avatarCrop.test.tsx` 和 `chatServer.test.ts`。发送主群消息或 Thread 回复时,显式点名的每个目标都必须仍是已加入成员。任一目标失效时拒绝发送并保留原输入,不把非空点名列表过滤为空,也不只发送给混合列表里的有效目标。输入框从候选中选过的目标在成员列表刷新后仍保留为本条草稿的点名意图,由发送入口校验;不把离群目标重新放回成员或候选列表。选择记录绑定到正文中的具体点名,编辑时随未改动的点名移动,删除或覆盖该点名时清除,不被另一个同名点名继承。删除正文里的点名后,草稿恢复普通消息规则。伙伴名字与「所有人」的叫法(含 Thread 的 all/everyone)相同时,从候选选中的仍只点名该伙伴;只有选「所有人」一项或手打该叫法才点名所有人。校验后到消息提交之间的成员变化仍由服务端按原始点名与最新授权处理;Thread 回复会由宿主将仍在群中的根消息伙伴作者加入接收人,并与显式点名去重;根消息中的文字和名字不产生额外接收人。回归见 `chatServer.test.ts`、`BotGroupChatView.test.tsx` 与 `ChatServerControls.test.tsx`。diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex 3f3b502a62..010e8f44d4 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -129,6 +129,9 @@ export interface BotGroupMemberView {/** The computer running this owned companion (its Chat Server actor home); live task cards read there. */homeDeviceId?: string | null;avatarUrl?: string | null;+ /** Explicit group-only override; null follows the account avatar. */+ groupAvatar?: string | null;+ defaultAvatarUrl?: string | null;guestAccess?: 'none' | 'chat' | 'tools';accessRevision?: number;actorKind?: 'human' | 'bot' | 'integration';@@ -442,6 +445,7 @@ export interface BotGroupSummary {/** Upgraded host forwards leave explicitly; absent on old compatibility hosts. */supportsGroupLeave?: boolean;supportsListRemoval?: boolean;+ supportsMemberAvatar?: boolean;dissolvedAt?: string | null;archived?: boolean;migrationPending?: boolean;@@ -778,6 +782,7 @@ export interface ChatInvitePreview {export type ChatGroupAction =| { type: 'update'; name: string; topic: string; description: string; expectedRevision: number; responseMode?: BotGroupReplyMode; speakingMode?: BotGroupSpeakingMode }| { type: 'nickname'; actorId: string; nickname: string | null }+ | { type: 'avatar'; actorId: string; avatar: { type: 'keep' | 'reset' } | { type: 'set'; data: Uint8Array; mimeType: string } }| { type: 'member'; actorId: string; action: 'invite' | 'leave' | 'remove' | 'ban' | 'unban' | 'role'; role?: 'admin' | 'member' }| { type: 'transfer'; actorId: string }| { type: 'botAccess'; actorId: string; access: 'none' | 'chat' | 'tools'; expectedRevision: number }