Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(agent-island): 接入群消息未读提醒
Dash18634b68754f
diff --git a/apps/desktop/native/agent-island/macos-agent-island-helper.swift b/apps/desktop/native/agent-island/macos-agent-island-helper.swiftindex c9f6945d40..4800cc0ccc 100644--- a/apps/desktop/native/agent-island/macos-agent-island-helper.swift+++ b/apps/desktop/native/agent-island/macos-agent-island-helper.swift@@ -1376,6 +1376,7 @@ struct AgentIslandCompanion: Codable, Equatable {}struct AgentIslandSession: Codable, Equatable, Identifiable {+ var groupChat: AgentIslandGroupChat? = nillet sessionId: Stringvar completionToken: String? = nillet title: String@@ -1399,6 +1400,11 @@ struct AgentIslandSession: Codable, Equatable, Identifiable {var subtitle: String { compactDetail }}+struct AgentIslandGroupChat: Codable, Equatable {+ let avatars: [AgentIslandCompanion]+ let mentionLabel: String?+}+struct AgentIslandPillSnapshot: Codable {let priorityId: String?let priorityStatus: String@@ -3487,7 +3493,9 @@ struct ExpandedSessionRow: View, Equatable {private var rowMainContent: some View {HStack(alignment: .center, spacing: 10) {Group {- if let companion = session.companion {+ if let group = session.groupChat {+ AgentIslandGroupAvatar(group: group, size: expandedRowLeadingSize)+ } else if let companion = session.companion {AgentIslandCompanionStatusAvatar(session: session, companion: companion, size: expandedRowLeadingSize)} else {StatusDot(@@ -3747,12 +3755,15 @@ struct ExpandedSessionHeaderLine: View {/// A finished companion turn reads as a message: the reply is the content, no "Done" tag.private var isCompanionReply: Bool {- session.companion != nil && session.phase == "completed"+ (session.companion != nil || session.groupChat != nil) && session.phase == "completed"}private var titleText: Text {let title = Text(expandedPrimaryTitle(for: session, strings: strings)).foregroundColor(Color.white.opacity(0.92))+ if let mention = session.groupChat?.mentionLabel {+ return title + Text(" · \(mention)").foregroundColor(Color.white.opacity(0.65))+ }guard let group = companionGroupName else { return title }// The group yields first when the line is too narrow: the speaker stays readable.return title + Text(" · \(group)").foregroundColor(Color.white.opacity(0.42))@@ -4239,7 +4250,9 @@ struct StatusDot: View {var body: some View {let accent = statusAccentColor(for: session)ZStack {- if let companion = session.companion {+ if let group = session.groupChat {+ AgentIslandGroupAvatar(group: group, size: side)+ } else if let companion = session.companion {AgentIslandCompanionStatusAvatar(session: session,companion: companion,@@ -4427,6 +4440,39 @@ final class AgentIslandCompanionAvatarStore {}}+/// Same first-five, first-member-in-front geometry as the teammate sidebar.+struct AgentIslandGroupAvatar: View {+ let group: AgentIslandGroupChat+ let size: CGFloat++ var body: some View {+ let members = Array(group.avatars.prefix(5))+ ZStack(alignment: .topLeading) {+ if members.isEmpty {+ Image(systemName: "person.2.fill")+ .font(.system(size: size * 0.6))+ .foregroundColor(.white.opacity(0.7))+ .frame(width: size, height: size)+ } else if members.count == 1 {+ AgentIslandCompanionAvatar(companion: members[0], size: size)+ } else {+ let diameter = size * (members.count <= 3 ? 0.6 : members.count == 4 ? 0.55 : 0.5)+ let radius = (size - diameter) / 2+ ForEach(Array(members.indices.reversed()), id: \.self) { index in+ let position = members.count - 1 - index+ let angle = -3 * Double.pi / 4 + Double(position) * 2 * Double.pi / Double(members.count)+ let x = members.count == 2 ? (index == 0 ? size - diameter : 0) : radius * (1 + CGFloat(cos(angle)))+ let y = members.count == 2 ? (index == 0 ? size - diameter : 0) : radius * (1 + CGFloat(sin(angle)))+ AgentIslandCompanionAvatar(companion: members[index], size: diameter)+ .overlay(Circle().stroke(Color.black, lineWidth: max(1, size / 20)))+ .offset(x: x, y: y)+ }+ }+ }+ .frame(width: size, height: size)+ }+}+struct AgentIslandCompanionAvatar: View {let companion: AgentIslandCompanionlet size: CGFloatdiff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex c825a2c52c..7be2aee736 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -573,6 +573,89 @@ describe('AgentIslandService native publishing', () => {await import('../service.js');}, 60_000);+ // Unit: native click -> existing chat deep link must preserve unread; group cards never+ // have task archive/read actions, sounds or relay rows. Existing tests only clicked tasks.+ it('opens the exact group/thread message without reading it, and falls back when native publishing fails', async () => {+ const { AgentIslandService } = await import('../service.js');+ setDeepLinkMainWindow(null);+ takePendingDeepLink();+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);+ const playSound = vi.fn();+ const nativeHost = { failed: false, publish, playSound, suspend: () => undefined };+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost });+ syncEnabledForTest(service, publish);+ const input = { groupId: 'group', name: 'Product', messageId: 'message', threadRootId: 'topic',+ mentioned: true, preview: 'Chris: hello', lastMessageAt: 1, members: [] };+ service.setGroupChat(input.groupId, input);+ expect(publish.mock.calls.at(-1)![0].mode).toBe('compact');+ expect(service.notifyGroupChat(input.groupId)).toBe(true);+ expect(publish.mock.calls.at(-1)![0].displayPolicy).toBe('transient');+ expect(playSound).not.toHaveBeenCalled();+ expect(service.getSessionActivitySnapshot('chat-group:group')).toBeNull();+ (service as unknown as { focusSession(id: string): void }).focusSession('chat-group:group');+ expect(takePendingDeepLink()).toEqual({ type: 'chat-message', groupId: 'group', messageId: 'message', threadRootId: 'topic' });+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(1);+ expect(await service.handleCompletionAction('chat-group:group', 'mark-read', 'forged')).toBe(false);+ nativeHost.failed = true;+ expect(service.notifyGroupChat(input.groupId)).toBe(false);+ nativeHost.failed = false;+ publish.mockReturnValue(false);+ expect(service.notifyGroupChat(input.groupId)).toBe(false);+ service.setGroupChat(input.groupId, null);+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(0);+ service.resetRuntimeState();+ });++ it('defers to native notifications when disabled or headless and keeps late avatar reads out of cleared cards', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish } });+ syncEnabledForTest(service, publish);+ let avatar!: (value: string) => void;+ mocks.companionAvatarThumbnail.mockReturnValueOnce(new Promise(resolve => { avatar = resolve; }));+ const input = { groupId: 'group', name: 'Product', messageId: 'message', mentioned: false,+ preview: 'hello', lastMessageAt: 1, members: [{ name: 'Cindy', avatar: 'cindy://avatar/preset/cindy', avatarColor: 'blue' }] };+ service.setGroupChat('group', input);+ service.setEnabled(false);+ expect(service.notifyGroupChat('group')).toBe(false);+ service.setGroupChat('group', null);+ avatar('late-avatar');+ await Promise.resolve();+ service.setEnabled(true);+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(0);+ service.resetRuntimeState();+ const headless = new AgentIslandService({ getMainWindow: () => null, nativeHost: { headless: true, failed: false, publish } });+ headless.setGroupChat('group', { ...input, members: [] });+ headless.setEnabled(true);+ expect(headless.notifyGroupChat('group')).toBe(false);+ headless.resetRuntimeState();+ });++ it('keeps group lane approvals but lets chat unread own the successful reply reminder', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);+ const playSound = vi.fn();+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', title: 'Chris', userSendAt: null,+ workingDir: '/home', workspaceKind: null, source: 'bot' });+ mocks.readAgentIslandCompanion.mockResolvedValue({ botId: 'bot', groupId: 'group',+ companion: { name: 'Chris', groupName: 'Product', hue: 'blue', glyph: 'C', glyphIsInitial: true } });+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish, playSound } });+ syncEnabledForTest(service, publish);+ service.handleUserPrompt({ sessionId: 'lane' }, 'please help');+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.companion?.groupName).toBe('Product'));+ handleInteractionRequestForTest(service, { sessionId: 'lane' }, { kind: 'ask_user_question', requestId: 'q', questions: [] });+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({ phase: 'needs-interaction', attention: true });+ service.handleInteractionDismissed('lane', 'q');+ playSound.mockClear();+ service.handleAgentEvent({ sessionId: 'lane' }, { type: 'done', source: 'codex', data: { result: 'done' } });+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);+ expect(playSound).not.toHaveBeenCalled();+ service.setGroupChat('group', { groupId: 'group', name: 'Product', messageId: 'reply', mentioned: false,+ preview: 'Chris: done', lastMessageAt: Date.now(), members: [] });+ expect(publish.mock.calls.at(-1)?.[0].pillSnapshot.attentionCount).toBe(1);+ service.resetRuntimeState();+ });+// Old unread has no runtime event after restart. Verify the real IPC -> native -> read// route, including owner fencing and stale-card rejection; existing event tests miss this (unit).it('restores companion chats from the owner snapshot and reads offline chats locally', async () => {diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.tsindex 45e05bc188..a034fb4fc9 100644--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts@@ -9,6 +9,8 @@ import {applyAgentIslandInteractionDismissed,applyAgentIslandInteractionRequest,applyAgentIslandMetadata,+ syncAgentIslandGroupChat,+ revealAgentIslandGroupChat,applyAgentIslandUserPrompt,AGENT_ISLAND_COMPLETION_DWELL_MS,AGENT_ISLAND_COMPLETION_REVEAL_DWELL_MS,@@ -107,6 +109,61 @@ describe('companion chat unread projection', () => {const REMOTE_DAEMON_CLOSED_REASON = 'remote_daemon_closed';+// Unit: group unread has no task lifecycle. Cover restore/live/read transitions at the real+// display builder, which the existing companion projection and task-only tests cannot exercise.+describe('group message cards', () => {+ const input = { groupId: 'group', name: 'Product', messageId: 'message', mentioned: false,+ preview: 'Chris: hello', lastMessageAt: 1, members: [] };+ const sync = (state: ReturnType<typeof createAgentIslandState>, extra = {}, now = 100) =>+ syncAgentIslandGroupChat(state, input.groupId, { ...input, ...extra }, [], '@you', now);++ it('restores one persistent unread card silently, without task actions or relay activity', () => {+ const state = createAgentIslandState();+ const now = AGENT_ISLAND_UNREAD_TRANSIENT_TTL_MS * 2;+ sync(state, {}, now);+ const display = buildAgentIslandDisplayState(state, now);+ expect(display.mode).toBe('compact');+ expect(display.pillSnapshot.attentionCount).toBe(1);+ expect(display.sessions[0]).toMatchObject({ title: 'Product', compactDetail: 'Chris: hello', attention: true, groupChat: { avatars: [] } });+ expect(display.sessions[0].completionToken).toBeUndefined();+ expect(buildAllSessionActivitySnapshots(state)).toEqual([]);+ expect(state.remoteUnreadTerminals.size).toBe(0);+ syncAgentIslandGroupChat(state, input.groupId, null, [], '@you', now + 1);+ expect(buildAgentIslandDisplayState(state, now + 1).pillSnapshot.attentionCount).toBe(0);+ });++ it('coalesces a burst in place, does not extend its dwell, and lets a new mention alert', () => {+ const state = createAgentIslandState();+ sync(state);+ revealAgentIslandGroupChat(state, input.groupId, 100);+ expect(buildAgentIslandDisplayState(state, 100).displayPolicy).toBe('transient');+ const until = state.sessions.get('chat-group:group')!.revealUntil!;+ sync(state, { messageId: 'next', preview: 'Sam: next' }, 200);+ revealAgentIslandGroupChat(state, input.groupId, 200);+ expect(state.sessions.get('chat-group:group')!.revealUntil).toBe(until);+ expect(buildAgentIslandDisplayState(state, 200).sessions).toHaveLength(1);+ expect(buildAgentIslandDisplayState(state, until + 1).mode).toBe('compact');+ sync(state, { mentioned: true }, until + 2);+ revealAgentIslandGroupChat(state, input.groupId, until + 2);+ expect(buildAgentIslandDisplayState(state, until + 2).sessions[0].groupChat?.mentionLabel).toBe('@you');+ expect(buildAgentIslandDisplayState(state, until + 2).displayPolicy).toBe('transient');+ });++ it('keeps a pending approval above mentions, and pins existing rows under the pointer', () => {+ const state = createAgentIslandState();+ sync(state);+ revealAgentIslandGroupChat(state, input.groupId, 100);+ syncAgentIslandGroupChat(state, 'other', { ...input, groupId: 'other', mentioned: true }, [], '@you', 100);+ requestAgentIslandManualExpand(state, 101);+ const order = buildAgentIslandDisplayState(state, 101).sessions.map(s => s.sessionId);+ expect(order[0]).toBe('chat-group:other');+ sync(state, { mentioned: true, lastMessageAt: 200 }, 200);+ expect(buildAgentIslandDisplayState(state, 200).sessions.map(s => s.sessionId)).toEqual(order);+ applyAgentIslandInteractionRequest(state, { sessionId: 'approval' }, { kind: 'ask_user_question', requestId: 'q', questions: [] }, 201);+ expect(buildAgentIslandDisplayState(state, 201).sessions[0].sessionId).toBe('approval');+ });+});+type PermissionInteractionRequest = Extract<InteractionRequest, { kind: 'permission' }>;function statusEvent(isRunning: boolean, status: string, turnContinuationId?: number): AgentEvent {diff --git a/apps/desktop/src/main/agent-island/groupChat.ts b/apps/desktop/src/main/agent-island/groupChat.tsnew file mode 100644index 0000000000..626967546d--- /dev/null+++ b/apps/desktop/src/main/agent-island/groupChat.ts@@ -0,0 +1,16 @@+/** An account-owned group projection. Reads and notification eligibility remain owned by Chat Server. */+export interface AgentIslandGroupChatInput {+ groupId: string;+ name: string;+ messageId: string;+ threadRootId?: string;+ mentioned: boolean;+ preview: string;+ lastMessageAt: number;+ members: Array<{ name: string; avatar: string; avatarColor: string }>;+}++/** A UI identity only: it must never be relayed or treated as a maker Session. */+export function groupChatIslandId(groupId: string): string {+ return `chat-group:${groupId}`;+}diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 287dd3194e..cc5a80c3bf 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -27,7 +27,8 @@ import {clearSessionAttention as clearAppBadgeSessionAttention,hasSessionAttention as hasAppBadgeSessionAttention,} from '../appBadgeService.js';-import { openMainWindowSession } from '../deepLink.js';+import { openMainWindowSession, openMainWindowChatMessage } from '../deepLink.js';+import { groupChatIslandId, type AgentIslandGroupChatInput } from './groupChat.js';import {AGENT_ISLAND_CONSUME_ENTRY_ALERT_CHANNEL,AGENT_ISLAND_MAX_RESIZABLE_WIDTH,@@ -101,6 +102,8 @@ import {agentIslandCompletionToken,readAgentIslandUnreadTerminalStamp,applyAgentIslandEvent,+ syncAgentIslandGroupChat,+ revealAgentIslandGroupChat,applyAgentIslandInteractionDismissed,applyAgentIslandInteractionRequest,applyAgentIslandUserPrompt,@@ -834,6 +837,47 @@ export class AgentIslandService {this.publish();}+ setGroupChat(groupId: string, input: AgentIslandGroupChatInput | null): void {+ const sessionId = groupChatIslandId(groupId);+ const previous = this.state.sessions.get(sessionId)?.groupChat;+ if (!input && !previous) return;+ if (input && previous && JSON.stringify(previous.input) === JSON.stringify(input)) return;+ const avatars = input?.members.map((member, index) => {+ const old = previous?.input.members[index];+ return old && JSON.stringify(old) === JSON.stringify(member) ? previous!.avatars[index]!+ : companionSnapshotWithoutArtwork(member);+ }) ?? [];+ syncAgentIslandGroupChat(this.state, groupId, input, avatars, t('bots.groupChat.server.thread.mentionedYou'), Date.now());+ const chat = this.state.sessions.get(sessionId)?.groupChat;+ this.publish();+ if (!input || !chat) return;+ for (const [index, member] of input.members.entries()) {+ if (avatars[index]?.imageJpeg || !companionAvatarHasArtwork(member.avatar)) continue;+ void companionAvatarThumbnail(member.avatar).then(imageJpeg => {+ if (!imageJpeg || this.state.sessions.get(sessionId)?.groupChat !== chat) return;+ chat.avatars[index] = { ...chat.avatars[index]!, imageJpeg };+ this.publish();+ }).catch(() => undefined);+ }+ }++ /** True means this surface owns the alert; otherwise the caller uses the OS notification. */+ notifyGroupChat(groupId: string): boolean {+ if (!this.isEnabled() || this.headless || this.nativeHost.failed) return false;+ const chat = this.state.sessions.get(groupChatIslandId(groupId))?.groupChat;+ if (!chat) return false;+ const window = this.deps.getMainWindow();+ // Thread reads are authoritative; merely being on the group's URL does not read a thread.+ if (!chat.input.threadRootId && window?.isFocused() && window.isVisible()) {+ try {+ if (new URL(window.webContents.getURL()).hash.split('?')[0] === `#/bots/groups/${groupId}`) return true;+ } catch { /* A loading window is not a visible chat. */ }+ }+ revealAgentIslandGroupChat(this.state, groupId, Date.now());+ this.publish();+ return !this.nativeHost.failed && !this.nativeFailureLogged;+ }+private companionChatProjections() {return [...this.companionChats.values()].map(({ input, companion, token }) => ({ ...input, companion, token }));}@@ -1061,7 +1105,7 @@ export class AgentIslandService {suppressCompletionAttention,// Direct IM sends bypass handleUserPrompt. Running preserves unread in the// live state/ledger, so use that state (including any intervening read ack).- preserveCompletionAttention: suppressCompletionAttention && (+ preserveCompletionAttention: suppressCompletionAttention && !this.metadataCache.get(hydrated.sessionId)?.companion?.groupId && (event.turnOrigin?.surface === 'im'? hasAgentIslandSessionAttention(this.state, hydrated.sessionId): this.hadAttentionBeforeSilencedCompletion(hydrated.sessionId)@@ -1602,6 +1646,11 @@ export class AgentIslandService {...rest,...(companion !== undefined ? { companion: companion?.companion ?? null } : {}),})) return;+ // Fast group replies can finish before identity resolves. The reply's chat read position+ // owns completion attention; running, failure and approval cards remain runtime-owned.+ if (companion?.groupId && this.state.sessions.get(sessionId)?.phase === 'completed') {+ completeAgentIslandSessionWithoutAttention(this.state, sessionId, Date.now(), { preserveAttention: false });+ }this.publish();}@@ -1754,6 +1803,7 @@ export class AgentIslandService {private isCompletionEventSilenced(sessionId: string, event: AgentEvent): boolean {if (!isCompletionDoneEvent(event)) return false;return event.agentMeta?.botTaskCoordination === true+ || !!this.metadataCache.get(sessionId)?.companion?.groupId|| event.turnOrigin?.surface === 'im' || this.silencedSessionRunIds.has(sessionId);}@@ -2077,14 +2127,13 @@ export class AgentIslandService {* 只投影哨兵;真实标题与 null 原样透传(null 由 native 走它自己的空标题分支)。*/private localizeDisplayState(state: AgentIslandDisplayState): AgentIslandDisplayState {- if (!state.sessions.some((s) => isDefaultDraftSessionTitle(s.title))) return state;+ if (!state.sessions.some((s) => isDefaultDraftSessionTitle(s.title) || s.groupChat?.mentionLabel)) return state;return {...state,- sessions: state.sessions.map((session) =>- isDefaultDraftSessionTitle(session.title)- ? { ...session, title: t('ccAgent.common.unnamedSession') }- : session,- ),+ sessions: state.sessions.map(session => ({ ...session,+ ...(isDefaultDraftSessionTitle(session.title) ? { title: t('ccAgent.common.unnamedSession') } : {}),+ ...(session.groupChat?.mentionLabel ? { groupChat: { ...session.groupChat, mentionLabel: t('bots.groupChat.server.thread.mentionedYou') } } : {}),+ })),};}@@ -2761,6 +2810,14 @@ export class AgentIslandService {private focusSession(sessionId: string): void {const nextSessionId = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : null;if (!nextSessionId) return;+ const group = this.state.sessions.get(nextSessionId)?.groupChat;+ if (group) {+ // Navigation never acknowledges a group: reading the destination updates the server read position.+ requestAgentIslandManualCollapse(this.state, Date.now());+ this.publish();+ openMainWindowChatMessage(group.input.groupId, group.input.messageId, group.input.threadRootId);+ return;+ }const now = Date.now();const islandEntryId = this.recordIslandEntryAlert(nextSessionId, now);const deviceId = this.state.sessions.get(nextSessionId)?.sourceDeviceId@@ -3169,6 +3226,7 @@ function getAgentIslandSoundEventForTransition(// Visual smart suppression controls unread/reveal state, not configured completion sounds.for (const session of next.sessions) {if (session.phase !== 'completed') continue;+ if (session.groupChat) continue;if (mutedCompletionSessionIds.has(session.sessionId)) continue;const prev = previousById.get(session.sessionId);if (prev?.phase !== 'completed') return 'complete';diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex e8de73e74f..a17759bda1 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -1,4 +1,5 @@import { randomUUID } from 'node:crypto';+import { groupChatIslandId, type AgentIslandGroupChatInput } from './groupChat.js';import { isSubagentParentToolUseId } from '@cindy/maker-shared/message-render';import {isCompactingWorkingStatus,@@ -123,6 +124,13 @@ interface ApplyAgentIslandEventOptions {}interface AgentIslandSessionState {+ groupChat?: {+ input: AgentIslandGroupChatInput;+ avatars: AgentIslandCompanionSnapshot[];+ mentionLabel?: string;+ lastAlertAt: number | null;+ lastAlertMention: boolean;+ };completionNotification?: 'silent';pendingDeviceCompletionNotification?: boolean;sessionId: string;@@ -195,6 +203,7 @@ interface AgentIslandSessionState {const completionTokenEpoch = randomUUID();export function agentIslandCompletionToken(session: AgentIslandSessionState): string | undefined {+ if (session.groupChat) return undefined;if (session.phase !== 'completed') return undefined;if (session.companionChat) return session.companionChat.unread ? session.companionChat.token : undefined;return session.sourceDeviceId ? session.sourceCompletionToken@@ -1612,6 +1621,39 @@ function visibleOverviewSessions(.sort((a, b) => compareSessionsForDisplay(state, a, b, now));}+/** Group cards use the existing transient queue, but server read state alone retires them. */+export function syncAgentIslandGroupChat(+ state: AgentIslandState, groupId: string, input: AgentIslandGroupChatInput | null,+ avatars: AgentIslandCompanionSnapshot[], mentionLabel: string, now: number,+): void {+ const sessionId = groupChatIslandId(groupId);+ if (!input) { removeAgentIslandSession(state, sessionId); return; }+ const session = getOrCreateSession(state, { sessionId }, now);+ const previous = session.groupChat;+ session.groupChat = { input, avatars, mentionLabel: input.mentioned ? mentionLabel : undefined,+ lastAlertAt: previous?.lastAlertAt ?? null, lastAlertMention: previous?.lastAlertMention ?? false };+ session.title = input.name;+ session.detail = input.preview;+ session.phase = 'completed';+ session.completionNotification = 'silent';+ session.unread = true;+ session.sortActivityAt = input.lastMessageAt;+ session.lastActivityAt = input.lastMessageAt;+}++export function revealAgentIslandGroupChat(state: AgentIslandState, groupId: string, now: number): void {+ const session = state.sessions.get(groupChatIslandId(groupId));+ const chat = session?.groupChat;+ if (!session || !chat) return;+ // Same-group bursts replace content in place. A new mention may break the quiet window.+ if (chat.lastAlertAt !== null && now - chat.lastAlertAt < 30_000+ && (!chat.input.mentioned || chat.lastAlertMention)) return;+ chat.lastAlertAt = now;+ chat.lastAlertMention = chat.input.mentioned;+ // A pointer already on the island must not receive a surprise automatic reveal later.+ if (!isPointerInsideIsland(state) && !state.hoverExpanded) enqueueTransientReveal(state, session, now, AGENT_ISLAND_REVEAL_DWELL_MS);+}+/** Chat read positions own reply attention; the runtime still owns errors and interactions.* Reconstruct only the display, so old replies never become new completions, sounds or relay events.*/@@ -1671,7 +1713,7 @@ export function buildAllSessionActivitySnapshots(): AgentIslandSessionSnapshot[] {// 其它设备的任务不进入本机活动快照:否则会被 relay 当作本机任务再推给控制端。const snapshots = Array.from(state.sessions.values())- .filter((session) => session.sourceDeviceId === null)+ .filter((session) => session.sourceDeviceId === null && !session.groupChat).map((session) => toSnapshot(session));const seen = new Set(snapshots.map((snapshot) => snapshot.sessionId));for (const unread of state.remoteUnreadTerminals.values()) {@@ -2207,9 +2249,13 @@ function orderSessionsForCurrentSurface(}const rank = new Map(state.expandedSessionOrder.map((sessionId, index) => [sessionId, index]));+ const hasGroupRows = sortedSessions.some(session => session.groupChat);const ordered = sortedSessions.slice().sort((a, b) => {- const priorityDelta =- islandDisplayPriorityRank(state, a, now) - islandDisplayPriorityRank(state, b, now);+ // With chat rows present, only an actionable task may jump ahead under the pointer.+ // Compare one consistent rank for all pairs, including newly arrived rows.+ const priorityDelta = hasGroupRows+ ? Number(isWaitingSession(b, now)) - Number(isWaitingSession(a, now))+ : islandDisplayPriorityRank(state, a, now) - islandDisplayPriorityRank(state, b, now);if (priorityDelta !== 0) return priorityDelta;const aRank = rank.get(a.sessionId);const bRank = rank.get(b.sessionId);@@ -2740,6 +2786,7 @@ function toSnapshot(session: AgentIslandSessionState): AgentIslandSessionSnapshoconst completionToken = agentIslandCompletionToken(session);return {...(session.phase === 'completed' && session.completionNotification ? { completionNotification: session.completionNotification } : {}),+ ...(session.groupChat ? { groupChat: { avatars: session.groupChat.avatars, mentionLabel: session.groupChat.mentionLabel } } : {}),sessionId: session.sessionId,title: session.companion?.name || session.title || session.projectName || session.sessionId.slice(0, 8),...(completionToken ? { completionToken } : {}),@@ -2795,7 +2842,7 @@ function shouldDisplaySession(function isUnreadTerminalLedger(session: AgentIslandSessionState,): session is AgentIslandSessionState & { phase: 'completed' | 'error' } {- return session.unread && (session.phase === 'completed' || session.phase === 'error');+ return !session.groupChat && session.unread && (session.phase === 'completed' || session.phase === 'error');}function syncRemoteUnreadTerminal(state: AgentIslandState, session: AgentIslandSessionState): void {@@ -2854,6 +2901,7 @@ function isUnreadTerminalWithinIslandTtl(session: AgentIslandSessionState, now:}function isSessionVisible(session: AgentIslandSessionState, now: number, preserveExpiredTransient = false): boolean {+ if (session.groupChat) return true;if (session.companionChat?.unread) return true;if (session.pendingInteractionIds.size > 0) return true;if (session.running) return true;@@ -2912,6 +2960,7 @@ function isWaitingSession(session: AgentIslandSessionState, now: number): boolea}function isUnreadCompletedSession(session: AgentIslandSessionState, now: number): boolean {+ if (session.groupChat) return true;return session.phase === 'completed' && (isUnreadTerminalWithinIslandTtl(session, now) || (session.completedUntil !== null && session.completedUntil > now));}@@ -2941,6 +2990,7 @@ function islandDisplayPriorityRank(unread: isUnreadCompletedSession(session, now),running: session.running,});+ if (session.groupChat?.input.mentioned) return LIVE_TASK_PRIORITY.waiting + 0.25;if (isTransientlyPinnedSession(state, session, now) && live > LIVE_TASK_PRIORITY.waiting) {return LIVE_TASK_PRIORITY.waiting + 0.5;}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.tsindex f6a7ae6c60..33929ebad0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts@@ -1,7 +1,24 @@import { afterEach, expect, it, vi } from 'vitest';-import { createChatMessageNotifications, type ChatNotificationMessage } from '../chatMessageNotifications.js';+import { createChatMessageNotifications, selectChatAttentionMessage, type ChatNotificationMessage } from '../chatMessageNotifications.js';afterEach(() => vi.useRealTimers());++// Unit: the same eligibility feeds both alert surfaces; ensure a mention does not get displaced+// by newer ordinary traffic, and reading/muting its thread reveals the remaining unread message.+it('selects an unread mention first and falls back to ordinary unread after its read position advances', () => {+ const ordinary = message('ordinary', { seq: '9007199254740995' });+ const mention = message('mention', { threadRootId: 'topic', mentions: ['me'] });+ const snapshot = { room: { name: 'Team' }, messages: [ordinary, mention], reads: [+ { thread_key: 'main', read_seq: '0', muted: false }, { thread_key: 'topic', read_seq: '0', muted: false },+ ] };+ expect(selectChatAttentionMessage(snapshot, 'me')).toBe(mention);+ snapshot.reads[1].read_seq = mention.seq;+ expect(selectChatAttentionMessage(snapshot, 'me')).toBe(ordinary);+ snapshot.reads[1].read_seq = '0'; snapshot.reads[1].muted = true;+ expect(selectChatAttentionMessage(snapshot, 'me')).toBe(ordinary);+ snapshot.reads[0].muted = true;+ expect(selectChatAttentionMessage(snapshot, 'me')).toBeNull();+});const message = (id: string, extra: Partial<ChatNotificationMessage> = {}): ChatNotificationMessage => ({id, seq: '9007199254740993', authorId: id, deleted: false, threadRootId: null, ...extra,});@@ -78,3 +95,29 @@ it('recovers a transient snapshot failure and fetches an event outside the latesexpect(notify).toHaveBeenCalledOnce();service.dispose();});++// Unit: a read or mute may arrive while the notification's sender presentation is loading.+// A stale snapshot must neither display a notice nor consume a still-unread message.+it('rechecks read state when the room changes during notification presentation', async () => {+ vi.useFakeTimers();+ let revision = 0;+ const snapshot = { room: { name: 'Team' }, messages: [message('peer')],+ reads: [{ thread_key: 'main', read_seq: '0' }] };+ let finishPresentation!: () => void;+ const notify = vi.fn();+ const present = vi.fn(() => new Promise<{ senderName: string; avatar: string; preview: string }>(resolve => {+ finishPresentation = () => resolve({ senderName: 'Peer', avatar: '', preview: 'Hello' });+ }));+ const service = createChatMessageNotifications({ current: () => true, selfId: () => 'me',+ revision: () => revision, snapshot: async () => snapshot, present, notify });+ service.enqueue('room', 'peer');+ await vi.advanceTimersByTimeAsync(1200);+ expect(present).toHaveBeenCalledOnce();+ snapshot.reads[0].read_seq = snapshot.messages[0].seq;+ revision++;+ finishPresentation();+ await vi.advanceTimersByTimeAsync(3000);+ expect(notify).not.toHaveBeenCalled();+ expect(present).toHaveBeenCalledOnce();+ service.dispose();+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex d2f6a20f5d..56624a16ad 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -181,6 +181,77 @@ describe('Chat Server result delivery and refresh', () => {service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService, deps);});afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); fixture.config = ''; vi.clearAllMocks(); });++ // Unit: exercise the real transport and read.changed path. The former notification-only+ // tests had no persistent group attention consumer, so read/mute/reconnect could not be observed.+ it('projects one group reminder, follows server reads and mute, and restores reconnect history without alerting it', async () => {+ service.dispose();+ const attention = vi.fn();+ const notify = vi.fn();+ deps.onChatGroupAttention = attention;+ deps.onChatMessageNotification = notify;+ const peer = { id: botId, kind: 'human', name: 'Chris', state: 'joined', role: 'member', ownerActorId: botId, avatar: '👋' };+ const message = (seq: string, threadRootId: string | null = null) => ({+ id: `50000000-0000-4000-8000-${seq.padStart(12, '0')}`, seq, authorId: botId, author: { kind: 'human', name: 'Chris' },+ content: [{ type: 'text', text: `Message ${seq}` }], createdAt: '2026-10-03T00:00:00Z', deleted: false, threadRootId,+ mentions: threadRootId ? [selfId] : [],+ });+ const topic = '70000000-0000-4000-8000-000000000001';+ const snapshot = { room: room(roomId), members: [peer], messages: [message('3'), message('2', topic)], cursor: '3',+ reads: [{ thread_key: 'main', read_seq: '0', muted: false }, { thread_key: topic, read_seq: '0', muted: false }] };+ fixture.handle.mockImplementation(route => {+ if (route === '/conversations?limit=100') return { body: [snapshot.room] };+ if (route === '/executions/claim') return { body: { execution: null } };+ if (route.endsWith('/snapshot')) return { body: snapshot };+ if (route.includes('/messages?')) return { body: snapshot.messages };+ return response(route);+ });+ service = withChatServer({ dispose: vi.fn() } as unknown as BotGroupChatService, deps);+ expect((await service.listGroups()).ok).toBe(true);+ expect(attention.mock.calls.at(-1)?.[1]).toMatchObject({ groupId: roomId, messageId: message('2').id,+ threadRootId: topic, mentioned: true, members: [{ name: 'Chris', avatar: '👋' }] });+ expect(notify).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(2000);+ const socket = fixture.sockets.at(-1)!;+ Object.defineProperty(socket, 'readyState', { value: 1 });+ socket.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(150);+ const readChanged = () => socket.emit('message', JSON.stringify({ type: 'changes', scope: `actor:${selfId}`, cursor: '5',+ changes: [{ type: 'read.changed', entityId: roomId }] }));+ snapshot.reads[1].read_seq = '2'; readChanged();+ await vi.advanceTimersByTimeAsync(150);+ expect(attention.mock.calls.at(-1)?.[1]).toMatchObject({ messageId: message('3').id, mentioned: false });+ snapshot.reads[0].muted = true; readChanged();+ await vi.advanceTimersByTimeAsync(150);+ expect(attention.mock.calls.at(-1)?.[1]).toBeNull();+ snapshot.reads[0].muted = false;+ await service.getGroup(roomId);+ const received = (seq: string) => socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: seq,+ changes: [{ type: 'message.created', entityId: message(seq).id }] }));+ received('3');+ await vi.advanceTimersByTimeAsync(1200);+ expect(notify).not.toHaveBeenCalled();+ snapshot.messages.unshift(message('6')); received('6');+ await vi.advanceTimersByTimeAsync(1200);+ expect(notify).toHaveBeenCalledOnce();+ expect(attention.mock.calls.at(-1)?.[1]).toMatchObject({ messageId: message('6').id, mentioned: false });+ // Server/device timestamps deliberately stay equal: only server sequences decide replay.+ socket.emit('close');+ snapshot.messages.unshift(message('7'));+ await vi.advanceTimersByTimeAsync(500);+ const reconnected = fixture.sockets.at(-1)!;+ Object.defineProperty(reconnected, 'readyState', { value: 1 });+ reconnected.emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(150);+ reconnected.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '7',+ changes: [{ type: 'message.created', entityId: message('7').id }] }));+ await vi.advanceTimersByTimeAsync(1200);+ expect(notify).toHaveBeenCalledOnce();+ expect(attention.mock.calls.at(-1)?.[1]).toMatchObject({ messageId: message('7').id });+ reconnected.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));+ await vi.advanceTimersByTimeAsync(150);+ expect(attention.mock.calls.at(-1)?.[1]).toBeNull();+ });// #6907: getGroup feeds Desktop and remote phones. Existing fixtures never pair group name A// with the bot's account ownerName B; exercise the production projection (unit tier).it.each(['Nickname A', 'Account B', ' ', null] as const)('uses the current room owner name %s with safe account fallback', async name => {diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.tsindex 654f79594c..d1006e5ce3 100644--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts@@ -186,6 +186,7 @@ export interface BotGroupChatServiceDeps {isOwnerScopeCurrent?: (scope: DataOwnerBroadcastScope) => boolean;onChanged?: (payload: BotGroupChangedPayload, ownerScope?: DataOwnerBroadcastScope) => void;onChatMessageNotification?: (payload: import('./chatMessageNotifications.js').ChatMessageNotification, current: () => boolean) => void;+ onChatGroupAttention?: (groupId: string, input: import('../agent-island/groupChat.js').AgentIslandGroupChatInput | null, current: () => boolean) => void;/** Cloud companions (cloud-companions.md); absent keeps the Chat Server per-computer only. */companionCloud?: import('../companion-cloud/runtime.js').CompanionCloudHost;now?: () => number;diff --git a/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts b/apps/desktop/src/main/maker-ipc/chatMessageNotifications.tsindex 11fefca46b..265a4613be 100644--- a/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts+++ b/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts@@ -16,17 +16,43 @@ export interface ChatNotificationMessage {threadRootId: string | null; mentions?: string[];}+export interface ChatAttentionSnapshot<M extends ChatNotificationMessage> {+ room: { name: string; kind?: string; archived?: boolean; dissolved_at?: string | null };+ messages: M[];+ reads?: Array<{ thread_key: string; read_seq: string; muted?: boolean; following?: boolean }>;+}++/** One eligibility rule for native notifications and the island's unread projection. */+export function isChatMessageAttention<M extends ChatNotificationMessage>(snapshot: ChatAttentionSnapshot<M>, message: M, selfId: string): boolean {+ if (!snapshot.reads || snapshot.room.archived || snapshot.room.dissolved_at+ || snapshot.reads.some(read => read.thread_key === 'main' && read.muted)+ || message.deleted || message.origin === 'system' || message.origin === 'import' || message.authorId === selfId) return false;+ const read = snapshot.reads.find(read => read.thread_key === (message.threadRootId ?? 'main'));+ if (read?.muted || BigInt(message.seq) <= BigInt(read?.read_seq ?? '0')) return false;+ return !message.threadRootId || read?.following === true || message.mentions?.includes(selfId) === true;+}++/** An unread mention wins; otherwise show the newest eligible message, regardless of snapshot order. */+export function selectChatAttentionMessage<M extends ChatNotificationMessage>(snapshot: ChatAttentionSnapshot<M>, selfId: string): M | null {+ let selected: M | null = null;+ for (const message of snapshot.messages) {+ if (!isChatMessageAttention(snapshot, message, selfId)) continue;+ const mention = message.mentions?.includes(selfId) === true;+ const previousMention = selected?.mentions?.includes(selfId) === true;+ if (!selected || (mention && !previousMention) || (mention === previousMention && BigInt(message.seq) > BigInt(selected.seq))) selected = message;+ }+ return selected;+}+export function createChatMessageNotifications<M extends ChatNotificationMessage>(deps: {current: () => boolean;selfId: () => string;message?: (groupId: string, messageId: string) => Promise<M>;- snapshot: (groupId: string) => Promise<{- room: { name: string; archived?: boolean; dissolved_at?: string | null };- messages: M[];- reads?: Array<{ thread_key: string; read_seq: string; muted?: boolean; following?: boolean }>;- }>;+ snapshot: (groupId: string) => Promise<ChatAttentionSnapshot<M>>;present: (groupId: string, message: M) => Promise<Omit<ChatMessageNotification, 'groupId' | 'groupName' | 'messageId' | 'threadRootId'>>;notify: (notification: ChatMessageNotification, current: () => boolean) => void;+ shouldAlert?: (message: M, snapshot: ChatAttentionSnapshot<M>, groupId: string) => boolean;+ revision?: (groupId: string) => unknown;}) {const pending = new Map<string, Set<string>>();const timers = new Map<string, ReturnType<typeof setTimeout>>();@@ -45,7 +71,10 @@ export function createChatMessageNotifications<M extends ChatNotificationMessagepending.delete(groupId);if (!ids || !current()) return;try {+ const revision = deps.revision?.(groupId);+ const stillCurrent = () => current() && deps.revision?.(groupId) === revision;const snapshot = await deps.snapshot(groupId);+ if (!stillCurrent()) throw new Error('CHAT_NOTIFICATION_CHANGED');if (!current() || !snapshot.reads || snapshot.room.archived || snapshot.room.dissolved_at) return;const main = snapshot.reads.find(read => read.thread_key === 'main');if (main?.muted) return;@@ -54,14 +83,12 @@ export function createChatMessageNotifications<M extends ChatNotificationMessageconst message = snapshot.messages.find(message => message.id === id) ?? await deps.message?.(groupId, id);if (!current()) return;if (!message) continue;- if (message.deleted || message.origin === 'system' || message.origin === 'import' || message.authorId === deps.selfId()) { remember(id); continue; }- const read = message.threadRootId ? snapshot.reads.find(read => read.thread_key === message.threadRootId) : main;- if (read?.muted || BigInt(message.seq) <= BigInt(read?.read_seq ?? '0')) { remember(id); continue; }- if (message.threadRootId && !read?.following && !message.mentions?.includes(deps.selfId())) { remember(id); continue; }+ if (!isChatMessageAttention(snapshot, message, deps.selfId()) || deps.shouldAlert?.(message, snapshot, groupId) === false) { remember(id); continue; }const presentation = await deps.present(groupId, message);if (!current()) return;+ if (!stillCurrent()) throw new Error('CHAT_NOTIFICATION_CHANGED');deps.notify({ ...presentation, groupId, groupName: snapshot.room.name, messageId: message.id,- ...(message.threadRootId ? { threadRootId: message.threadRootId } : {}) }, current);+ ...(message.threadRootId ? { threadRootId: message.threadRootId } : {}) }, stillCurrent);remember(id);}} catch {diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex f0ba0055b8..3397da2b1d 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -34,7 +34,7 @@ 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 { createChatMessageNotifications, selectChatAttentionMessage } from './chatMessageNotifications.js';import WebSocket from 'ws';import { z } from 'zod';import { and, asc, eq, gt } from 'drizzle-orm';@@ -369,12 +369,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet supportsListRemoval = false;let supportsMemberAvatar = false;const personalList = createConversationListState();+ const attentionGroups = new Set<string>();+ const clearGroupAttention = (roomId: string) => {+ attentionGroups.delete(roomId);+ deps.onChatGroupAttention?.(roomId, null, current);+ };const syncPersonalList = async (force = false) => {if (supportsListRemoval) await (force ? personalList.sync(api) : personalList.ensureSynced(api));};personalList.subscribe(row => {if (!current()) return;- if (row.hidden) { displayHistory.forget(row.conversationId); sendJournal.forgetRoom(row.conversationId); }+ if (row.hidden) { displayHistory.forget(row.conversationId); sendJournal.forgetRoom(row.conversationId); clearGroupAttention(row.conversationId); }deps.onChanged?.({ groupId: row.conversationId, change: 'list', listState: row }, scope);for (const [source, target] of upgradedGroups) if (target === row.conversationId)deps.onChanged?.({ groupId: source, change: 'list', listState: row }, scope);@@ -531,14 +536,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// Local writes always notify: HTTP can finish before the server handles subscribe,// even on an open socket. Nearby realtime echoes join the same bounded window.const pendingChanges = new Map<string, ReturnType<typeof setTimeout>>();+ // The first snapshot of each connection is a quiet baseline; use server sequences, not device clocks.+ const notificationBaselines = new Map<string, bigint>();const chatNotifications = deps.onChatMessageNotification ? createChatMessageNotifications<Message>({current, selfId: () => selfId,message: (groupId, messageId) => api<Message>(`/conversations/${groupId}/messages/${messageId}`),snapshot: async groupId => {+ const version = generation(groupId);+ const connection = snapshotConnection;const snapshot = await api<Snapshot>(`/conversations/${groupId}/snapshot`);if (personalList.hidden(groupId)) throw new Error('CHAT_HIDDEN');+ if (current() && generation(groupId) === version && snapshotConnection === connection) publishGroupAttention(snapshot);return snapshot;},+ // Replayed group history restores unread above, but is not a new popup. Direct chats keep their existing delivery policy.+ shouldAlert: (message, snapshot, groupId) => snapshot.room.kind === 'direct'+ || BigInt(message.seq) > (notificationBaselines.get(groupId) ?? BigInt(message.seq)),+ revision: groupId => `${snapshotConnection}:${generation(groupId)}:${personalList.hidden(groupId)}`,present: async (groupId, message) => {const snapshot = await recentSnapshot(groupId);const member = snapshot.members.find(member => member.id === message.authorId);@@ -574,6 +588,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDpendingChanges.set(roomId, setTimeout(() => {pendingChanges.delete(roomId);if (!current()) return;+ if (roomId && attentionGroups.has(roomId)) void refreshGroupAttention(roomId);deps.onChanged?.({ groupId: roomId, change: 'messages' }, scope);// A restored route may still contain the local ID until the user navigates.for (const [sourceId, targetId] of upgradedGroups)@@ -988,6 +1003,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDtry {const event = JSON.parse(String(raw));if (event.type === 'ready') {+ notificationBaselines.clear();memberJoinedClaims = true;claimWakeVersion++;idleClaims.clear();@@ -1001,7 +1017,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDfor (const roomId of rooms.keys()) invalidate(roomId);ws.send(JSON.stringify({ type: 'subscribe', scope: `actor:${selfId}`, after: '0' }));for (const [roomId, cursor] of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));- void syncPersonalList(true).then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) { changed(roomId); autoContinuePlans(roomId); } changed(''); } }).catch(() => ws.close());+ void syncPersonalList(true).then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) {+ if (deps.onChatGroupAttention) void refreshGroupAttention(roomId);+ changed(roomId); autoContinuePlans(roomId);+ } changed(''); } }).catch(() => ws.close());} else if (event.type === 'changes') {// Durable UI projections commit before ACK. Serial frames preserve the cursor order.if (event.scope.startsWith('conversation:')) {@@ -1080,6 +1099,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}).catch(() => ws.close());} else {rooms.delete(roomId);+ clearGroupAttention(roomId);displayHistory.forget(roomId); sendJournal.forgetRoom(roomId);// Access may come back with a narrower history; re-read every reference.threads.reset();@@ -1104,10 +1124,50 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst value = await api<Snapshot>(`/conversations/${roomId}/snapshot`);if (value.room.dissolved_at) retirePlanning(roomId);// A prior connection or room change makes this answer ineligible for reuse.- if (current() && snapshotConnection === connection && generation(roomId) === read)+ if (current() && snapshotConnection === connection && generation(roomId) === read) {snapshots.set(roomId, { value, generation: read, at: Date.now() });+ publishGroupAttention(value);+ }return value;}++ function publishGroupAttention(s: Snapshot): void {+ if (!current() || !isGroupRoom(s.room)) return;+ if (!notificationBaselines.has(s.room.id)) notificationBaselines.set(s.room.id,+ s.messages.reduce((max, message) => BigInt(message.seq) > max ? BigInt(message.seq) : max, 0n));+ if (!deps.onChatGroupAttention) return;+ const unavailable = personalList.hidden(s.room.id) || s.members.some(m => m.id === selfId && m.state !== 'joined');+ const selected = unavailable ? null : selectChatAttentionMessage(s, selfId);+ if (!selected) { clearGroupAttention(s.room.id); return; }+ const view = messageView(selected, s.members, s.members);+ const preview = notificationPreview(botGroupMessageSummaryText(view) || mediaNames(selected), 240)+ || t('settings.notifications.chat.message');+ const context = selected.threadRootId ? `${t('settings.notifications.chat.thread')} · ` : '';+ attentionGroups.add(s.room.id);+ deps.onChatGroupAttention(s.room.id, {+ groupId: s.room.id, name: s.room.name, messageId: selected.id,+ ...(selected.threadRootId ? { threadRootId: selected.threadRootId } : {}),+ mentioned: selected.mentions?.includes(selfId) === true,+ preview: `${context}${notificationPreview(view.authorName)}: ${preview}`,+ lastMessageAt: Date.parse(selected.createdAt),+ members: s.members.filter(m => m.state === 'joined').slice(0, 5).map(m => ({+ name: memberName(m, s.members), avatar: m.groupAvatar ?? m.avatar ?? m.defaultAvatarUrl ?? localBot(m.id)?.avatar ?? '',+ avatarColor: localBot(m.id)?.avatarColor ?? '',+ })),+ }, current);+ }++ async function refreshGroupAttention(roomId: string): Promise<void> {+ const version = generation(roomId);+ const connection = snapshotConnection;+ try {+ const value = await (history()?.snapshot<Snapshot>(roomId) ?? recentSnapshot(roomId));+ if (current() && generation(roomId) === version && snapshotConnection === connection) publishGroupAttention(value);+ } catch (error) {+ if (current() && generation(roomId) === version && snapshotConnection === connection+ && error instanceof ChatResponseError && [403, 404].includes(error.status)) clearGroupAttention(roomId);+ }+ }async function snapshot(roomId: string) {const value = await readSnapshot(roomId);subscribe(roomId, value.cursor);@@ -1405,6 +1465,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}async function detail(roomId: string, options?: unknown, summaryOnly = false, attempt = 0): Promise<BotGroupDetail> {id.parse(roomId);+ const attentionGeneration = generation(roomId);+ const attentionConnection = snapshotConnection;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 ?? {});@@ -1465,6 +1527,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn detail(roomId, options, summaryOnly, attempt + 1);}const threadShareUpdates = shares?.updates;+ if (current() && generation(roomId) === attentionGeneration && snapshotConnection === attentionConnection) publishGroupAttention(s);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))@@ -2869,14 +2932,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlistGroups: () => safe(async () => {await ensureRegistered(); await syncPersonalList(); beginUpgrade();const groups: BotGroupDetail[] = [];+ const joinedIds = new Set<string>();let after: string | undefined;do {const page = await api<Array<Room & { state: string; head?: unknown }>>(`/conversations?limit=100${after ? `&after=${after}` : ''}`);// Only group rooms belong in the group list.const joined = page.filter(r => r.state === 'joined' && isGroupRoom(r) && !personalList.hidden(r.id));+ for (const room of joined) joinedIds.add(room.id);groups.push(...settledValues(await settleBounded(joined, SUMMARY_CONCURRENCY, room => summary(room))));after = page.length === 100 ? page.at(-1)!.id : undefined;} while (after);+ if (current()) for (const roomId of attentionGroups) if (!joinedIds.has(roomId)) clearGroupAttention(roomId);return { ok: true as const, groups: groups.filter(group => !personalList.hidden(group.id)) };}),getGroup: (roomId, options) => safe(async () => {@@ -3115,6 +3181,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDeditPlanStep: input => safe(() => actPlan(input, 'reassign')),dispose: () => {chatNotifications?.dispose();+ for (const roomId of attentionGroups) clearGroupAttention(roomId);unsubscribeProfiles();disposed = true; threads.dispose(); clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); clearTimeout(claimTrigger); socket?.close();companion?.dispose(); companion = undefined; deps.companionCloud?.homes.reset();diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex bfdf5084cf..e0c3c7682d 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -642,7 +642,7 @@ import { createBotGroupChatService, settleBotGroupLaneTerminal, type BotGroupChaimport { settleUndispatchedBotGroupTurn } from './botGroupRuntimeFailure.js';import { withChatServer } from './chatServer.js';import { createSqliteChatHistoryStore } from './chatHistoryStore.js';-import { showDesktopChatMessage } from '../notificationService.js';+import { showDesktopChatMessage, getDesktopNotificationsEnabled } from '../notificationService.js';import { companionHomes, isCompanionShadowed } from '../companion-cloud/homes.js';import { createCompanionCloudHost } from '../companion-cloud/host.js';import { activeCompanionCloud } from '../companion-cloud/runtime.js';@@ -13190,7 +13190,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return result.ok ? { ok: true as const } : { ok: false as const, errorCode: result.errorCode };},}),- onChatMessageNotification: (event, current) => { void showDesktopChatMessage(event, current).catch(() => log.warn('Chat notification unavailable')); },+ onChatGroupAttention: (groupId, input, current) => {+ if (current()) getAgentIslandService()?.setGroupChat(groupId, input);+ },+ onChatMessageNotification: (event, current) => {+ if (!current() || !getDesktopNotificationsEnabled()) return;+ if (event.conversationKind !== 'direct' && getAgentIslandService()?.notifyGroupChat(event.groupId)) return;+ void showDesktopChatMessage(event, current).catch(() => log.warn('Chat notification unavailable'));+ },onStepSettled: (event, scope) => {const ownerScope = scope as ReturnType<typeof captureDataOwnerBroadcastScope> | undefined;if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex d49cbe019c..070829dfc0 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -43,6 +43,8 @@ export interface AgentIslandCompanionSnapshot {* Renderer-facing session snapshot for the macOS Agent Island overlay.*/export interface AgentIslandSessionSnapshot {+ /** Group-message UI only; never a maker task or a remotely relayed activity. */+ groupChat?: { avatars: AgentIslandCompanionSnapshot[]; mentionLabel?: string };/** Opaque identity of the completed card, issued by its owning process. */completionToken?: string;/** This completion preserves older unread state without requesting a new alert. */diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex bdf278c5f3..10bebbe7d3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -154,6 +154,14 @@ worktree 资源等待后复核。控制端先按既有工作区/自动化预原生配置或数据库 migration 更新。回归见 `agentIslandRemoteSessions.test.ts`、`agent-island/__tests__/service.test.ts` 和 `localDb/ipc/__tests__/sessionsUpdate.test.ts`。+## 灵动岛群消息展示++Desktop Main 向随包分发的原生灵动岛 helper 追加可选 `groupChat` 展示字段(成员头像与本地化 @ 标记),缺省时沿用原卡片。+群卡使用独立 UI 标识,点击仍走现有群消息深链;不签发任务 `completionToken`,不进入任务活动广播或 device-link relay。+服务端已读/关注/静音判据与系统通知共用,未新增服务端接口、数据库、Mobile 原生配置或远程 IPC。+旧 helper 忽略可选字段后仍可显示标题和摘要、点击进入群消息;旧 Main 配合新 helper 保持原样。+回归见 `agent-island/__tests__/{state,service,deviceSessions}.test.ts` 与 `maker-ipc/__tests__/chatServer.test.ts`。+## 限额恢复时间查询既有 `maker:usage:claude-subscription` 请求可选在 providerId 后追加 `true`,表示等待同一余量diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex e89e9328d1..65d6251589 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -818,8 +818,17 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;### 收到消息后的注意、定位与回应-- 桌面运行时由 Chat Server 实时事件触发原生通知;手机由 Chat Server 直接发 APNs/FCM,不依赖电脑在线。+- 桌面运行时由 Chat Server 实时事件触发提醒:灵动岛开启且可用时由岛面承接群消息,关闭、无原生岛或原生发布失败时回退系统通知,+ 同一条消息不同时发两份横幅;手机由 Chat Server 直接发 APNs/FCM,不依赖电脑在线。桌面完全退出后没有常驻接收进程,不承诺继续弹窗。伙伴私聊的任务回复继续复用原有任务通知链。+- **灵动岛群消息**:一个群一张两行卡,第一行群名及可选「@你」,第二行发送者与摘要;话题回复标明话题,头像复用侧栏前五位成员的聚拢顺序。+ 未读 @ 优先于普通群消息,等待回答/审批和报错优先于群消息;展开操作时保持既有非阻塞卡的顺序。连续消息原位更新,+ 同一群 30 秒内不反复展开、不延长已展示卡的停留时间;普通提醒后新到的 @ 可以提前提醒,群消息不播放任务完成音。+ 自动提示收起后,未读卡仍保留在展开列表。点击沿用群/消息/话题深链,不清空读位、不提供任务归档或已读滑动动作。+ 服务端读位推进后,已读的 @ 消退;若还有其他符合提醒规则的未读消息,原卡显示它,否则移除。+ 静音、隐藏、归档、离群和撤权同步收起。启动/重连用本次连接的第一份群快照序号作静默基线,只恢复未读,不重弹旧消息。+ 群专线的成功回复由群消息提醒承接,不再同时留下任务完成提醒;运行、审批和报错仍按原任务状态展示。+ 实现与回归:`chatMessageNotifications.ts`、`chatServer.ts` 及对应测试,`agent-island/{state,service}.ts`、`deviceSessions.test.ts`。- 主时间线未读来自服务器精确序号,只计别人发来的可见消息;列表同时显示 @。最新快照窗口最多 100 条,计数为该窗口中的未读数。系统事件、已删除、导入与自己的消息不提醒。话题只提醒点名或主动关注的回复。- 只有前台实际读到底部才推进读位;阅读历史时保留位置,显示新消息按钮。按钮返回最新消息;打开通知