Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): show readable notifications with precise conversation context
Chris4821c50324ee
diff --git a/apps/desktop/src/main/__tests__/notificationPreview.test.ts b/apps/desktop/src/main/__tests__/notificationPreview.test.tsindex 5e40b62de1..0ba2c6ec2b 100644--- a/apps/desktop/src/main/__tests__/notificationPreview.test.ts+++ b/apps/desktop/src/main/__tests__/notificationPreview.test.ts@@ -8,12 +8,23 @@ describe('notification plain text', () => {['# 标题\n\n**加粗 _斜体_** [报告 **完成**](https://example.com)', '标题 加粗 斜体 报告 完成'],['`a_b * 2`\n\n```ts\nconst a_b = 2 * 3;\n```', 'a_b * 2 const a_b = 2 * 3;'],['> 已完成\n\n- 第一项\n- 第二项\n\n~~旧内容~~', '已完成 第一项 第二项 旧内容'],- ['', ''],- ['![private filename][image]\n\n[image]: https://example.com/image.png', ''],- ['<img src="https://example.com/image.png" alt="private filename">', ''],+ ['', 'private filename'],+ ['![private filename][image]\n\n[image]: https://example.com/image.png', 'private filename'],+ ['<img src="https://example.com/image.png" alt="private filename">', 'private filename'],['& 😀 <tag>', '& 😀 <tag>'],['**日本語** / _한국어_ / [繁體中文](url)', '日本語 / 한국어 / 繁體中文'],])('converts %s', (markdown, expected) => expect(notificationPreview(markdown)).toBe(expected));+ // Reported notification bug: a rich reply leaked renderer operations instead of visible text.+ // Existing plain Markdown cases did not exercise the real cindy-ui stream (unit tier).+ it('projects the final rich reply instead of component JSON', () => {+ expect(notificationPreview('```cindy-ui\n' + [+ { version: 1, seq: 1, op: 'create', id: 'answer', kind: 'text', props: { text: '会议' } },+ { seq: 2, op: 'append', id: 'answer', text: '改到十点' },+ ].map(value => JSON.stringify(value)).join('\n') + '\n```')).toBe('会议改到十点');+ });+ it('names an image without a caption in the receiving locale', () => {+ expect(notificationPreview('', 240, '图片')).toBe('图片');+ });it('does not stall on bracketed repeated code spans', () => {const markdown = '[' + '`````a`````'.repeat(15) + ']';expect(notificationPreview(markdown)).toBe('[' + ('a' + '`'.repeat(10)).repeat(14) + 'a]');diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.tsindex 66e2a933e0..026ac5e009 100644--- a/apps/desktop/src/main/__tests__/notificationService.test.ts+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts@@ -80,6 +80,7 @@ vi.mock('electron', () => ({}),nativeImage: {createFromPath: () => ({ isEmpty: () => true }),+ createFromBuffer: (bytes: Buffer) => ({ bytes, isEmpty: () => false }),},}));@@ -162,7 +163,7 @@ async function freshService() {markSessionNeedsAttention.mockClear();sendMobileSessionNotify.mockReset().mockReturnValue(true);getMobileNotifyGeneration.mockClear();- latestMessageText.mockClear();+ latestMessageText.mockReset().mockResolvedValue('');readSessionNotificationPreview.mockReset().mockImplementation(async (sessionId, includeReply = true) => {if (!includeReply) return {};const text = await latestMessageText(sessionId, 'assistant');@@ -543,6 +544,7 @@ describe('notificationService — channels 分发', () => {await registeredHandlers.get('notification:show-session-event')!({}, {sessionId: 's1', title: 'Hello', kind, channels: { desktop: true, mobile: true },});+ await vi.advanceTimersByTimeAsync(0);expect(notificationCtor).toHaveBeenCalledTimes(1);await vi.advanceTimersByTimeAsync(1_000);expect(sendMobileSessionNotify).toHaveBeenCalledTimes(1);@@ -605,40 +607,39 @@ describe('notificationService — channels 分发', () => {expect(sendMobileSessionNotify).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 's1', teammateBotId: 'bot-1', teammateAvatar: { kind: 'preset', value: 'cindy' } }));});- it('routes a teammate approval push to the teammate chat without changing its title or fallback', async () => {+ it.each(['error', 'needs-reply'] as const)('routes teammate %s with its actual identity and state, never an older answer', async (kind) => {const { initNotificationService } = await freshService();initNotificationService(baseDeps(makeFeishuIm('ou_owner')));- readSessionNotificationPreview.mockResolvedValue({ teammateName: 'Cindy', teammateBotId: 'bot-1' });- await invokeHandler({ sessionId: 's1', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true } });+ readSessionNotificationPreview.mockResolvedValue({ teammateName: 'Cindy', teammateBotId: 'bot-1', teammateAvatar: { kind: 'jpeg', value: 'YQ==' } });+ await invokeHandler({ sessionId: 's1', title: 'Hello', kind, channels: { desktop: true, feishu: false, mobile: true } });await flushAsync();expect(sendMobileSessionNotify).toHaveBeenCalledWith({- sessionId: 's1', title: 'Hello', kind: 'needs-reply', generation: 7, teammateBotId: 'bot-1',+ sessionId: 's1', title: 'Cindy', kind, generation: 7, teammateBotId: 'bot-1', teammateAvatar: { kind: 'jpeg', value: 'YQ==' },});+ expect(latestMessageText).not.toHaveBeenCalled();+ expect(notificationCtor).toHaveBeenCalledWith(expect.objectContaining({ title: 'Cindy', icon: expect.objectContaining({ bytes: Buffer.from('a') }) }));// A failed identity read keeps the ordinary push.sendMobileSessionNotify.mockClear();readSessionNotificationPreview.mockRejectedValueOnce(new Error('read unavailable'));- await invokeHandler({ sessionId: 's2', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true } });+ await invokeHandler({ sessionId: 's2', title: 'Hello', kind, channels: { desktop: false, feishu: false, mobile: true } });await flushAsync();- expect(sendMobileSessionNotify).toHaveBeenCalledWith({ sessionId: 's2', title: 'Hello', kind: 'needs-reply', generation: 7 });+ expect(sendMobileSessionNotify).toHaveBeenCalledWith({ sessionId: 's2', title: 'Hello', kind, generation: 7 });});- it('does not let a slow teammate lookup spend the approval push preview window', async () => {+ it('bounds a slow approval identity lookup without reusing the previous answer', async () => {const { initNotificationService } = await freshService();initNotificationService(baseDeps(makeFeishuIm('ou_owner')));vi.useFakeTimers();readSessionNotificationPreview.mockReturnValueOnce(new Promise(() => {}));- let releaseDrain!: () => void;- drainPersistQueue.mockReturnValueOnce(new Promise<void>((resolve) => { releaseDrain = resolve; }));- latestMessageText.mockResolvedValueOnce('要删除 build 目录吗?');+ latestMessageText.mockResolvedValueOnce('上一轮已完成');await registeredHandlers.get('notification:show-session-event')!({}, {sessionId: 's1', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true },});- // The reply read starts without waiting for the routing lookup.- releaseDrain();+ // A missing identity cannot indefinitely hide the action request.await vi.advanceTimersByTimeAsync(1_000);expect(sendMobileSessionNotify).toHaveBeenCalledTimes(1);expect(sendMobileSessionNotify).toHaveBeenCalledWith({- sessionId: 's1', title: 'Hello', kind: 'needs-reply', generation: 7, detail: '要删除 build 目录吗?',+ sessionId: 's1', title: 'Hello', kind: 'needs-reply', generation: 7,});});@@ -801,18 +802,18 @@ describe('notificationService — channels 分发', () => {expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();});- it('伙伴最终答复没有可读正文时飞书使用本地化新回复兜底', async () => {+ it('伙伴纯图片回复使用本地化图片摘要而不是泛泛新回复', async () => {const { initNotificationService } = await freshService();const feishuIm = makeFeishuIm('ou_owner');initNotificationService(baseDeps(feishuIm));readSessionNotificationPreview.mockImplementation(async (_id, includeReply = true) => ({teammateName: 'Mika', eventId: 'turn:300:400',- ...(includeReply ? { reply: { clientId: 'final-2', text: '' } } : {}),+ ...(includeReply ? { reply: { clientId: 'final-2', text: '' } } : {}),}));await invokeHandler({ sessionId: 'bot-main', title: 'Old title', kind: 'done', channels: { desktop: false, feishu: true } });- expect(feishuIm.sendText).toHaveBeenCalledWith('ou_owner', 'Mika\n有新回复');+ expect(feishuIm.sendText).toHaveBeenCalledWith('ou_owner', 'Mika\n图片');expect(feishuIm.sendMarkdownText).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.tsindex 39e28b51d7..9aada3e997 100644--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@ -78,7 +78,7 @@ export type DeepLinkPayload =* 供 renderer 在导航落地后申请处置被点的那张卡。*/| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }- | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string; conversationKind?: 'direct' }| { type: 'project'; workingDir: string }/*** 由 --open-folder argv 触发的 "新建对话 + 预填工作目录"。@@ -428,8 +428,8 @@ export function openMainWindowSession(}/** An authenticated chat notification opens its exact message through the existing navigation queue. */-export function openMainWindowChatMessage(groupId: string, messageId: string, threadRootId?: string): void {- dispatchDeepLink({ type: 'chat-message', groupId, messageId, ...(threadRootId ? { threadRootId } : {}) });+export function openMainWindowChatMessage(groupId: string, messageId: string, threadRootId?: string, conversationKind?: 'direct'): void {+ dispatchDeepLink({ type: 'chat-message', groupId, messageId, ...(conversationKind ? { conversationKind } : {}), ...(threadRootId ? { threadRootId } : {}) });}/** Sends a typed internal event to the primary renderer without broadcasting to utility windows. */diff --git a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.tsindex 93fc2a230d..6df15ec220 100644--- a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts@@ -11,8 +11,8 @@ describe('buildSessionNotifyPayload', () => {expect(first.sender?.id).toMatch(/^[a-f0-9]{64}$/);expect(buildSessionNotifyPayload({ ...opts, selfDeviceId: 'd2' }).sender?.id).not.toBe(first.sender?.id);expect(buildSessionNotifyPayload({ ...opts, sessionId: 's2' }).sender?.id).toBe(first.sender?.id);- expect(buildSessionNotifyPayload({ ...opts, kind: 'needs-reply' }).sender).toBeUndefined();- expect(buildSessionNotifyPayload({ ...opts, kind: 'error' }).sender).toBeUndefined();+ expect(buildSessionNotifyPayload({ ...opts, kind: 'needs-reply' }).sender).toEqual(first.sender);+ expect(buildSessionNotifyPayload({ ...opts, kind: 'error' }).sender).toEqual(first.sender);expect(buildSessionNotifyPayload({ ...opts, teammateBotId: undefined }).sender).toBeUndefined();});const base = {@@ -155,7 +155,7 @@ it('uses final-message identity for completed replies, allowing distinct repliesit('sends plain text to APNs, not Markdown or image paths', () => {const payload = { sessionId: 'bot', title: 'Cindy', kind: 'done' as const, selfDeviceId: 'home', fallbackBody: 'New reply' };expect(buildSessionNotifyPayload({ ...payload, detail: '**Report** [ready](https://example.com) `a_b`' }).body).toBe('Report ready a_b');- expect(buildSessionNotifyPayload({ ...payload, detail: '' }).body).toBe('New reply');+ expect(buildSessionNotifyPayload({ ...payload, detail: '' }).body).toBe('private');});describe('buildBotGroupNotifyPayload', () => {diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex d2618a2cf9..efb626682b 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -167,7 +167,7 @@ import {type MobileSessionEventKind,} from './mobileNotify';import { createSubscriptionReplayScheduler, isPermanentSubscriptionReplayError } from './subscriptionReplayScheduler';-import { getSessionNotificationBody } from '../sessionNotificationCopy';+import { getNotificationImageLabel, getSessionNotificationBody } from '../sessionNotificationCopy';import { getClientEndpoint } from '../clientEndpointsService';import {handleContactsDeviceLinkStatusChanged,@@ -2158,6 +2158,7 @@ export function sendMobileSessionNotify(payload: {selfDeviceId,fallbackBody: payload.fallbackBody ?? getSessionNotificationBody(payload.kind),detail: payload.detail,+ imageFallback: getNotificationImageLabel(),...(payload.teammateBotId ? { teammateBotId: payload.teammateBotId } : {}),...(payload.teammateAvatar ? { teammateAvatar: payload.teammateAvatar } : {}),}),diff --git a/apps/desktop/src/main/device-link/mobileNotify.ts b/apps/desktop/src/main/device-link/mobileNotify.tsindex 47667f0a69..d949f024c2 100644--- a/apps/desktop/src/main/device-link/mobileNotify.ts+++ b/apps/desktop/src/main/device-link/mobileNotify.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto';-import { notificationPreview } from '../notificationPreview.js';+import { notificationPreview, truncateNotificationText } from '../notificationPreview.js';import {NOTIFY_BODY_MAX_LENGTH,NOTIFY_DEEP_LINK_MAX_LENGTH,@@ -37,6 +37,7 @@ export function buildSessionNotifyPayload(opts: {selfDeviceId: string;/** 由 main host 按发送时的当前 locale 解析;本纯模块不依赖 Electron i18n。 */fallbackBody: string;+ imageFallback?: string;/** 内容摘要(可选):折叠空白后按协议上限截断 */detail?: string;/**@@ -46,17 +47,14 @@ export function buildSessionNotifyPayload(opts: {teammateBotId?: string;teammateAvatar?: NotifySender['avatar'];}): NotifyPayload {- const safeTitle = (opts.title.trim() || opts.sessionId.slice(0, 8)).slice(- 0,- NOTIFY_TITLE_MAX_LENGTH,- );- const detail = opts.detail ? notificationPreview(opts.detail, NOTIFY_BODY_MAX_LENGTH) : '';+ const safeTitle = truncateNotificationText(opts.title.trim() || opts.sessionId.slice(0, 8), NOTIFY_TITLE_MAX_LENGTH);+ const detail = opts.detail ? notificationPreview(opts.detail, NOTIFY_BODY_MAX_LENGTH, opts.imageFallback) : '';return {category: CATEGORY_BY_KIND[opts.kind],title: safeTitle,- body: detail || opts.fallbackBody.slice(0, NOTIFY_BODY_MAX_LENGTH),+ body: detail || truncateNotificationText(opts.fallbackBody, NOTIFY_BODY_MAX_LENGTH),deepLink: sessionDeepLink(opts.sessionId, opts.selfDeviceId, opts.teammateBotId),- ...(opts.kind === 'done' && opts.teammateBotId ? {+ ...(opts.teammateBotId ? {sender: {id: createHash('sha256').update(`${opts.selfDeviceId}:bot:${opts.teammateBotId}`).digest('hex'),...(opts.teammateAvatar ? { avatar: opts.teammateAvatar } : {}),@@ -85,7 +83,7 @@ export function buildBotGroupNotifyPayload(opts: {body: string;selfDeviceId: string;}): NotifyPayload {- const title = (opts.title.trim() || opts.groupId.slice(0, 8)).slice(0, NOTIFY_TITLE_MAX_LENGTH);+ const title = truncateNotificationText(opts.title.trim() || opts.groupId.slice(0, 8), NOTIFY_TITLE_MAX_LENGTH);return {category: 'session-needs-reply',title,diff --git a/apps/desktop/src/main/localDb/sessionNotificationPreview.ts b/apps/desktop/src/main/localDb/sessionNotificationPreview.tsindex 032689d123..4d5b79b9f5 100644--- a/apps/desktop/src/main/localDb/sessionNotificationPreview.ts+++ b/apps/desktop/src/main/localDb/sessionNotificationPreview.ts@@ -18,7 +18,7 @@ export interface SessionNotificationPreview {}/** Use the durable current turn, never the previous answer or an internal task receipt. */-export async function readSessionNotificationPreview(sessionId: string, includeReply = true): Promise<SessionNotificationPreview> {+export async function readSessionNotificationPreview(sessionId: string, includeReply = true, includeAvatar = includeReply): Promise<SessionNotificationPreview> {const db = getDbClient().drizzle;const rows = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);const current = rows[0];@@ -26,7 +26,7 @@ export async function readSessionNotificationPreview(sessionId: string, includeRconst profile = current.source === 'bot' ? await db.select({ id: botProfiles.id, name: botProfiles.displayName, avatar: botProfiles.avatar }).from(botProfiles).innerJoin(botSessionLinks, eq(botSessionLinks.botId, botProfiles.id)).where(and(eq(botSessionLinks.sessionId, sessionId), eq(botSessionLinks.role, 'canonical'))).get() : undefined;- const avatar = profile && includeReply ? await notificationAvatar(profile.avatar) : undefined;+ const avatar = profile && includeAvatar ? await notificationAvatar(profile.avatar) : undefined;const teammate = profile ? {teammateName: profile.name, teammateBotId: profile.id,...(avatar ? { teammateAvatar: avatar } : {}),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex a33237acf7..c13f270b3a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -3652,6 +3652,33 @@ describe('Chat Server result delivery and refresh', () => {expect(vi.mocked(socket.send).mock.calls.filter(([raw]) => String(raw).includes(groupId))).toEqual([]);});+ // Notification landing explicitly opts into direct read/send. Previously the real+ // getGroup entry rejected it. Existing cases below still protect group-only operations.+ it('opens, reads and answers a direct notification without invoking group planning', async () => {+ const messageId = '50000000-0000-4000-8000-000000000009';+ deps.decidePlan = vi.fn(async () => null);+ const read = await service.getGroup(directId, { conversationKind: 'direct' });+ expect(read).toMatchObject({ ok: true, group: { conversationKind: 'direct', canInvite: false, supportsGroupLeave: false } });+ expect(await service.sendMessage({ groupId: directId, conversationKind: 'direct', text: 'Received',+ clientId: 'direct-notice-reply', mentions: { all: false, botIds: [] } })).toMatchObject({ ok: true });+ expect(writes()).toHaveLength(1);+ expect(writes()[0]).toMatchObject([`/conversations/${directId}/messages`, 'POST', {+ content: [{ type: 'text', text: 'Received' }], deferExecution: false,+ }]);+ expect(deps.decidePlan).not.toHaveBeenCalled();+ expect(await service.getGroup(channelId, { conversationKind: 'direct' })).toMatchObject({ ok: false });+ expect(await service.sendMessage({ groupId: directId, conversationKind: 'direct', text: 'No plan', division: true,+ clientId: 'direct-notice-no-plan', mentions: { all: false, botIds: [] } })).toMatchObject({ ok: false });+ expect(writes()).toHaveLength(1);+ const previous = fixture.handle.getMockImplementation()!;+ fixture.handle.mockImplementation((route, method, body) => route === `/conversations/${directId}/snapshot`+ ? { body: { room: roomOf(directId), cursor: '2', members: [], reads: [{ thread_key: 'main', read_seq: '0' }],+ messages: [{ id: messageId, seq: '2', threadRootId: null }] } }+ : previous(route, method, body));+ expect(await service.chatServer!.manage({ groupId: directId, action: { type: 'read', messageId, conversationKind: 'direct' } })).toMatchObject({ ok: true });+ expect(writes().at(-1)).toMatchObject([`/conversations/${directId}/read`, 'POST', { readSeq: '2' }]);+ });+it('rejects a first send to a direct room before reading plans or members', async () => {expect(await service.sendMessage({ groupId: directId, text: 'hi', clientId: 'cold-direct-send', mentions: { all: true, botIds: [] } })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });diff --git a/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts b/apps/desktop/src/main/maker-ipc/chatMessageNotifications.tsindex b7c385c223..11fefca46b 100644--- a/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts+++ b/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts@@ -4,6 +4,8 @@ export interface ChatMessageNotification {groupName: string;messageId: string;threadRootId?: string;+ conversationKind?: 'direct' | 'group';+ threadName?: string;senderName: string;avatar: string;preview: string;diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 94ad72057f..551dc4286e 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -29,6 +29,7 @@ import { prepareBotGroupTaskPost, type BotGroupTaskPostSnapshot } from './botGroimport { registerGroupToolAuthority, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';import path from 'node:path';import { randomUUID, createHash } from 'node:crypto';+import { notificationPreview } from '../notificationPreview.js';import { markdownPreviewText } from '../../shared/markdownPreviewText.js';import { createChatMessageNotifications } from './chatMessageNotifications.js';import WebSocket from 'ws';@@ -506,8 +507,26 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst snapshot = await recentSnapshot(groupId);const member = snapshot.members.find(member => member.id === message.authorId);const view = messageView(message, snapshot.members);- return { senderName: view.authorName, avatar: member?.avatar ?? localBot(message.authorId)?.avatar ?? '',- preview: markdownPreviewText(botGroupMessageSummaryText(view) || mediaNames(message)).slice(0, 160) };+ const words = (key: string) => t(`settings.notifications.chat.${key}`);+ const name = notificationPreview(view.authorName) || words('sender');+ const senderName = message.author.kind === 'bot' ? `${name} (${words('teammate')})` : name;+ const attachments = await Promise.all(bodyBlocks(message).filter(block => block.type === 'media').map(async block => {+ if (block.caption?.trim()) return notificationPreview(block.caption);+ const file = block.mediaId ? await api<{ name: string; type: string }>(`/conversations/${groupId}/media/${block.mediaId}`).catch(() => null) : null;+ const kind = file?.type.startsWith('image/') ? 'image' : file?.type.startsWith('audio/') ? 'audio' : file?.type.startsWith('video/') ? 'video' : 'file';+ return kind === 'file' && file?.name ? `${words(kind)}: ${notificationPreview(file.name)}` : words(kind);+ }));+ const readContext = async (messageId: string) => snapshot.messages.find(item => item.id === messageId)+ ?? await api<Message>(`/conversations/${groupId}/messages/${messageId}`).catch(() => undefined);+ const root = message.threadRootId ? await readContext(message.threadRootId) : undefined;+ const quote = view.quote ? await readContext(view.quote.messageId) : undefined;+ const reason = message.mentions?.includes(selfId) ? words('mention')+ : quote && !quote.deleted && quote.authorId === selfId ? words('reply') : message.threadRootId ? words('threadReply') : '';+ const preview = notificationPreview([botGroupMessageSummaryText(view), ...attachments].filter(Boolean).join(' '), 240, words('image')) || words('message');+ return { senderName, avatar: member?.avatar ?? localBot(message.authorId)?.avatar ?? '',+ conversationKind: snapshot.room.kind === 'direct' ? 'direct' as const : 'group' as const,+ ...(message.threadRootId ? { threadName: root && !root.deleted ? notificationPreview(displayText(root), 48) || words('thread') : words('thread') } : {}),+ preview: [reason,preview].filter(Boolean).join(': ') };},notify: deps.onChatMessageNotification,}) : undefined;@@ -1036,6 +1055,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDsubscribe(roomId, value.cursor);return value;}+ /** Notification landing opts into a direct room; ordinary group callers remain strict. */+ async function directSnapshot(roomId: string) {+ const value = await readSnapshot(roomId);+ if (value.room.kind !== 'direct') throw new Error('NOT_A_GROUP');+ subscribe(roomId, value.cursor);+ return value;+ }/** Every groupId entry resolves through here: a room that is not a group answers as missing before any other read or write. */async function groupRoom(groupId: string) {const room = await resolveGroup(groupId);@@ -1293,7 +1319,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}async function detail(roomId: string, options?: unknown, summaryOnly = false): Promise<BotGroupDetail> {id.parse(roomId);- const o = z.object({ beforeSequence: z.number().int().positive().optional(), limit: z.number().int().min(1).max(100).optional(),+ const o = z.object({ conversationKind: z.literal('direct').optional(), beforeSequence: z.number().int().positive().optional(), limit: z.number().int().min(1).max(100).optional(),sourceMessageIds: z.array(id).optional(),shownShares: z.array(z.object({ id, messageId: id, threadRootId: id, sharerId: z.string().min(1).max(200).optional() })).optional() }).parse(options ?? {});const query = new URLSearchParams({ limit: String(o.limit ?? 100) });@@ -1303,18 +1329,19 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// reported (a left room stays 「not found」), whichever request fails first in time.// A followed room reports every later change, so its snapshot may run alongside. A new// room first takes the snapshot cursor it will follow from, before the rest is read.- const snapshotRead = groupSnapshot(roomId);+ const direct = o.conversationKind === 'direct';+ const snapshotRead = direct ? directSnapshot(roomId) : groupSnapshot(roomId);if (!rooms.has(roomId)) await snapshotRead;const messagesRead = summaryOnly ? null : api<Message[]>(`/conversations/${roomId}/messages?${query}`);- const executionsRead = api<Execution[]>(`/conversations/${roomId}/executions`);+ const executionsRead = direct ? Promise.resolve([] as Execution[]) : api<Execution[]>(`/conversations/${roomId}/executions`);for (const read of [messagesRead, executionsRead]) read?.catch(() => undefined);const s = await snapshotRead;const page = (await messagesRead) ?? s.messages;const executions = await executionsRead;const ids = page.flatMap(m => m.content.flatMap(b => b.namespace === 'cindy.plan' && typeof b.data?.planId === 'string' ? [id.parse(b.data.planId)] : []));- const plansRead = api<ServerPlan[]>(`/conversations/${roomId}/plans${ids.length ? `?ids=${ids.join(',')}` : ''}`);+ const plansRead = direct ? Promise.resolve([] as ServerPlan[]) : api<ServerPlan[]>(`/conversations/${roomId}/plans${ids.length ? `?ids=${ids.join(',')}` : ''}`);plansRead.catch(() => undefined);- const executionFailures = summaryOnly ? undefined : await failureSnapshot(roomId, s.members, [...(o.sourceMessageIds ?? []), ...page.map(m => m.id)], executions);+ const executionFailures = summaryOnly || direct ? undefined : await failureSnapshot(roomId, s.members, [...(o.sourceMessageIds ?? []), ...page.map(m => m.id)], executions);const serverPlans = await plansRead;const workspace = workspaces().read(roomId);const plans = serverPlans.map(plan => planView(plan, s.members, workspace));@@ -1334,20 +1361,20 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (deciding) speakers.push({ botId: deciding.botId, sessionId: null, activity: 'planning' });// Sidebar refresh must not download every attachment in every group's history.const messages = summaryOnly ? [] : await messageViews(roomId, page, s.members);- const shares = summaryOnly ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);+ const shares = summaryOnly || direct ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);const threadShareUpdates = shares?.updates;const reads = threadReads(s);const unread = reads ? s.messages.filter(m => !m.deleted && m.origin !== 'system' && m.origin !== 'import' && m.authorId !== selfId&& (!m.threadRootId || m.mentions?.includes(selfId) || s.reads?.some(read => read.thread_key === m.threadRootId && read.following))&& BigInt(m.seq) > (reads.get(m.threadRootId ?? 'main') ?? 0n)) : null;if (reads) for (const view of messages) if (!view.threadRootId && (view.replyCount ?? 0) > 0) view.threadUnread = threadUnread(view.id, s.messages, reads);- const threadList = reads ? threadSummaries(roomId, s, page, reads) : undefined;+ const threadList = reads && !direct ? threadSummaries(roomId, s, page, reads) : undefined;messages.sort((a, b) => a.sequence - b.sequence);const last = s.messages[0];const 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, 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, supportsDivision: true } : {}), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,+ return { conversationKind: direct ? 'direct' : 'group', serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: !direct, supportsDissolve: !direct && supportsDissolve, supportsListRemoval, supportsMemberAvatar: !direct && 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: !direct && !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), canStopAll: !direct && singleSpeaker && !!managementActor(s), ...(!direct && singleSpeaker ? { singleSpeaker: true, supportsDivision: true } : {}), id: s.room.id, name: direct ? s.members.filter(m => m.state === 'joined' && m.id !== selfId).map(memberName).join(', ') || s.room.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,@@ -1358,11 +1385,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD...(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: m.groupAvatar ? '' : p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };- }), organizerBotId: ((id?: string) => id ? localBot(id)?.id ?? id : null)(s.room.organizer_id ?? s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id), projectDir: workspace?.projectDir ?? null,+ }), organizerBotId: direct ? null : ((id?: string) => id ? localBot(id)?.id ?? id : null)(s.room.organizer_id ?? s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id), projectDir: workspace?.projectDir ?? null,// Only servers that tell a 分工 from a queue (kind) can hand one on by itself....(singleSpeaker ? { autoContinue: workspace?.autoContinue === true } : {}), lastMessage: last && lastView ? {isSelf: lastView.isSelf, authorKind: lastView.authorKind, authorName: lastView.authorName, noticeCode: lastView.noticeCode,- preview: lastIsShare ? '' : markdownPreviewText(botGroupMessageSummaryText(lastView) || mediaNames(last)).slice(0, 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),+ preview: lastIsShare ? '' : notificationPreview(botGroupMessageSummaryText(lastView) || mediaNames(last), 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),} : null, speakingBotIds: speakers.map(s => s.botId), planningBotId: planning.get(roomId)?.botId ?? null, openPlan: open ? { id: open.id, status: open.status, currentStep: open.currentStep, stepCount: open.steps.length, currentBotName: open.steps[open.currentStep ?? 0]?.botName ?? null, currentStepStatus: open.steps[open.currentStep ?? 0]?.status ?? null, ...(open.kind ? { kind: open.kind } : {}) } : null,lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.origin !== 'system' && m.authorId !== selfId? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),@@ -2341,10 +2368,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDchanged(''); return {};}),manage: input => result(async () => {- const target = await resolveGroup(id.parse(input.groupId));+ const requested = id.parse(input.groupId);const actorAction = z.object({ actorId: id });const action = z.discriminatedUnion('type', [- z.object({ type: z.literal('read'), messageId: id }).strict(),+ z.object({ type: z.literal('read'), messageId: id, conversationKind: z.literal('direct').optional() }).strict(),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(),@@ -2358,6 +2385,8 @@ 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);+ const target = action.type === 'read' && action.conversationKind === 'direct'+ ? (await directSnapshot(requested)).room.id : await resolveGroup(requested);if (action.type === 'read') {const snapshot = await recentSnapshot(target);if (!snapshot.reads) return {};@@ -2584,10 +2613,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}const sendMessage: BotGroupChatService['sendMessage'] = (input, origin) => safe(async () => {const started = Date.now();- const i = z.object({ groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),+ const i = z.object({ conversationKind: z.literal('direct').optional(), groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }), division: z.boolean().optional(), attachments: z.array(z.unknown()).optional(),quote: z.object({ messageId: id }).strict().optional() }).parse(input);i.groupId = await resolveGroup(i.groupId);+ const direct = i.conversationKind === 'direct';+ if (direct && i.division) throw new Error('INVALID_INPUT');if (!i.text.trim() && !i.attachments?.length) throw new Error('INVALID_INPUT');// A single-speaker server cannot release a held request (no cancel-planning): a newer message// replacing a 分工 still being arranged would leave it to be queued two minutes later. Wait for its card.@@ -2597,14 +2628,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// The reads a send needs share one round trip (none for a snapshot the live subscription// vouches for). Each is awaited in the former order, so the first failure reported is the// one the serial version reported.- const snapshotRead = recentSnapshot(i.groupId, true);+ const snapshotRead = direct ? directSnapshot(i.groupId) : recentSnapshot(i.groupId, true);// An unopened room must be confirmed as a group before reading its other resources.if (!rooms.has(i.groupId)) await snapshotRead;const quoteKey = i.quote ? JSON.stringify([i.groupId, i.clientId, i.quote.messageId, i.text, i.mentions, i.division]) : '';const knownQuote = i.quote ? postedQuotes.get(quoteKey) : undefined;const snapshotMembers = snapshotRead.then(value => value.members);const quoteRead = i.quote && !knownQuote ? quoteSnapshot(i.groupId, i.quote.messageId, snapshotMembers) : undefined;- const plansRead = api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);+ const plansRead = direct ? Promise.resolve([] as ServerPlan[]) : api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);const membersRead = namesNobody(i.mentions) && !i.quote ? undefined : api<Member[]>(`/conversations/${i.groupId}/members`);for (const read of [snapshotMembers, quoteRead, plansRead, membersRead]) read?.catch(() => undefined);const s = await snapshotRead;@@ -2622,16 +2653,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst settleQueue = singleSpeaker && i.division && openPlan?.kind === 'talk' && openPlan.status === 'waiting' && mayAdd ? openPlan : undefined;if (i.division && openPlan && !proposed && !settleQueue) throw new Error('PLAN_OPEN');// Reply mode decides whether an unaddressed message wakes anyone (single-speaker servers apply it too).- const canTrigger = i.division || s.room.response_mode !== 'mentioned' || !namesNobody(i.mentions);+ const canTrigger = !direct && (i.division || s.room.response_mode !== 'mentioned' || !namesNobody(i.mentions));// Words for a card under way reach its current step only when they would wake anyone (§4.0,// §7.4); a queue waiting for 继续 gives way to a new request instead.const commentPlan = canTrigger && openPlan && openPlan.status !== 'proposed' && !(singleSpeaker && openPlan.kind === 'talk' && openPlan.status === 'waiting') && !i.mentions.botIds.length && !i.mentions.all && mayAdd ? openPlan : undefined;// Single-speaker servers queue turns themselves; only a 分工, or words about your proposed card,// wait for the arrangement. A 分工 that writes out its steps needs no helper model.- const shouldPlan = singleSpeaker+ const shouldPlan = !direct && (singleSpeaker? i.division || (canTrigger && proposed && namesNobody(i.mentions) && !!deps.decidePlan): canTrigger && !!deps.decidePlan && (i.division || (!i.mentions.botIds.length && (!proposed || !i.mentions.all)))- && (!openPlan || proposed);+ && (!openPlan || proposed));const prepared = i.attachments?.length ? await deps.prepareAttachments?.({ groupId: i.groupId, attachments: i.attachments, controllerDeviceId: origin?.controllerDeviceId }) : undefined;if (i.attachments?.length && (!prepared || !prepared.ok)) {const error = new Error(prepared && !prepared.ok ? prepared.errorCode === 'INVALID_PARAMS' ? 'INVALID_ATTACHMENT' : prepared.errorCode : 'INVALID_ATTACHMENT');@@ -2651,7 +2682,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDposting = true;result = await api<{ id: string }>(`/conversations/${i.groupId}/${commentPlan ? `plans/${commentPlan.id}/messages` : 'messages'}`, 'POST', {operationId: i.clientId, content: [ ...(quote ? [buildBotGroupQuoteCard(quote)] : []), ...(i.text ? [{ type: 'text', text: i.text }] : []),- ...uploaded ], mentions, deferExecution: shouldPlan, ...(groupDiscussionParity ? { mentionsAll: i.mentions.all, planningMode: i.division || proposed ? 'explicit' : 'auto' } : {}),+ ...uploaded ], mentions, deferExecution: shouldPlan, ...(!direct && groupDiscussionParity ? { mentionsAll: i.mentions.all, planningMode: i.division || proposed ? 'explicit' : 'auto' } : {}),});} catch (error) {if (prepared?.ok) await prepared.discard();@@ -2666,6 +2697,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// The message exists: the send is answered now and its receipt answers any retry, so the// quote snapshot is no longer needed. Arrangement bookkeeping continues after the answer.postedQuotes.delete(quoteKey);+ if (direct) { changed(i.groupId); return { ok: true as const, messageId: result.id }; }const roomId = i.groupId;const messageId = result.id;void (async () => {@@ -2735,7 +2767,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (!current()) return Promise.resolve(chatGroupFailure(new Error('OWNER_CHANGED')));// clientId identifies one immutable send; annotation burn-in can regenerate// attachment names/URLs while the controller is retrying its lost receipt.- const identity = z.object({ groupId: id, clientId: z.string().min(1).max(200), text: z.string(),+ const identity = z.object({ conversationKind: z.literal('direct').optional(), groupId: id, clientId: z.string().min(1).max(200), text: z.string(),mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }), division: z.boolean().optional(),quote: z.object({ messageId: z.string() }).optional() }).safeParse(input);if (!identity.success) return sendMessage(input, origin);diff --git a/apps/desktop/src/main/notificationPreview.ts b/apps/desktop/src/main/notificationPreview.tsindex 836f23e812..4b95ec6d67 100644--- a/apps/desktop/src/main/notificationPreview.ts+++ b/apps/desktop/src/main/notificationPreview.ts@@ -1,14 +1,18 @@import { markdownPreviewText } from '../shared/markdownPreviewText';-/** Parse before shortening, without leaking image filenames into notifications. */-export function notificationPlainText(markdown: string): string {- return markdownPreviewText(markdown, { includeImageAlt: false });+/** Project message text and image descriptions before shortening. */+export function notificationPlainText(markdown: string, imageFallback = 'Image'): string {+ return markdownPreviewText(markdown, { imageFallback });}-export function notificationPreview(markdown: string, limit = 240): string {+export function notificationPreview(markdown: string, limit = 240, imageFallback = 'Image'): string {+ return truncateNotificationText(notificationPlainText(markdown, imageFallback), limit);+}++export function truncateNotificationText(text: string, limit: number): string {// The notify protocol measures JS string length (UTF-16), not code points.let preview = '';- for (const character of notificationPlainText(markdown)) {+ for (const character of text) {if (preview.length + character.length > limit) break;preview += character;}diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.tsindex a21fd9093c..712373f009 100644--- a/apps/desktop/src/main/notificationService.ts+++ b/apps/desktop/src/main/notificationService.ts@@ -35,10 +35,10 @@ import type { ChatMessageNotification } from './maker-ipc/chatMessageNotificatioimport { readSessionNotificationPreview, type SessionNotificationPreview } from './localDb/sessionNotificationPreview';import { drainSessionActiveTurnWrites, getSessionNotificationTurnSignal } from './localDb/sessionActiveTurn';import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './device-link/broadcast-tap';-import { latestMessageText } from './localDb/latestMessageText';import { drainPersistQueue } from './messagePersistBroadcaster';import { createLogger } from './logger';import {+ getNotificationImageLabel,getSessionExternalNotificationText,getSessionNotificationBody,getTeammateNotificationFallback,@@ -75,15 +75,18 @@ export async function showDesktopChatMessage(payload: ChatMessageNotification, c]).finally(() => clearTimeout(timer));if (!current() || !desktopNotificationsEnabled || visible()) return;const icon = thumbnail ? nativeImage.createFromBuffer(Buffer.from(thumbnail, 'base64')) : undefined;- const notification = new Notification({ title: payload.groupName,- body: `${payload.senderName}: ${payload.preview}`,+ const notification = new Notification({ title: payload.conversationKind === 'direct' ? payload.senderName : [payload.groupName,payload.threadName].filter(Boolean).join(' · '),+ body: payload.conversationKind === 'direct' ? payload.preview : [payload.senderName,payload.preview].filter(Boolean).join(': '),...(icon && !icon.isEmpty() ? { icon } : devNotificationIcon ? { icon: devNotificationIcon } : {}),});liveNotifications.add(notification);const release = () => { liveNotifications.delete(notification); };notification.on('click', () => {release();- if (current()) openMainWindowChatMessage(payload.groupId, payload.messageId, payload.threadRootId);+ if (current()) {+ if (payload.conversationKind === 'direct') openMainWindowChatMessage(payload.groupId, payload.messageId, payload.threadRootId, 'direct');+ else openMainWindowChatMessage(payload.groupId, payload.messageId, payload.threadRootId);+ }});notification.on('close', release);notification.on('failed', release);@@ -205,6 +208,7 @@ export function showDesktopSessionEvent(payload: Pick<ShowSessionEventPayload, 'sessionId' | 'title' | 'kind'> & {body?: string;teammate?: boolean;+ avatarJpeg?: string;/** 其它设备的任务传 false:未读归属那台设备,本机 Dock 角标不跟着记。 */markAttention?: boolean;},@@ -212,7 +216,7 @@ export function showDesktopSessionEvent(const { sessionId, title, kind } = payload;if (sessionId && payload.markAttention !== false) markSessionNeedsAttention(sessionId);const safeTitle = title?.trim() || sessionId.slice(0, 8) || getSessionNotificationUntitled();- return showDesktopToast(safeTitle, kind, () => focusWindow(getWindow, sessionId), payload.body, payload.teammate);+ return showDesktopToast(safeTitle, kind, () => focusWindow(getWindow, sessionId), payload.body, payload.teammate, payload.avatarJpeg);}/**@@ -276,10 +280,6 @@ export function initNotificationService(deps: NotificationServiceDeps): void {const wantFeishu = channels?.feishu === true;if (markAttention) markSessionNeedsAttention(sessionId);- // Action/error desktop notices have no transcript preview and must be immediate.- if (wantDesktop && kind !== 'done') {- showDesktopSessionEvent(getWindow, { sessionId, title: safeTitle, kind, markAttention });- }// Content is read from main's transcript. Bound only enrichment, not delivery;// a timeout is not a dedupe window and never causes a second late toast.void (async () => {@@ -288,19 +288,27 @@ export function initNotificationService(deps: NotificationServiceDeps): void {let teammateBotId: string | undefined;let postDrainPreviewReady = false;let detail: string | undefined;- if (kind === 'done' || (kind === 'needs-reply' && channels?.mobile === true)) {+ let avatarJpeg: string | undefined;+ if (kind === 'done' || wantDesktop || channels?.mobile === true) {let finished = false;let timer: ReturnType<typeof setTimeout> | undefined;- // Routing is optional: read it beside the reply so it never spends the- // preview's wait window, and a failed identity read costs nothing.- const routeRead = kind === 'needs-reply'- ? readSessionNotificationPreview(sessionId, false).then(- (identity) => { if (!finished) teammateBotId = identity.teammateBotId; },+ // Resolve identity and artwork within the same bounded enrichment window.+ const readAvatar = async (identity: SessionNotificationPreview) => {+ if (!wantDesktop) return;+ const avatar = identity.teammateAvatar;+ const jpeg = avatar?.kind === 'jpeg' ? avatar.value+ : avatar?.kind === 'preset' ? await companionAvatarThumbnail(`cindy://avatar/preset/${avatar.value}`) : undefined;+ if (!finished) avatarJpeg = jpeg;+ };+ const routeRead = kind !== 'done'+ ? readSessionNotificationPreview(sessionId, false, true).then(+ async (identity) => { if (!finished) { teammateBotId = identity.teammateBotId; preview = identity; await readAvatar(identity); } },() => undefined): undefined;try {await Promise.race([Promise.all([(async () => {+ if (kind !== 'done') return; // A previous answer is neither the current question nor the error.if (kind === 'done') {// Read the teammate identity first so a blocked write still// has the correct fallback. This snapshot may predate the@@ -320,8 +328,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {preview = await readSessionNotificationPreview(sessionId);postDrainPreviewReady = true;detail = preview.reply?.text;- } else {- detail = await latestMessageText(sessionId, 'assistant');+ await readAvatar(preview);}})(), routeRead]),new Promise<void>((resolve) => { timer = setTimeout(resolve, NOTIFICATION_PREVIEW_WAIT_MS); }),@@ -377,15 +384,15 @@ export function initNotificationService(deps: NotificationServiceDeps): void {}return;}- const fallbackBody = teammate ? getTeammateNotificationFallback() : undefined;+ const fallbackBody = teammate && kind === 'done' ? getTeammateNotificationFallback() : undefined;const mobileTeammateBotId = preview?.teammateBotId ?? teammateBotId;- if (wantDesktop && kind === 'done' && !wasReplyNotified(desktopKey, eventId)) {+ if (wantDesktop && (kind !== 'done' || !wasReplyNotified(desktopKey, eventId))) {try {const accepted = showDesktopSessionEvent(getWindow, {- sessionId, title: notificationTitle, kind, teammate, markAttention,- body: teammate ? notificationPreview(detail ?? '') || fallbackBody : undefined,+ sessionId, title: notificationTitle, kind, teammate, markAttention, avatarJpeg,+ body: teammate ? notificationPreview(detail ?? '', 240, getNotificationImageLabel()) || fallbackBody : undefined,});- if (accepted) {+ if (kind === 'done' && accepted) {notifiedReplies.set(desktopKey, eventId ? { eventId } : { fallbackSentAt: Date.now() });}} catch (err) {@@ -413,7 +420,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {pendingFeishuReplies.add(pendingKey);if (!eventId) pendingFeishuFallbacks.set(feishuKey, Date.now());try {- const body = teammate ? notificationPreview(detail ?? '') || fallbackBody : undefined;+ const body = teammate ? notificationPreview(detail ?? '', 240, getNotificationImageLabel()) || fallbackBody : undefined;const accepted = await sendFeishuMessage(feishuIm, notificationTitle, kind, body);if (accepted) {notifiedReplies.set(feishuKey, eventId ? { eventId } : { fallbackSentAt: Date.now() });@@ -460,7 +467,7 @@ function assertValidSessionEventPayload(}/** 桌面 toast 分支 — 原实现保持不变,只是拆出来便于 channels 选择性执行。 */-function showDesktopToast(safeTitle: string, kind: SessionEventKind, onClick: () => void, previewBody?: string, teammate = false): boolean {+function showDesktopToast(safeTitle: string, kind: SessionEventKind, onClick: () => void, previewBody?: string, teammate = false, avatarJpeg?: string): boolean {const body = previewBody ?? getSessionNotificationBody(kind);// Electron Notification 在某些 Linux 桌面环境下可能不可用——静默兜底。@@ -469,13 +476,13 @@ function showDesktopToast(safeTitle: string, kind: SessionEventKind, onClick: ()return false;}+ const avatar = avatarJpeg ? nativeImage.createFromBuffer(Buffer.from(avatarJpeg, 'base64')) : undefined;const notif = new Notification({title: teammate && safeTitle.trim().toLowerCase() === 'cindy'? CLIENT_NOTIFICATION_NAME : `${CLIENT_NOTIFICATION_NAME} · ${safeTitle}`,body,// silent 默认 false——发声音,与 Electron 默认一致。- // icon 仅在 dev 下传值;packaged 时为 undefined,回到原行为(由 AUMID/.icns 兜底)。- ...(devNotificationIcon ? { icon: devNotificationIcon } : {}),+ ...(avatar && !avatar.isEmpty() ? { icon: avatar } : devNotificationIcon ? { icon: devNotificationIcon } : {}),});liveNotifications.add(notif);diff --git a/apps/desktop/src/main/sessionNotificationCopy.ts b/apps/desktop/src/main/sessionNotificationCopy.tsindex b8ce027725..5e10ac4fe8 100644--- a/apps/desktop/src/main/sessionNotificationCopy.ts+++ b/apps/desktop/src/main/sessionNotificationCopy.ts@@ -61,3 +61,7 @@ export function getBotGroupStepNotificationBody(event: {.replaceAll('{{name}}', () => event.botName).replaceAll('{{task}}', () => event.task);}++export function getNotificationImageLabel(): string {+ return t('settings.notifications.chat.image');+}diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex d21f5d81b8..e5462812f7 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -699,7 +699,7 @@ export function MainLayout() {(payload:| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }- | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string; conversationKind?: 'direct' }| { type: 'project'; workingDir: string }| { type: 'new-session'; workingDir: string }| { type: 'share-import'; filePath: string }@@ -713,6 +713,7 @@ export function MainLayout() {if (payload.type === 'chat-message') {const search = new URLSearchParams({ messageId: payload.messageId });if (payload.threadRootId) search.set('threadRootId', payload.threadRootId);+ if (payload.conversationKind === 'direct') search.set('conversationKind', 'direct');navigate(`/bots/groups/${encodeURIComponent(payload.groupId)}?${search}`);return;}diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex 7abe357154..de0a57abae 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -189,10 +189,12 @@ function isAttachmentDrag(event: DragEvent): boolean {export function BotGroupChatView() {const { groupId } = useParams();- return <BotGroupChatContent key={groupId ?? ''} groupId={groupId ?? ''} />;+ const { search } = useLocation();+ const direct = new URLSearchParams(search).get('conversationKind') === 'direct';+ return <BotGroupChatContent key={`${groupId}:${direct}`} groupId={groupId ?? ''} direct={direct} />;}-function BotGroupChatContent({ groupId }: { groupId: string }) {+function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boolean }) {const { t, i18n } = useTranslation();const locale = i18n.language;const controlledBy = useControlledBy();@@ -277,8 +279,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {// Older pages are not re-read, so their shares ask for the reply's current state.const shownShares = shown ? botGroupShownShares(displayed.older) : [];const result = sourceMessageIds.length || shownShares.length- ? await api.getBotGroup(groupId, { sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })- : await api.getBotGroup(groupId);+ ? await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })+ : await api.getBotGroup(groupId, direct ? { conversationKind: 'direct' } : undefined);if (!isApplicable()) return;if (result.ok) {readOwner.current = owner;@@ -304,7 +306,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {if (displayed.kind === 'ready' && displayed.group.id === groupId && result.group.messages.length > 0) {const latestFrom = Math.min(...result.group.messages.map((message) => message.sequence));const refreshed = await refreshPendingBotGroupAttachments(displayed.older, latestFrom, async (before) => {- const page = await api.getBotGroup(groupId, { beforeSequence: before });+ const page = await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), beforeSequence: before });return page.ok && isCurrent() ? page.group.messages : null;});if (refreshed && isCurrent()) {@@ -361,7 +363,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {for (let page = 0; remaining.length > 0 && page < targets.length; page += 1) {let messages: BotGroupMessageView[] | null = null;try {- const read = await api.getBotGroup(groupId, { beforeSequence: remaining[0]!.sequence + 1 });+ const read = await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), beforeSequence: remaining[0]!.sequence + 1 });messages = read.ok ? read.group.messages : null;} catch {messages = null;@@ -542,7 +544,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {const latest = readMessages.current.at(-1);if (current.kind === 'ready' && current.group.serverUnread && latest && readRequest.current !== latest.id) {readRequest.current = latest.id;- void window.electronAPI.maker.chatServer.manage({ groupId, action: { type: 'read', messageId: latest.id } })+ void window.electronAPI.maker.chatServer.manage({ groupId, action: { type: 'read', messageId: latest.id, ...(direct ? { conversationKind: 'direct' as const } : {}) } }).then(result => { if (!result.ok && readRequest.current === latest.id) readRequest.current = null; }).catch(() => { if (readRequest.current === latest.id) readRequest.current = null; });}@@ -580,10 +582,11 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {state.kind === 'ready' && (state.older.length > 0 ? state.olderHasMore : state.group.hasMoreBefore);const openSettings = useCallback(() => {+ if (direct) return;const search = new URLSearchParams(location.search);search.set(BOT_GROUP_SETTINGS_PARAM, '1');navigate(`${location.pathname}?${search.toString()}`);- }, [location.pathname, location.search, navigate]);+ }, [direct, location.pathname, location.search, navigate]);const separator = t('bots.groupChat.memberSeparator');const [threadRootId, setThreadRootId] = useState<string | null>(null);@@ -662,16 +665,17 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {<div ref={threadHeaderRef} data-testid="bot-group-content-header" className="flex h-full w-full min-w-0 items-center gap-2 pr-2"><buttontype="button"- onClick={openSettings}+ onClick={direct ? undefined : openSettings}+ disabled={direct}className="flex min-w-0 items-center gap-2 rounded-xl px-2 py-1 text-left hover:bg-[var(--surface-hover)]"style={WINDOW_NO_DRAG_STYLE}>- <BotGroupAvatarStack members={members} />+ <BotGroupAvatarStack members={direct ? members.filter(member => !member.isSelf) : members} /><span className="flex min-w-0 flex-col"><span className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{headerGroup.name}</span><span className="flex min-w-0 items-center gap-2 text-11 leading-4 text-[var(--text-tertiary)]"><span className="hidden min-w-0 items-center gap-1 truncate sm:flex" title={names}>- {members.map((member, index) => (+ {(direct ? members.filter(member => !member.isSelf) : members).map((member, index) => (<Fragment key={member.botId}>{index > 0 ? <span aria-hidden>{separator}</span> : null}<span className="shrink-0">{botGroupMemberDisplayName(member)}</span>@@ -685,7 +689,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {</button><div className="ml-auto flex shrink-0 items-center">{headerGroup.serverBacked && headerGroup.canInvite && <ChatInviteButton groupId={headerGroup.id} />}- <Tip text={settingsLabel}>+ {!direct && <Tip text={settingsLabel}><buttontype="button"onClick={openSettings}@@ -695,11 +699,11 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {><Settings2 size={15} /></button>- </Tip>+ </Tip>}</div></div>);- }, [headerGroup?.name, headerGroup?.id, headerGroup?.serverBacked, headerGroup?.canInvite, members, organizerBotId, headerStatus, openSettings, separator, settingsLabel]);+ }, [direct, headerGroup?.name, headerGroup?.id, headerGroup?.serverBacked, headerGroup?.canInvite, members, organizerBotId, headerStatus, openSettings, separator, settingsLabel]);useRegisterContentHeader(header);const running = group?.round.status === 'running';@@ -752,7 +756,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {setLoadingOlder(true);try {const sourceMessageIds = loaded.map(message => message.id);- const result = await api.getBotGroup(groupId, { beforeSequence: before, sourceMessageIds });+ const result = await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), beforeSequence: before, sourceMessageIds });if (!isDataOwnerGenerationCurrent(owner)) return null;if (!result.ok) {toast.error(t('bots.groupChat.timeline.loadEarlierFailed'));@@ -1208,13 +1212,13 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {locale={locale}shareScope={shareScope}sharing={sharing}- reactionGroupId={group.serverBacked ? group.id : undefined}+ reactionGroupId={group.serverBacked && !direct ? group.id : undefined}reactionRevision={messageReactionRevision(group, message.id)}readOnly={Boolean(group.archived || group.dissolvedAt)}quoteDisplay={quoteDisplays.get(message.id)?.display}onLocateQuote={onLocateQuote}onQuote={quotable ? onQuote : undefined}- onOpenThread={group.serverBacked && !message.pending ? onOpenThread : undefined}+ onOpenThread={group.serverBacked && !direct && !message.pending ? onOpenThread : undefined}onChanged={onChanged}highlighted={highlightId === message.id}focusable={jumpTarget === message.id || highlightId === message.id}@@ -1302,6 +1306,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 760} /> : group.archived || group.dissolvedAt ? <p className="border-t border-[var(--border-default)] p-4 text-center text-13 text-[var(--text-tertiary)]">{t(group.dissolvedAt ? 'bots.groupChat.lifecycle.dissolved' : 'bots.groupChat.server.settings.archived')}</p> : <BotGroupComposergroupId={group.id}+ conversationKind={direct ? 'direct' : undefined}draftKey={attachmentScope}members={group.members}running={running}diff --git a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsxindex 1b1edc2739..eb21e93059 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx@@ -164,6 +164,7 @@ const NO_ATTACHMENTS: BotGroupComposerAttachments = {export function BotGroupComposer({groupId,mode = 'group',+ conversationKind,draftKey,members,running,@@ -183,6 +184,7 @@ export function BotGroupComposer({footerStart,}: {groupId: string;+ conversationKind?: 'direct';/** `thread`: a 话题's reply box (no 「+」 menu, attachments or quotes). */mode?: 'group' | 'thread';/** Where the unsent text is kept (the group's attachment scope, or the 话题's own key). */@@ -406,6 +408,7 @@ export function BotGroupComposer({const sentQuote = quoteRef.current;const fields = {groupId,+ ...(conversationKind ? { conversationKind } : {}),text: trimmed,mentions,...(division ? { division: true } : {}),@@ -667,7 +670,7 @@ export function BotGroupComposer({{t('extraDirs.addFiles')}</span></DropdownMenuItem>- <DropdownMenuItem+ {conversationKind !== 'direct' && <DropdownMenuItemdisabled={divisionBlocked}className={cn(MENU_ITEM_CLASS, 'h-auto items-start gap-2.5 py-2')}onSelect={() => {@@ -688,7 +691,7 @@ export function BotGroupComposer({)}</span></span>- </DropdownMenuItem>+ </DropdownMenuItem>}</DropdownMenuContent></DropdownMenu></>)}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex eb03ab5c97..96b697a41d 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1946,7 +1946,20 @@"wecomGroupToggleFailed": "Could not update WeCom group notifications","wecomGroupClear": "Remove","wecomGroupCleared": "Webhook removed",- "wecomGroupClearFailed": "Could not remove the Webhook"+ "wecomGroupClearFailed": "Could not remove the Webhook",+ "chat": {+ "image": "Image",+ "audio": "Voice message",+ "video": "Video",+ "file": "File",+ "message": "New message",+ "teammate": "Teammate",+ "sender": "Unknown sender",+ "mention": "Mentioned you",+ "reply": "Replied to you",+ "threadReply": "Thread reply",+ "thread": "Thread"+ }},"windowBehavior": {"menubar": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a53ff7f519..3cd21b5826 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1917,7 +1917,20 @@"wecomGroupToggleFailed": "WeCom グループ通知の設定を更新できませんでした","wecomGroupClear": "削除","wecomGroupCleared": "Webhook を削除しました",- "wecomGroupClearFailed": "Webhook を削除できませんでした"+ "wecomGroupClearFailed": "Webhook を削除できませんでした",+ "chat": {+ "image": "画像",+ "audio": "音声メッセージ",+ "video": "動画",+ "file": "ファイル",+ "message": "新しいメッセージ",+ "teammate": "パートナー",+ "sender": "不明な送信者",+ "mention": "あなたにメンション",+ "reply": "あなたに返信",+ "threadReply": "スレッドへの返信",+ "thread": "スレッド"+ }},"windowBehavior": {"menubar": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b926f5632e..cc39179433 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1917,7 +1917,20 @@"wecomGroupToggleFailed": "WeCom 그룹 알림 설정을 업데이트하지 못했습니다","wecomGroupClear": "삭제","wecomGroupCleared": "Webhook을 삭제했습니다",- "wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다"+ "wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다",+ "chat": {+ "image": "이미지",+ "audio": "음성 메시지",+ "video": "동영상",+ "file": "파일",+ "message": "새 메시지",+ "teammate": "파트너",+ "sender": "알 수 없는 발신자",+ "mention": "나를 멘션함",+ "reply": "내게 답장함",+ "threadReply": "스레드 답장",+ "thread": "스레드"+ }},"windowBehavior": {"menubar": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 215d56cdcb..3aeec1a17e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1917,7 +1917,20 @@"wecomGroupToggleFailed": "企业微信群通知开关更新失败","wecomGroupClear": "移除","wecomGroupCleared": "Webhook 已移除",- "wecomGroupClearFailed": "Webhook 移除失败"+ "wecomGroupClearFailed": "Webhook 移除失败",+ "chat": {+ "image": "图片",+ "audio": "语音",+ "video": "视频",+ "file": "文件",+ "message": "新消息",+ "teammate": "伙伴",+ "sender": "未知发送者",+ "mention": "提到了你",+ "reply": "回复了你",+ "threadReply": "话题新回复",+ "thread": "话题"+ }},"windowBehavior": {"menubar": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0e823f9a27..c69940bd54 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1917,7 +1917,20 @@"wecomGroupToggleFailed": "企業微信群通知開關更新失敗","wecomGroupClear": "移除","wecomGroupCleared": "Webhook 已移除",- "wecomGroupClearFailed": "Webhook 移除失敗"+ "wecomGroupClearFailed": "Webhook 移除失敗",+ "chat": {+ "image": "圖片",+ "audio": "語音",+ "video": "影片",+ "file": "檔案",+ "message": "新訊息",+ "teammate": "夥伴",+ "sender": "未知傳送者",+ "mention": "提到了你",+ "reply": "回覆了你",+ "threadReply": "話題新回覆",+ "thread": "話題"+ }},"windowBehavior": {"menubar": {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex ef7f63c65f..344770979b 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3056,7 +3056,7 @@ interface ElectronAPI {callback: (payload:| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }- | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string; conversationKind?: 'direct' }| { type: 'project'; workingDir: string }| { type: 'new-session'; workingDir: string }| { type: 'share-import'; filePath: string }@@ -3077,7 +3077,7 @@ interface ElectronAPI {*/takePendingDeepLink: () => Promise<| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }- | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string; conversationKind?: 'direct' }| { type: 'project'; workingDir: string }| { type: 'new-session'; workingDir: string }| { type: 'share-import'; filePath: string }diff --git a/apps/desktop/src/shared/markdownPreviewText.ts b/apps/desktop/src/shared/markdownPreviewText.tsindex 75a9660cb8..9cc9455190 100644--- a/apps/desktop/src/shared/markdownPreviewText.ts+++ b/apps/desktop/src/shared/markdownPreviewText.ts@@ -2,6 +2,7 @@ import type { Nodes } from 'mdast';import remarkGfm from 'remark-gfm';import remarkParse from 'remark-parse';import { unified } from 'unified';+import { richAnswerText } from '@cindy/maker-shared/rich-answer';import { htmlImgToImageNode } from './htmlImage';@@ -10,11 +11,11 @@ const previewParser = unified().use(remarkParse).use(remarkGfm);/** Extract readable text without HTML output or link destinations. */export function markdownPreviewText(markdown: string,- options: { includeImageAlt?: boolean } = {},+ options: { includeImageAlt?: boolean; imageFallback?: string } = {},): string {// Marked's link regex can backtrack for minutes on short bracketed code spans.// These previews run on Main after DB replies, so use the existing remark parser.- const stack: Array<Nodes | string> = [previewParser.parse(markdown)];+ const stack: Array<Nodes | string> = [previewParser.parse(richAnswerText(markdown))];const parts: string[] = [];const includeImageAlt = options.includeImageAlt !== false;while (stack.length > 0) {@@ -33,10 +34,13 @@ export function markdownPreviewText(break;case 'image':case 'imageReference':- if (includeImageAlt) parts.push(node.alt ?? '');+ if (includeImageAlt) parts.push(node.alt?.trim() || options.imageFallback || '');break;case 'html':- if (includeImageAlt) parts.push(htmlImgToImageNode(node)?.alt ?? '', ' ');+ if (includeImageAlt) {+ const image = htmlImgToImageNode(node);+ if (image) parts.push(image.alt?.trim() || options.imageFallback || '', ' ');+ }break;case 'definition':break;diff --git a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatConnectionService.kt b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatConnectionService.ktindex 400611f9e1..0a3c87ba3d 100644--- a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatConnectionService.kt+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatConnectionService.kt@@ -24,7 +24,7 @@ import java.util.concurrent.Executorsimport java.util.concurrent.TimeUnitinternal data class ChatConnection(val owner: String, val actor: String, val base: String, val token: String,- val title: String, val stopLabel: String, val preview: Boolean)+ val title: String, val stopLabel: String, val preview: Boolean, val language: String = "en")/** User-visible, opt-in socket. No boot receiver, hidden restart or stored access token. */class ChatConnectionService : Service() {@@ -108,7 +108,7 @@ class ChatConnectionService : Service() {private fun current(config: ChatConnection) = !stopped && active === config && configuration?.owner == config.ownerprivate fun get(config: ChatConnection, path: String): String {check(current(config))- http.newCall(Request.Builder().url(config.base + "/v1" + path).header("Authorization", "Bearer ${config.token}").build()).execute().use { response ->+ http.newCall(Request.Builder().url(config.base + "/v1" + path).header("Authorization", "Bearer ${config.token}").header("Accept-Language", config.language).build()).execute().use { response ->if (response.code == 401) handler.post { refreshRequested?.invoke() }check(response.isSuccessful) { "CHAT_REQUEST_FAILED" }val body = response.body ?: throw Exception("CHAT_EMPTY_RESPONSE")diff --git a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatDelivery.kt b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatDelivery.ktindex eeadebfd63..2bb7252467 100644--- a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatDelivery.kt+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatDelivery.kt@@ -43,8 +43,7 @@ object ChatDelivery {prefs.edit().putString("ids", next.toString()).apply()}val display = data.toMutableMap()- if (body.optString("category") == "chat-message" &&- !context.getSharedPreferences("cindy-chat-background", Context.MODE_PRIVATE).getBoolean("preview", true)) {+ if (!context.getSharedPreferences("cindy-chat-background", Context.MODE_PRIVATE).getBoolean("preview", true)) {body.remove("sender"); body.remove("senderName"); body.remove("body")display["body"] = body.toString(); display["message"] = ""}@@ -65,7 +64,8 @@ class ChatNotificationsService : NotificationsService() {val data = content.body ?: return originalval chat = data.optString("category") == "chat-message"val sender = data.optJSONObject("sender")- if (!chat && (data.optString("category") != "session-done" || sender == null)) return original+ if (!chat && (data.optString("category") !in listOf("session-done", "session-error", "session-needs-reply") || sender == null)) return original+ val group = chat && data.optString("conversationKind") != "direct"val name = if (chat) data.optString("senderName") else content.title ?: ""if (name.isBlank()) return originalval person = Person.Builder().setName(name).setKey(sender?.optString("id") ?: name)@@ -75,7 +75,7 @@ class ChatNotificationsService : NotificationsService() {.setCategory(NotificationCompat.CATEGORY_MESSAGE).setVisibility(NotificationCompat.VISIBILITY_PRIVATE).setOnlyAlertOnce(true).setStyle(NotificationCompat.MessagingStyle(Person.Builder().setName("Cindy").build())- .setConversationTitle(if (chat) content.title else null).setGroupConversation(chat)+ .setConversationTitle(if (group) content.title else null).setGroupConversation(group).addMessage(text, notification.originDate.time.takeIf { it > 0 } ?: System.currentTimeMillis(), person)).build()}}diff --git a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/CindyChatNotificationsModule.kt b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/CindyChatNotificationsModule.ktindex 142679c17e..9b27c75a8b 100644--- a/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/CindyChatNotificationsModule.kt+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/CindyChatNotificationsModule.kt@@ -27,13 +27,13 @@ class CindyChatNotificationsModule : Module() {appContext.reactContext?.getSharedPreferences("cindy-chat-background", android.content.Context.MODE_PRIVATE)?.edit()?.putBoolean("preview", enabled)?.apply()}- AsyncFunction("configure") { owner: String, actor: String, baseUrl: String, token: String, title: String, stop: String, preview: Boolean ->+ AsyncFunction("configure") { owner: String, actor: String, baseUrl: String, token: String, title: String, stop: String, preview: Boolean, language: String? ->val context = appContext.reactContext ?: throw Exception("CHAT_CONTEXT_UNAVAILABLE")val endpoint = URI(baseUrl)require(endpoint.scheme == "https" && endpoint.host != null && endpoint.userInfo == null && endpoint.query == null && endpoint.fragment == null) { "CHAT_ENDPOINT_INVALID" }require(token.isNotBlank() && token.length <= 16000 && actor.length <= 128 && owner.length <= 512)ChatDelivery.identity(context, actor)- ChatConnectionService.configure(ChatConnection(owner, actor, baseUrl.trimEnd('/'), token, title, stop, preview))+ ChatConnectionService.configure(ChatConnection(owner, actor, baseUrl.trimEnd('/'), token, title, stop, preview, language ?: "en"))// Only a visible activity can initiate the foreground service. Token updates// from an already-running service never start/restart an application.if (!ChatConnectionService.running) {diff --git a/apps/mobile/modules/cindy-chat-notifications/src/index.ts b/apps/mobile/modules/cindy-chat-notifications/src/index.tsindex a3d3ce8f62..8cd2c2fe9b 100644--- a/apps/mobile/modules/cindy-chat-notifications/src/index.ts+++ b/apps/mobile/modules/cindy-chat-notifications/src/index.ts@@ -1,6 +1,6 @@import { requireOptionalNativeModule } from 'expo-modules-core';export interface ChatNotificationsNative {- configure(owner: string, actor: string, baseUrl: string, accessToken: string, title: string, stopLabel: string, preview: boolean): Promise<void>;+ configure(owner: string, actor: string, baseUrl: string, accessToken: string, title: string, stopLabel: string, preview: boolean, language?: string): Promise<void>;stop(): Promise<void>;isPaused(): Promise<boolean>;resume(): Promise<void>;diff --git a/apps/mobile/plugins/communication-notifications/NotificationService.swift b/apps/mobile/plugins/communication-notifications/NotificationService.swiftindex f39b8ad1f6..90c936f206 100644--- a/apps/mobile/plugins/communication-notifications/NotificationService.swift+++ b/apps/mobile/plugins/communication-notifications/NotificationService.swift@@ -21,7 +21,8 @@ final class NotificationService: UNNotificationServiceExtension {let content = request.contentlet category = content.userInfo["category"] as? Stringlet isChat = category == "chat-message"- guard category == "session-done" || isChat,+ let isGroup = isChat && (content.userInfo["conversationKind"] as? String) != "direct"+ guard ["session-done", "session-error", "session-needs-reply"].contains(category ?? "") || isChat,let senderData = content.userInfo["sender"] as? [String: Any],let id = senderData["id"] as? String, !id.isEmpty, id.utf8.count <= 128,!content.title.isEmpty, !content.threadIdentifier.isEmpty else {@@ -44,7 +45,7 @@ final class NotificationService: UNNotificationServiceExtension {recipients: nil,outgoingMessageType: .outgoingMessageText,content: message,- speakableGroupName: isChat ? INSpeakableString(spokenPhrase: content.title) : nil,+ speakableGroupName: isGroup ? INSpeakableString(spokenPhrase: content.title) : nil,conversationIdentifier: content.threadIdentifier,serviceName: nil,sender: sender,diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex e5a905c7b9..79a2dadaeb 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -37,6 +37,15 @@ describe('direct Chat Server client', () => {expect(deleted.messages[0].quote).toMatchObject({ messageId: id(20), originalDeleted: true });});+ it('opens a direct notification with the peer identity and no group leave control', () => {+ const source = snapshot();+ const peer = { ...source.members[0]!, id: id(12), kind: 'human' as const, name: 'Chris', state: 'joined' };+ const view = chatGroupView({ snapshot: { ...source, room: { ...source.room, kind: 'direct', name: '' }, members: [...source.members, peer] },+ messages: [message(20)], before: null }, source.members[0]!.id);+ expect(view).toMatchObject({ conversationKind: 'direct', name: 'Chris', supportsGroupLeave: false });+ expect(view.messages).toHaveLength(1);+ });+it('names the home computer of my own companions from the account actors, never of other members', () => {const mine = { id: id(12), kind: 'bot' as const, name: 'Mine', state: 'joined', ownerActorId: id(11), ownerName: '', avatar: null, role: 'member' as const };const theirs = { id: id(13), kind: 'bot' as const, name: 'Theirs', state: 'joined', ownerActorId: id(10), ownerName: '', avatar: null, role: 'member' as const };diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 0d4a3b6c83..c31a67b211 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -204,7 +204,9 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly Cconst member = members.find(candidate => candidate.id === failure.botId);return [{ ...failure, botName: member ? memberName(member) : '' }];});- return { id: room.id, name: room.name, serverBacked: true, supportsGroupLeave: true, dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,+ return { id: room.id, conversationKind: room.kind === 'direct' ? 'direct' : 'group',+ name: room.kind === 'direct' ? active.filter(member => member.id !== selfId).map(memberName).join(', ') || room.name : room.name,+ serverBacked: true, supportsGroupLeave: room.kind !== 'direct', dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,revision: room.revision, members: memberViews, replyMode: room.response_mode, speakingMode: room.speaking_mode,organizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),diff --git a/apps/mobile/src/notifications/ChatBackgroundBridge.tsx b/apps/mobile/src/notifications/ChatBackgroundBridge.tsxindex bae5364099..1115b09033 100644--- a/apps/mobile/src/notifications/ChatBackgroundBridge.tsx+++ b/apps/mobile/src/notifications/ChatBackgroundBridge.tsx@@ -8,7 +8,7 @@ import { readPushEnabled, readPushPreviewEnabled, subscribePushPreferences } fro/** The existing auth owner rotates tokens; Android receives only a current in-memory copy. */export function ChatBackgroundBridge() {const api = useChatClient();- const { t } = useTranslation();+ const { t, i18n } = useTranslation();useEffect(() => {const native = Native;if (!native) return;@@ -32,7 +32,7 @@ export function ChatBackgroundBridge() {const [base, token] = await Promise.all([api.endpoint(), api.token()]);if (cancelled || !api.current() || !token) return;await native.configure(api.owner, actor, base, token,- t('settings.notifications.backgroundActive'), t('settings.notifications.backgroundStop'), preview);+ t('settings.notifications.backgroundActive'), t('settings.notifications.backgroundStop'), preview, i18n.language);} catch { /* Foreground and the service's next token refresh retry transient failures. */ }finally {refreshing = false;@@ -48,6 +48,6 @@ export function ChatBackgroundBridge() {const background = subscribeChatBackground(() => { void update(); });void update();return () => { cancelled = true; state.remove(); refresh.remove(); prefs(); background(); void native.stop(); void native.setIdentity(''); };- }, [api, t]);+ }, [api, t, i18n.language]);return null;}diff --git a/apps/mobile/src/notifications/pushNotifications.ts b/apps/mobile/src/notifications/pushNotifications.tsindex e0ee662f82..a293367329 100644--- a/apps/mobile/src/notifications/pushNotifications.ts+++ b/apps/mobile/src/notifications/pushNotifications.ts@@ -1,3 +1,4 @@+import { i18n } from '@/i18n';import AsyncStorage from '@react-native-async-storage/async-storage';import { Platform } from 'react-native';import type { ClientEndpointRegion } from '@cindy/maker-shared/client-endpoints';@@ -200,7 +201,7 @@ function pushTargets(realm: ClientEndpointRegion) {}async function mutatePushTokens(apiFetch: AuthedApiFetch, realm: ClientEndpointRegion, method: 'PUT' | 'DELETE', body?: unknown) {const results = await Promise.allSettled(pushTargets(realm).map(async target => {- try { await apiFetch(target.path, { baseUrl: target.baseUrl, method, ...(body ? { body: target.optional ? body : Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'preview')) } : {}) }); }+ try { await apiFetch(target.path, { baseUrl: target.baseUrl, method, headers: { 'Accept-Language': i18n.language || 'en' }, ...(body ? { body } : {}) }); }catch (error) {// An older chat server can roll forward independently of existing task pushes.if (target.optional && [404, 405].includes((error as { status?: number }).status ?? 0)) return;diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex 3d9dc094f5..b7cdd303b8 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -72,7 +72,7 @@ import {BotGroupDuoAvatar,useBotGroupIdentities,} from './BotGroupAvatars';-import { CHAT_HEADER_BLUR_FADE_INSIDE, ChatIdentityHeader } from './ChatIdentityHeader';+import { CHAT_HEADER_MARK_SIZE, CHAT_HEADER_BLUR_FADE_INSIDE, ChatIdentityHeader } from './ChatIdentityHeader';import { SessionHeaderNativeBlur } from './SessionHeaderNativeControls';import { CompanionEntering, CompanionFadeIn } from './CompanionEntering';import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';@@ -361,13 +361,15 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n};const title = group?.name ?? (cachedRow ? resolveRemoteText(cachedRow.item.display.title, i18n.language) : '');- const memberLine = group+ const direct = group?.conversationKind === 'direct';+ const peer = direct ? group.members.find(member => !member.isSelf) : undefined;+ const memberLine = direct ? '' : group? botGroupMemberNames(group.members, t('groupChat.memberSeparator')): cachedRow?.item.display.subtitle ? resolveRemoteText(cachedRow.item.display.subtitle, i18n.language) : '';const headerMembers = group ? group.members.map((member) => identityFor(member.botId, member.name)) : [];const header = <ChatIdentityHeader testIDPrefix="botGroup" settingsTestID="botGroup.settingsButton" nativeHeader={nativeHeader}- mark={<BotGroupDuoAvatar deviceId={deviceId} members={headerMembers} online={chat.online} variant="header"+ mark={peer ? <BotGroupAvatar deviceId={deviceId} identity={identityFor(peer.botId, peer.name)} size={CHAT_HEADER_MARK_SIZE} online={chat.online} /> : <BotGroupDuoAvatar deviceId={deviceId} members={headerMembers} online={chat.online} variant="header"working={group?.round.status === 'running'} />}title={title}subtitle={threadRootId ? t('message.renderer.reply') : memberLine}@@ -375,7 +377,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, nidentityHint={t('groupChat.settings.open')}controlsReady={!!group}onBack={threadRootId ? () => router.replace(`/companions/groups/${groupId}?messageId=${threadRootId}` as never) : leave}- onOpenSettings={() => setSettings(true)}+ onOpenSettings={direct ? undefined : () => setSettings(true)}settingsLabel={t('groupChat.settings.open')} />;const offlineNote = group && !chat.online@@ -482,7 +484,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n{header}{body}</>}- {group ? <BotGroupSettingsSheet readOnly={chat.server} visible={settings} group={group} host={host} identityFor={identityFor} online={chat.online}+ {group && !direct ? <BotGroupSettingsSheet readOnly={chat.server} visible={settings} group={group} host={host} identityFor={identityFor} online={chat.online}act={actFromSettings} onClose={() => setSettings(false)}onRefresh={chat.reload}onClosed={() => { if (leaveAfterSettings.current) { leaveAfterSettings.current = false; leave(); } }}diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.tsindex 498fa35c41..29ca376438 100644--- a/apps/mobile/src/session/messageMarkdown.ts+++ b/apps/mobile/src/session/messageMarkdown.ts@@ -1,3 +1,4 @@+import { richAnswerText } from '@cindy/maker-shared/rich-answer';import { normalizeMathDelimiters } from '@cindy/maker-shared/math-markdown';import {BARE_HTTP_URL_RE_SOURCE,@@ -71,7 +72,7 @@ export type MobileMarkdownBlock =/** Plain summaries share the message parser, keeping labels and omitting link destinations. */export function mobileMarkdownPreviewText(markdown: string): string {const inlineText = (inlines: MobileMarkdownInline[]) => inlines.map(inline => inline.type === 'image' ? inline.alt : inline.text).join('');- return parseMobileMarkdown(markdown).map(block => {+ return parseMobileMarkdown(richAnswerText(markdown)).map(block => {if ('inlines' in block) return inlineText(block.inlines);if (block.type === 'table') return [...block.header, ...block.rows.flatMap(row => row.cells)].map(inlineText).join(' ');return block.text;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 67b785d7db..fe6d2aa091 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -3432,3 +3432,10 @@ namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独分享的刷新通知复用已有 `maker:provider:changed` 空载荷,只发给当前被授权的接收方,并核对对应 host。自定义 API 不进入这套策略与新增刷新规则。详细范围及验证见[订阅 Fast 控制交接说明](../subscription-fast-policy.md)。+++### 聊天通知内容与私聊落点(#7046)++聊天推送增量携带 `conversationKind`,新原生端以此区分私聊/群通讯样式,旧端继续使用原通知。手机 `Accept-Language` 只控制服务端固定提示词,真实原文不翻译;云注册到两个服务都保留显式 preview 选择,旧请求缺省 true。完整任务通知预览关闭需要服务端先支持新列/字段;不添加隐私确认或更改默认预览。++Desktop 在通知点击事件携带可选 `conversationKind: direct`,落入现有时间线的明确私聊模式。`getBotGroup` options、`sendBotGroupMessage` input 与 `manage` 的 read action 的同名可选字段仅用于此模式,主进程读取实际 kind 后确认;普通群入口仍拒绝 direct/channel。私聊不提供群设置、邀请、分工或群话题操作,已读通过既有 read action、发送保留原幂等/引用/附件路径。手机由实际 snapshot.kind 决定私聊标题和单人头像;内部 groups 路径保持旧通知链接兼容,不改变服务器成员权限。此入口补齐通知的阅读/回应,不改伙伴主任务/接管编排。diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex c035393e54..578abbe786 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -446,6 +446,8 @@ export interface BotGroupRoundView {}export interface BotGroupSummary {+ /** Explicit direct-message landing; group management remains unavailable. */+ conversationKind?: 'direct' | 'group';serverBacked?: boolean;/** Authoritative unread window for this account, including followed thread replies. */serverUnread?: { count: number; mentioned: boolean };@@ -599,6 +601,7 @@ export interface BotGroupSetMembersInput {}export interface BotGroupSendInput {+ conversationKind?: 'direct';groupId: string;text: string;mentions: BotGroupMention;@@ -627,6 +630,7 @@ export interface BotGroupPlanEditInput extends BotGroupPlanActionInput {}export interface BotGroupGetOptions {+ conversationKind?: 'direct';/** Load messages with a smaller sequence (older page). */beforeSequence?: number;limit?: number;@@ -801,7 +805,7 @@ export interface ChatInvitePreview {reusable?: boolean;}export type ChatGroupAction =- | { type: 'read'; messageId: string }+ | { type: 'read'; messageId: string; conversationKind?: 'direct' }| { 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 } }