Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(chat): connect cross-platform notifications and message responses

Chris1be2cb1f10ff
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index 5bdc939e8e..39e28b51d7 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -78,6 +78,7 @@ export type DeepLinkPayload =
* 供 renderer 在导航落地后申请处置被点的那张卡。
*/
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
/**
* 由 --open-folder argv 触发的 "新建对话 + 预填工作目录"。
@@ -426,6 +427,11 @@ 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 } : {}) });
+}
+
/** Sends a typed internal event to the primary renderer without broadcasting to utility windows. */
export function sendMainWindowMessage(channel: string, payload: unknown): boolean {
const win = mainWindowRef;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts
new file mode 100644
index 0000000000..f6a7ae6c60
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatMessageNotifications.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createChatMessageNotifications, type ChatNotificationMessage } from '../chatMessageNotifications.js';
+
+afterEach(() => vi.useRealTimers());
+const message = (id: string, extra: Partial<ChatNotificationMessage> = {}): ChatNotificationMessage => ({
+ id, seq: '9007199254740993', authorId: id, deleted: false, threadRootId: null, ...extra,
+});
+function fixture(messages: ChatNotificationMessage[]) {
+ const snapshot = { room: { name: 'Team' }, messages,
+ reads: [{ thread_key: 'main', read_seq: '0', muted: false, following: false }] };
+ const notify = vi.fn();
+ const service = createChatMessageNotifications({ current: () => true, selfId: () => 'me',
+ snapshot: async () => snapshot, present: async (_group, m) => ({ senderName: m.authorId, avatar: `avatar:${m.authorId}`, preview: 'Hello' }), notify });
+ return { service, snapshot, notify };
+}
+
+// Unit: real socket notification consumer; no prior ordinary-chat delivery covered read/mute/replay races.
+it('delivers people and companions once, with sender identity and the exact destination', async () => {
+ vi.useFakeTimers();
+ const f = fixture([message('person'), message('bot')]);
+ for (const id of ['person', 'bot', 'person']) f.service.enqueue('room', id);
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify.mock.calls.map(([event]) => event)).toEqual(['person', 'bot'].map(id => ({
+ groupId: 'room', groupName: 'Team', messageId: id, senderName: id, avatar: `avatar:${id}`, preview: 'Hello',
+ })));
+ f.service.enqueue('room', 'person');
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify).toHaveBeenCalledTimes(2);
+ f.service.dispose();
+});
+
+it('checks current reads and mute after the delay, excluding self, removed and imported messages', async () => {
+ vi.useFakeTimers();
+ const f = fixture([message('peer'), message('me'), message('deleted', { deleted: true }), message('old', { origin: 'import' })]);
+ for (const m of f.snapshot.messages) f.service.enqueue('room', m.id);
+ f.snapshot.reads[0]!.read_seq = '9007199254740993';
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify).not.toHaveBeenCalled();
+ f.snapshot.messages = [message('later', { seq: '9007199254740994' })];
+ f.snapshot.reads[0]!.muted = true;
+ f.service.enqueue('room', 'later');
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify).not.toHaveBeenCalled();
+ f.service.dispose();
+});
+
+it('notifies followed or mentioned threads and cancels queued work on owner disposal', async () => {
+ vi.useFakeTimers();
+ const f = fixture([message('unfollowed', { threadRootId: 'other' }),
+ message('mentioned', { threadRootId: 'other', mentions: ['me'] }), message('followed', { threadRootId: 'topic' })]);
+ f.snapshot.reads.push({ thread_key: 'topic', read_seq: '0', muted: false, following: true });
+ for (const m of f.snapshot.messages) f.service.enqueue('room', m.id);
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify.mock.calls.map(([event]) => [event.messageId, event.threadRootId])).toEqual([['mentioned', 'other'], ['followed', 'topic']]);
+ f.snapshot.messages.push(message('pending'));
+ f.service.enqueue('room', 'pending'); f.service.dispose();
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(f.notify).toHaveBeenCalledTimes(2);
+});
+
+it('recovers a transient snapshot failure and fetches an event outside the latest snapshot window', async () => {
+ vi.useFakeTimers();
+ const notify = vi.fn();
+ const snapshot = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue({
+ room: { name: 'Team' }, messages: [], reads: [{ thread_key: 'main', read_seq: '0' }],
+ });
+ const fetchMessage = vi.fn(async () => message('older'));
+ const service = createChatMessageNotifications({ current: () => true, selfId: () => 'me', snapshot,
+ message: fetchMessage, present: async () => ({ senderName: 'Peer', avatar: '', preview: 'Hello' }), notify });
+ service.enqueue('room', 'older');
+ await vi.advanceTimersByTimeAsync(1200);
+ expect(notify).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(fetchMessage).toHaveBeenCalledWith('room', 'older');
+ expect(notify).toHaveBeenCalledOnce();
+ service.enqueue('room', 'older');
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(notify).toHaveBeenCalledOnce();
+ service.dispose();
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
index aaa08f7e1e..51eca0c7f3 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
@@ -78,6 +78,26 @@ describe('Chat Server membership notices', () => {
});
afterEach(() => { service.dispose(); vi.useRealTimers(); vi.clearAllMocks(); });
+ it('records the displayed main message using its exact server position and reflects another device read', async () => {
+ const seq = '9007199254740993';
+ messages = [{ ...joined(), origin: 'human', seq, content: [{ type: 'text', text: '**Hello** [team](https://example.com)' }] } as unknown as ReturnType<typeof joined>];
+ let readSeq = '0';
+ const original = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/read')) { readSeq = body.readSeq; return { body: { readSeq } }; }
+ const response = original(route, method, body);
+ if (route.endsWith('/snapshot')) response.body.reads = [{ thread_key: 'main', read_seq: readSeq }];
+ return response;
+ });
+ const before = await service.getGroup(roomId);
+ expect(before.ok && before.group.serverUnread).toEqual({ count: 1, mentioned: false });
+ expect(before.ok && before.group.lastMessage?.preview).toBe('Hello team');
+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'read', messageId: messages[0]!.id } })).toEqual({ ok: true });
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/read`, 'POST', { operationId: `read-main:${seq}`, readSeq: seq });
+ const after = await service.getGroup(roomId);
+ expect(after.ok && after.group.serverUnread).toEqual({ count: 0, mentioned: false });
+ });
+
it('reads a persisted join into the main timeline and sidebar using its name snapshot', async () => {
const result = await service.getGroup(roomId);
expect(result.ok && result.group.messages).toEqual([expect.objectContaining({
diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
index c63a380175..8de48a83e3 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
@@ -183,6 +183,7 @@ export interface BotGroupChatServiceDeps {
captureOwnerScope?: () => DataOwnerBroadcastScope;
isOwnerScopeCurrent?: (scope: DataOwnerBroadcastScope) => boolean;
onChanged?: (payload: BotGroupChangedPayload, ownerScope?: DataOwnerBroadcastScope) => void;
+ onChatMessageNotification?: (payload: import('./chatMessageNotifications.js').ChatMessageNotification, 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.ts
new file mode 100644
index 0000000000..b7c385c223
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatMessageNotifications.ts
@@ -0,0 +1,97 @@
+/** Live chat notifications. Server reads/mute state win over delayed or replayed socket events. */
+export interface ChatMessageNotification {
+ groupId: string;
+ groupName: string;
+ messageId: string;
+ threadRootId?: string;
+ senderName: string;
+ avatar: string;
+ preview: string;
+}
+
+export interface ChatNotificationMessage {
+ id: string; seq: string; authorId: string; deleted: boolean; origin?: string;
+ threadRootId: string | null; mentions?: string[];
+}
+
+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 }>;
+ }>;
+ present: (groupId: string, message: M) => Promise<Omit<ChatMessageNotification, 'groupId' | 'groupName' | 'messageId' | 'threadRootId'>>;
+ notify: (notification: ChatMessageNotification, current: () => boolean) => void;
+}) {
+ const pending = new Map<string, Set<string>>();
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
+ const handled = new Set<string>();
+ const retries = new Map<string, number>();
+ let disposed = false;
+ const current = () => !disposed && deps.current();
+ const remember = (id: string) => {
+ handled.add(id);
+ retries.delete(id);
+ if (handled.size > 1000) handled.delete(handled.values().next().value!);
+ };
+ async function flush(groupId: string) {
+ timers.delete(groupId);
+ const ids = pending.get(groupId);
+ pending.delete(groupId);
+ if (!ids || !current()) return;
+ try {
+ const snapshot = await deps.snapshot(groupId);
+ 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;
+ for (const id of ids) {
+ if (handled.has(id)) continue;
+ const 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; }
+ const presentation = await deps.present(groupId, message);
+ if (!current()) return;
+ deps.notify({ ...presentation, groupId, groupName: snapshot.room.name, messageId: message.id,
+ ...(message.threadRootId ? { threadRootId: message.threadRootId } : {}) }, current);
+ remember(id);
+ }
+ } catch {
+ // A transient disconnect must not consume a live notice. Retry a bounded
+ // window with fresh authorization/read state, preserving arrivals during the request.
+ if (!current()) return;
+ const remaining = pending.get(groupId) ?? new Set<string>();
+ for (const id of ids) {
+ if (handled.has(id)) continue;
+ const attempt = (retries.get(id) ?? 0) + 1;
+ if (attempt > 3) { remember(id); continue; }
+ retries.set(id, attempt);
+ if (remaining.size < 100) remaining.add(id);
+ }
+ if (remaining.size && (pending.has(groupId) || pending.size < 100)) {
+ pending.set(groupId, remaining);
+ if (!timers.has(groupId)) timers.set(groupId, setTimeout(() => { void flush(groupId); }, 3000));
+ }
+ }
+ }
+ return {
+ enqueue(groupId: string, messageId: string) {
+ if (!current() || handled.has(messageId)) return;
+ const ids = pending.get(groupId) ?? new Set<string>();
+ if (ids.size >= 100 || (!pending.has(groupId) && pending.size >= 100)) return;
+ ids.add(messageId); pending.set(groupId, ids);
+ if (!timers.has(groupId)) timers.set(groupId, setTimeout(() => { void flush(groupId); }, 1200));
+ },
+ dispose() {
+ disposed = true;
+ for (const timer of timers.values()) clearTimeout(timer);
+ timers.clear(); pending.clear(); handled.clear(); retries.clear();
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 86cbd7fa0e..94ad72057f 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -29,6 +29,8 @@ import { prepareBotGroupTaskPost, type BotGroupTaskPostSnapshot } from './botGro
import { registerGroupToolAuthority, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';
import path from 'node:path';
import { randomUUID, createHash } from 'node:crypto';
+import { markdownPreviewText } from '../../shared/markdownPreviewText.js';
+import { createChatMessageNotifications } from './chatMessageNotifications.js';
import WebSocket from 'ws';
import { z } from 'zod';
import { and, asc, eq, gt } from 'drizzle-orm';
@@ -72,7 +74,7 @@ interface Room {
created_at: string; updated_at: string; revision: number; archived: boolean; dissolved_at?: string | null; organizer_id?: string | null; kind?: string;
}
/** `reads`: this reader's read position per Thread (`thread_key` = root ID, `main` for the main timeline); older servers omit it. */
-interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; following?: boolean }> }
+interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; following?: boolean; muted?: boolean }> }
interface Execution {
id: string; conversation_id: string; source_message_id: string; bot_id: string;
requester_id?: string;
@@ -492,6 +494,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>>();
+ const chatNotifications = deps.onChatMessageNotification ? createChatMessageNotifications<Message>({
+ current, selfId: () => selfId,
+ message: (groupId, messageId) => api<Message>(`/conversations/${groupId}/messages/${messageId}`),
+ snapshot: async groupId => {
+ const snapshot = await api<Snapshot>(`/conversations/${groupId}/snapshot`);
+ if (personalList.hidden(groupId)) throw new Error('CHAT_HIDDEN');
+ return snapshot;
+ },
+ present: async (groupId, message) => {
+ const 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) };
+ },
+ notify: deps.onChatMessageNotification,
+ }) : undefined;
const changed = (roomId: string) => {
if (!current()) return;
invalidate(roomId);
@@ -900,6 +919,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if ((event.changes ?? []).some((change: { type?: string; data?: { dissolvedAt?: unknown } }) => change.type === 'conversation.updated' && change.data?.dissolvedAt)) retirePlanning(roomId);
if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);
for (const change of event.changes ?? []) {
+ if (change.type === 'message.created' && typeof change.entityId === 'string' && id.safeParse(change.entityId).success)
+ chatNotifications?.enqueue(roomId, change.entityId);
if (change.type === 'message.updated' || change.type === 'message.deleted') threads.invalidate(roomId, change.entityId);
if (change.type === 'reaction.changed' && typeof change.entityId === 'string') bumpMessageReactions(roomId, change.entityId);
}
@@ -1036,7 +1057,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const joined = !m.deleted && m.threadRootId === null ? m.content.find(b => b.type === 'card' &&
b.namespace === 'cindy.membership' && b.schemaRevision === 1 && b.data?.type === 'member.joined' &&
id.safeParse(b.data.actorId).success && typeof b.data.displayName === 'string' && b.data.displayName.trim()) : undefined;
- return { id: m.id, sequence: Number(m.seq), kind: 'notice', authorKind: 'system', isSelf: false,
+ return { id: m.id, sequence: Number(m.seq), serverSequence: m.seq, kind: 'notice', authorKind: 'system', isSelf: false,
authorBotId: null, authorName: joined ? String(joined.data!.displayName) : '', content: displayText(m),
threadRootId: m.threadRootId, replyCount: 0, reactions: [], mentions: { all: false, botIds: [] },
noticeCode: joined ? 'member-joined' : null, planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
@@ -1044,7 +1065,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const notice = m.origin === 'integration' && !m.deleted ? m.content.find(b => b.namespace === 'cindy.group-notice' && b.schemaRevision === 1) : undefined;
const noticeCode = notice?.data?.noticeCode;
if (noticeCode === 'member-failed' || noticeCode === 'member-timeout' || noticeCode === 'plan-failed') return {
- id: m.id, sequence: Number(m.seq), kind: 'notice', authorKind: 'system', isSelf: false,
+ id: m.id, sequence: Number(m.seq), serverSequence: m.seq, kind: 'notice', authorKind: 'system', isSelf: false,
authorBotId: localBot(m.authorId)?.id ?? null, authorName: members.find(member => member.id === m.authorId)?.name ?? '',
content: displayText(m), threadRootId: m.threadRootId, replyCount: 0, reactions: [], mentions: { all: false, botIds: [] },
noticeCode, planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt),
@@ -1053,17 +1074,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const planCard = m.content.find(b => b.namespace === 'cindy.plan');
const legacy = m.origin === 'import' ? m.content.find(b => b.namespace === 'cindy.local-history')?.data : undefined;
const runtimeFailureCode = readImportedBotGroupRuntimeFailureCode(m);
- if (runtimeFailureCode) return { id: m.id, sequence: Number(m.seq), kind: 'notice', authorKind: 'system', isSelf: false,
+ if (runtimeFailureCode) return { id: m.id, sequence: Number(m.seq), serverSequence: m.seq, kind: 'notice', authorKind: 'system', isSelf: false,
authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: typeof legacy?.authorName === 'string' ? legacy.authorName : '',
content: '', threadRootId: m.threadRootId, replyCount: 0, reactions: [], mentions: { all: false, botIds: [] },
noticeCode: runtimeFailureCode === 'RUNTIME_TIMEOUT' ? 'member-timeout' : 'member-failed', runtimeFailureCode,
planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
const quote = m.deleted || planCard ? null : readBotGroupQuote(m.content);
const task = m.deleted || planCard ? null : taskCardOf(m);
- return { id: m.id, sequence: Number(m.seq), deleted: m.deleted, kind: planCard ? 'plan' : 'message', authorKind: legacy?.authorKind === 'system' ? 'system' : m.author.kind === 'human' ? 'user' : 'bot',
+ return { id: m.id, sequence: Number(m.seq), serverSequence: m.seq, deleted: m.deleted, kind: planCard ? 'plan' : 'message', authorKind: legacy?.authorKind === 'system' ? 'system' : m.author.kind === 'human' ? 'user' : 'bot',
isSelf: m.authorId === selfId, threadRootId: m.threadRootId, replyCount: m.replyCount ?? 0, reactions: m.reactions ?? [], ...(quote ? { quote } : {}), ...(task ? { task } : {}),
authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: legacy?.authorKind === 'system' && typeof legacy.authorName === 'string' ? legacy.authorName : member ? memberName(member) : m.author.name, content: displayText(m),
- mentions: { all: false, botIds: [] }, noticeCode: null, planId: typeof planCard?.data?.planId === 'string' ? planCard.data.planId : null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
+ mentions: { all: false, botIds: (m.mentions ?? []).map(actorId => localBot(actorId)?.id ?? actorId) }, noticeCode: null, planId: typeof planCard?.data?.planId === 'string' ? planCard.data.planId : null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
}
/**
* When the newest (up to 99) messages from someone else arrived, oldest first: Bots and other
@@ -1315,7 +1336,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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 threadShareUpdates = shares?.updates;
- const reads = summaryOnly ? null : threadReads(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))
+ && 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;
messages.sort((a, b) => a.sequence - b.sequence);
@@ -1338,11 +1362,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// 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 ? '' : (botGroupMessageSummaryText(lastView) || mediaNames(last)).slice(0, 80), createdAt: lastView.createdAt, ...(lastIsShare ? { threadShare: true } : {}),
+ preview: lastIsShare ? '' : markdownPreviewText(botGroupMessageSummaryText(lastView) || mediaNames(last)).slice(0, 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),
incomingMessageTimes: incomingMessageTimes(s.messages, s.members),
+ ...(unread ? { serverUnread: { count: Math.min(99, unread.length), mentioned: unread.some(m => m.mentions?.includes(selfId)) } } : {}),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),
...(shares ? { threadShareVersion: shares.version } : {}), ...(threadList ? { threads: threadList } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,
@@ -2319,6 +2344,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const target = await resolveGroup(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('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(),
@@ -2332,6 +2358,19 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
z.object({ type: z.literal('dissolve'), expectedRevision: z.number().int().positive() }).strict(),
z.object({ type: z.literal('archive'), archived: z.boolean(), expectedRevision: z.number().int().positive() }).strict(),
]).parse(input.action);
+ if (action.type === 'read') {
+ const snapshot = await recentSnapshot(target);
+ if (!snapshot.reads) return {};
+ const message = snapshot.messages.find(m => m.id === action.messageId)
+ ?? await api<Message>(`/conversations/${target}/messages/${action.messageId}`);
+ if (message.threadRootId) throw new Error('MAIN_MESSAGE_REQUIRED');
+ const read = snapshot.reads.find(entry => entry.thread_key === 'main')?.read_seq ?? '0';
+ if (BigInt(message.seq) > BigInt(read)) {
+ await api(`/conversations/${target}/read`, 'POST', { operationId: `read-main:${message.seq}`, readSeq: message.seq });
+ changed(target);
+ }
+ return {};
+ }
if (action.type === 'avatar') {
if (!supportsMemberAvatar) throw new Error('CHAT_UNAVAILABLE');
const snapshot = await groupSnapshot(target);
@@ -2894,6 +2933,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
continuePlan: input => safe(() => actPlan(input, 'continue')), retryPlan: input => safe(() => actPlan(input, 'retry')),
editPlanStep: input => safe(() => actPlan(input, 'reassign')),
dispose: () => {
+ chatNotifications?.dispose();
disposed = true; threads.dispose(); clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); clearTimeout(claimTrigger); socket?.close();
companion?.dispose(); companion = undefined; deps.companionCloud?.homes.reset();
for (const refresh of attachmentRefreshes.values()) clearTimeout(refresh);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4649040908..609cb9febe 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -627,6 +627,7 @@ import {
import { createBotGroupChatService, settleBotGroupLaneTerminal, type BotGroupChatService, type BotGroupChatServiceDeps, type BotGroupLaneTerminal } from './botGroupChatService.js';
import { settleUndispatchedBotGroupTurn } from './botGroupRuntimeFailure.js';
import { withChatServer } from './chatServer.js';
+import { showDesktopChatMessage } 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';
@@ -12879,6 +12880,7 @@ 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')); },
onStepSettled: (event, scope) => {
const ownerScope = scope as ReturnType<typeof captureDataOwnerBroadcastScope> | undefined;
if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index 7dd3bdb788..6c0289f4e0 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -29,6 +29,9 @@ import * as path from 'node:path';
import { markSessionNeedsAttention } from './appBadgeService';
import { getMobileNotifyGeneration, sendMobileSessionNotify } from './device-link';
import { notificationPreview } from './notificationPreview';
+import { companionAvatarThumbnail } from './agent-island/companionIdentity';
+import { getDeepLinkMainWindow, openMainWindowChatMessage } from './deepLink';
+import type { ChatMessageNotification } from './maker-ipc/chatMessageNotifications';
import { readSessionNotificationPreview, type SessionNotificationPreview } from './localDb/sessionNotificationPreview';
import { drainSessionActiveTurnWrites, getSessionNotificationTurnSignal } from './localDb/sessionActiveTurn';
import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './device-link/broadcast-tap';
@@ -53,6 +56,37 @@ export function getDesktopNotificationsEnabled(): boolean {
return desktopNotificationsEnabled;
}
+/** Chat uses the same system permission and global desktop preference as task notifications. */
+export async function showDesktopChatMessage(payload: ChatMessageNotification, current: () => boolean): Promise<void> {
+ const visible = () => {
+ const window = getDeepLinkMainWindow();
+ if (!window?.isFocused() || !window.isVisible()) return false;
+ try { return new URL(window.webContents.getURL()).hash.split('?')[0] === `#/bots/groups/${payload.groupId}`; }
+ catch { return false; }
+ };
+ if (!current() || !desktopNotificationsEnabled || visible() || !Notification.isSupported()) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const thumbnail = await Promise.race([
+ companionAvatarThumbnail(payload.avatar).catch(() => undefined),
+ new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), 600); }),
+ ]).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}`,
+ ...(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);
+ });
+ notification.on('close', release);
+ notification.on('failed', release);
+ notification.show();
+}
+
// dev 下 electron.exe / Electron.app 自带的是默认图标,notification toast 没有
// AUMID/.icns 兜底会显示成空白或 Electron logo——给 toast 显式塞一张 PNG
// 让 dev 体验和 packaged 一致。packaged 模式不动:Win toast 顶图由 AUMID 关联
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index ace0a54e98..d5ee8cc682 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3992,6 +3992,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
callback: (
payload:
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
@@ -4019,6 +4020,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
connect?: unknown;
messageClientId?: unknown;
islandEntryId?: unknown;
+ groupId?: unknown;
+ messageId?: unknown;
+ threadRootId?: unknown;
};
if (p.type === 'session' && typeof p.id === 'string' && p.id.length > 0) {
callback({
@@ -4032,6 +4036,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
? { islandEntryId: p.islandEntryId }
: {}),
});
+ } else if (p.type === 'chat-message' && typeof p.groupId === 'string' && typeof p.messageId === 'string'
+ && [p.groupId, p.messageId, ...(p.threadRootId === undefined ? [] : [p.threadRootId])].every(value => typeof value === 'string' && /^[0-9a-f-]{36}$/i.test(value))) {
+ callback({ type: 'chat-message', groupId: p.groupId, messageId: p.messageId,
+ ...(typeof p.threadRootId === 'string' ? { threadRootId: p.threadRootId } : {}) });
} else if (p.type === 'settings' && (p.tab === 'voice-input' || p.tab === 'providers')) {
// connect 只对 providers 页有意义;主进程已做 id 白名单,这里按纵深防御
// 原样复用同一规则。字段存在但不合法时丢弃整个 payload,不降级成半执行。
@@ -4090,6 +4098,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 详见 main/deepLink.ts 的 pending buffer 段。
takePendingDeepLink: (): Promise<
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index d762ec435f..d21f5d81b8 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -699,6 +699,7 @@ export function MainLayout() {
(
payload:
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
@@ -709,6 +710,12 @@ export function MainLayout() {
| { type: 'provider-share-join'; link: string }
| { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' },
) => {
+ if (payload.type === 'chat-message') {
+ const search = new URLSearchParams({ messageId: payload.messageId });
+ if (payload.threadRootId) search.set('threadRootId', payload.threadRootId);
+ navigate(`/bots/groups/${encodeURIComponent(payload.groupId)}?${search}`);
+ return;
+ }
if (payload.type === 'chat-invite') {
requestChatInvite(payload.token);
return;
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index fdb34ef1b1..7abe357154 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -31,6 +31,7 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { attachGhostMediaToSession, getGhostMediaHandoverFromDataTransfer } from '@/cindy-brain/ghostMediaHandover';
import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';
+import { NewMessageIndicator } from '@/components/chat/NewMessageIndicator';
import { shareSelectionStore, useShareSelectionActive } from '@/components/chat/shareSelectionStore';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Button } from '@/components/ui/button';
@@ -101,6 +102,7 @@ import {
import {
BOT_GROUP_SETTINGS_PARAM,
botGroupComposerPlanState,
+ botGroupNewMessageCount,
botGroupErrorKey,
botGroupMemberNames,
botGroupPlanFollowUp,
@@ -206,6 +208,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const controlledBannerCollapsed = useComposerCollapsed(controlledBannerKey);
const navigate = useNavigate();
const location = useLocation();
+ const notificationTarget = useMemo(() => {
+ const query = new URLSearchParams(location.search);
+ const messageId = query.get('messageId');
+ const threadRootId = query.get('threadRootId');
+ return messageId && /^[0-9a-f-]{36}$/i.test(messageId)
+ && (!threadRootId || /^[0-9a-f-]{36}$/i.test(threadRootId)) ? { messageId, threadRootId } : null;
+ }, [location.search]);
+ const handledNotification = useRef<string | null>(null);
const [state, setState] = useState<GroupViewState>({ kind: 'loading' });
const stateRef = useRef(state); stateRef.current = state;
const [reloadVersion, setReloadVersion] = useState(0);
@@ -218,6 +228,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const stickToBottomRef = useRef(true);
+ const [seenThrough, setSeenThrough] = useState<string | null>(null);
const readOwner = useRef(getDataOwnerGeneration());
const prependAnchorRef = useRef<{ height: number; top: number } | null>(null);
const attachmentScope = botGroupAttachmentScope(groupId);
@@ -508,10 +519,33 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
? Math.max(latest, message.createdAt) : latest, 0), [realMessages]);
const latestIncomingRef = useRef(latestIncomingAt);
latestIncomingRef.current = latestIncomingAt;
+ const latestSequence = realMessages.reduce((latest, message) => {
+ const position = message.serverSequence ?? String(message.sequence);
+ return BigInt(position) > BigInt(latest) ? position : latest;
+ }, '0');
+ const latestSequenceRef = useRef(latestSequence);
+ latestSequenceRef.current = latestSequence;
+ useEffect(() => {
+ if (state.kind === 'ready') setSeenThrough(previous => previous ?? latestSequence);
+ }, [state.kind, latestSequence]);
+ const newMessageCount = botGroupNewMessageCount(realMessages, seenThrough);
+ const readRequest = useRef<string | null>(null);
+ const readMessages = useRef(realMessages); readMessages.current = realMessages;
const acknowledge = useCallback(() => {
if (!isDataOwnerGenerationCurrent(readOwner.current) || !stickToBottomRef.current || document.visibilityState !== 'visible' || !document.hasFocus()) return;
+ const element = scrollRef.current;
+ if (!element || element.scrollHeight - element.scrollTop - element.clientHeight >= STICK_TO_BOTTOM_PX) return;
+ setSeenThrough(latestSequenceRef.current);
const at = latestIncomingRef.current;
if (at > 0) markBotRead(botGroupReadKey(groupId), at);
+ const current = stateRef.current;
+ 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 } })
+ .then(result => { if (!result.ok && readRequest.current === latest.id) readRequest.current = null; })
+ .catch(() => { if (readRequest.current === latest.id) readRequest.current = null; });
+ }
}, [groupId]);
const lastAcknowledgeRef = useRef(0);
const acknowledgeTimerRef = useRef<number | null>(null);
@@ -536,7 +570,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
window.addEventListener('focus', acknowledge);
document.addEventListener('visibilitychange', acknowledge);
return () => { cancelAnimationFrame(frame); window.removeEventListener('focus', acknowledge); document.removeEventListener('visibilitychange', acknowledge); };
- }, [acknowledge, latestIncomingAt]);
+ }, [acknowledge, latestIncomingAt, latestSequence]);
const plans = useMemo(
() => (state.kind === 'ready' ? mergeBotGroupPlans(state.olderPlans, state.group.plans) : []),
@@ -766,7 +800,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
* Goes to a quoted message in this group's main timeline, paging back a bounded number
* of times. A deleted or unreachable original says so instead of jumping anywhere else.
*/
- const locateQuoted = async (quote: BotGroupQuoteView) => {
+ const locateQuoted = async (quote: Pick<BotGroupQuoteView, 'messageId' | 'sequence'>) => {
if (locatingRef.current) return;
const find = (list: readonly BotGroupMessageView[]) => list.find(message => message.id === quote.messageId && !message.threadRootId);
const settle = (original: BotGroupMessageView | undefined) => {
@@ -953,6 +987,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
setThreadFocus(focusMessageId ? { messageId: focusMessageId, nonce: Date.now() } : null);
}, []);
const onSending = useCallback(() => { stickToBottomRef.current = true; }, []);
+ const locateNotification = useRef(locateQuoted); locateNotification.current = locateQuoted;
+ useEffect(() => {
+ if (state.kind !== 'ready' || !notificationTarget || handledNotification.current === location.key) return;
+ handledNotification.current = location.key;
+ stickToBottomRef.current = false;
+ if (notificationTarget.threadRootId) onOpenThread(notificationTarget.threadRootId, notificationTarget.messageId);
+ else void locateNotification.current({ messageId: notificationTarget.messageId, sequence: null });
+ }, [state.kind, notificationTarget, location.key, onOpenThread]);
const planById = useMemo(() => new Map(plans.map((plan) => [plan.id, plan])), [plans]);
const layout = useMemo(() => layoutBotGroupTimeline(rows), [rows]);
@@ -1106,6 +1148,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
data-testid="bot-group-timeline"
onScroll={(event) => {
const element = event.currentTarget;
+ if (stickToBottomRef.current) setSeenThrough(latestSequenceRef.current);
stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < STICK_TO_BOTTOM_PX;
if (stickToBottomRef.current) acknowledgeSoon();
}}
@@ -1214,6 +1257,15 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
: <BotGroupSpeakingLine key={`${speaker.member.botId}:${speaker.activity}`} speaker={speaker} />))}
</div>
</div>
+ <div className="relative h-0 shrink-0" inert={newMessageCount <= 0}>
+ <NewMessageIndicator visible={newMessageCount > 0} count={newMessageCount} bottomOffset={12} onClick={() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ stickToBottomRef.current = true;
+ element.scrollTop = element.scrollHeight;
+ acknowledge();
+ }} />
+ </div>
{hasControlledBanner && (
// Like teammate chats, keep the collapsed breathing light above the composer.
<div className="shrink-0 px-5 pt-2">
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
index a49a9654b5..e3ceea2b0e 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
@@ -213,7 +213,10 @@ export function BotGroupSidebarRow({
)}
>
{timestamp}
- <NavigationCountBadge count={unread} label={t('sidebar.teammateUnreadCount', { count: unread })} className="ml-auto mt-1 w-fit" />
+ <span className="mt-1 flex items-center justify-end gap-1">
+ {unread > 0 && group.serverUnread?.mentioned && <span className="text-[var(--text-primary)]" title={t('bots.groupChat.server.thread.hintMentioned')}>@</span>}
+ <NavigationCountBadge count={unread} label={t('sidebar.teammateUnreadCount', { count: unread })} className="w-fit" />
+ </span>
</span>
</button>
{children}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index e6bc652c53..85f374d2fd 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -2937,11 +2937,13 @@ it('keeps copy/share in each author row\'s more menu and shares only message con
const scroll = view.container.querySelector('.overflow-y-auto.px-5') as HTMLElement;
Object.defineProperties(scroll, { scrollHeight: { configurable: true, value: 1000 }, clientHeight: { configurable: true, value: 100 } });
scroll.scrollTop = 0; fireEvent.scroll(scroll);
- mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [msg({ id: 'new', ...incoming, content: 'New reply', createdAt: 1200 })] }) });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [msg({ id: 'new', sequence: 3, ...incoming, content: 'New reply', createdAt: 1200 })] }) });
act(() => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
await screen.findByText('New reply');
act(() => window.dispatchEvent(new Event('focus')));
expect(getBotLastReadAt(botGroupReadKey('g1'))).toBe(200);
+ expect(scroll.scrollTop).toBe(0);
+ expect(screen.getByRole('button', { name: 'chat.newMessageIndicator.aria' })).toBeTruthy();
scroll.scrollTop = 900; fireEvent.scroll(scroll);
expect(getBotLastReadAt(botGroupReadKey('g1'))).toBe(1200);
} finally { focus.mockRestore(); resetBotReadStateForTests(); }
diff --git a/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts b/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts
index 549f22061a..d52858368e 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupPresentation.ts
@@ -15,6 +15,7 @@ import { botGroupErrorVariant, botGroupNoticeVariant } from '@cindy/maker-shared
export {
botGroupComposerPlanState,
+ botGroupNewMessageCount,
botGroupMemberNames,
botGroupPathBasename,
botGroupPlanFilePath,
diff --git a/apps/desktop/src/renderer/features/bots/botReadState.ts b/apps/desktop/src/renderer/features/bots/botReadState.ts
index 6a7b08ae4b..090bcd024d 100644
--- a/apps/desktop/src/renderer/features/bots/botReadState.ts
+++ b/apps/desktop/src/renderer/features/bots/botReadState.ts
@@ -146,7 +146,7 @@ export function resetBotReadStateForTests(): void {
/** Group replies use the same owner-scoped, monotonic local read positions. */
export const botGroupReadKey = (groupId: string) => `group:${groupId}`;
-type GroupReadSummary = Pick<BotGroupSummary, 'id' | 'lastReplyAt'> & Partial<Pick<BotGroupSummary, 'lastMessage'>> & {
+type GroupReadSummary = Pick<BotGroupSummary, 'id' | 'lastReplyAt'> & Partial<Pick<BotGroupSummary, 'lastMessage' | 'serverUnread'>> & {
/**
* ISO times of the group's latest (up to 99) messages from others — Bots and other humans,
* never the reader's own or notices — oldest first. Older hosts omit it.
@@ -166,6 +166,7 @@ function latestGroupReplyAt(group: GroupReadSummary): number {
* most 99); a host without the list only says whether anything is new (1).
*/
export function botGroupUnreadCount(group: GroupReadSummary): number {
+ if (group.serverUnread) return group.serverUnread.count;
const readAt = getBotLastReadAt(botGroupReadKey(group.id));
if (readAt === null) return 0;
const latestUnread = latestGroupReplyAt(group) > readAt ? 1 : 0;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index e795676649..572dc46e28 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3054,6 +3054,7 @@ interface ElectronAPI {
callback: (
payload:
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
@@ -3074,6 +3075,7 @@ interface ElectronAPI {
*/
takePendingDeepLink: () => Promise<
| { type: 'session'; id: string; messageClientId?: string; islandEntryId?: string }
+ | { type: 'chat-message'; groupId: string; messageId: string; threadRootId?: string }
| { type: 'project'; workingDir: string }
| { type: 'new-session'; workingDir: string }
| { type: 'share-import'; filePath: string }
diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js
index 92612eefc4..9301d41759 100644
--- a/apps/mobile/app.config.js
+++ b/apps/mobile/app.config.js
@@ -310,6 +310,10 @@ module.exports = (context = {}) => {
android: {
...baseConfig.android,
package: regional.androidPackage,
+ // Public Firebase application configuration, supplied by the selected build profile.
+ // No file is bundled from another app identity or copied from a user's installation.
+ ...(process.env.CINDY_ANDROID_GOOGLE_SERVICES_FILE?.trim()
+ ? { googleServicesFile: process.env.CINDY_ANDROID_GOOGLE_SERVICES_FILE.trim() } : {}),
},
// 非自建线的 EAS Update 入口:由下发的 projectId 推导;自建分支下方会把它覆写成
// selfhost 占位(真实地址运行时由 mobileUpdateBaseUrl 注入)。projectId 缺省则不配 OTA。
diff --git a/apps/mobile/app/companions/groups/[groupId].tsx b/apps/mobile/app/companions/groups/[groupId].tsx
index a38e5884dd..f2494cc54d 100644
--- a/apps/mobile/app/companions/groups/[groupId].tsx
+++ b/apps/mobile/app/companions/groups/[groupId].tsx
@@ -12,10 +12,10 @@ function firstParam(value: string | string[] | undefined): string {
* which carries no computer name; the screen then shows the id until the group loads.
*/
export default function BotGroupChatRoute() {
- const params = useLocalSearchParams<{ groupId?: string | string[]; deviceId?: string | string[]; deviceName?: string | string[] }>();
+ const params = useLocalSearchParams<{ groupId?: string | string[]; deviceId?: string | string[]; deviceName?: string | string[]; messageId?: string | string[]; threadRootId?: string | string[]; notificationResponse?: string | string[] }>();
const { accountGeneration } = useAuth();
const groupId = firstParam(params.groupId);
const deviceId = firstParam(params.deviceId);
- return <BotGroupChatScreen key={`${accountGeneration}:${deviceId}:${groupId}`} groupId={groupId} deviceId={deviceId}
- deviceName={firstParam(params.deviceName)} />;
+ return <BotGroupChatScreen key={`${accountGeneration}:${deviceId}:${groupId}:${firstParam(params.threadRootId)}`} groupId={groupId} deviceId={deviceId}
+ threadRootId={firstParam(params.threadRootId) || undefined} deviceName={firstParam(params.deviceName)} messageId={firstParam(params.messageId)} notificationResponse={firstParam(params.notificationResponse)} />;
}
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index b1ab166aa1..a99a9a6e62 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -5,6 +5,7 @@ import { useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import {
Alert,
+ AppState,
Linking,
Platform,
Pressable,
@@ -62,7 +63,10 @@ import {
readPushEnabled,
syncPushRegistration,
writePushEnabled,
+ readPushPreviewEnabled,
+ writePushPreviewEnabled,
} from '@/notifications/pushNotifications';
+import { isChatBackgroundSupported, readChatBackgroundEnabled, writeChatBackgroundEnabled } from '@/notifications/chatBackground';
import {
hydrateMobileVoiceDictionary,
readCachedMobileVoiceDictionarySnapshot,
@@ -146,6 +150,8 @@ export default function SettingsScreen() {
const [updatePhase, setUpdatePhase] = useState<UpdatePhase>('idle');
const [updateOutcome, setUpdateOutcome] = useState<ManualUpdateCheckOutcome | null>(null);
const [pushEnabled, setPushEnabled] = useState(false);
+ const [pushPreview, setPushPreview] = useState(true);
+ const [chatBackground, setChatBackground] = useState(false);
const [pushBusy, setPushBusy] = useState(false);
const [pushMessage, setPushMessage] = useState<string | null>(null);
// 使用统计(TapDB)开关。真相在 analyticsConsentStore,这里只是视图态。
@@ -385,8 +391,13 @@ export default function SettingsScreen() {
void readPushEnabled().then((enabled) => {
if (!cancelled) setPushEnabled(enabled);
});
+ void readPushPreviewEnabled().then(value => { if (!cancelled) setPushPreview(value); });
+ const refreshBackground = () => { void readChatBackgroundEnabled().then(value => { if (!cancelled) setChatBackground(value); }); };
+ refreshBackground();
+ const foreground = AppState.addEventListener('change', state => { if (state === 'active') refreshBackground(); });
return () => {
cancelled = true;
+ foreground.remove();
};
}, []);
@@ -439,6 +450,7 @@ export default function SettingsScreen() {
}
await writePushEnabled(true);
setPushEnabled(true);
+ if (result === 'local-only') setPushMessage(t('settings.notifications.googleUnavailable'));
} catch (error) {
setPushMessage(formatRemoteError(error));
} finally {
@@ -642,10 +654,10 @@ export default function SettingsScreen() {
) : null}
</SettingsGroup>
- {/* 通知:任务完成推送(仅 iOS;Android 待 FCM/厂商通道) */}
+ {/* Notification permission and preview preferences belong to this installation. */}
{isPushSupported() ? (
<SettingsGroup
- footer={t('settings.notifications.taskDoneHint')}
+ footer={t('settings.notifications.taskDoneHint') + (isChatBackgroundSupported() ? ` ${t('settings.notifications.backgroundHint')}` : '')}
messages={[pushMessage ? { text: pushMessage, testID: 'settings.pushMessage' } : null]}
title={t('settings.notifications.sectionTitle')}
>
@@ -659,6 +671,31 @@ export default function SettingsScreen() {
testID="settings.pushToggleRow"
value={pushEnabled}
/>
+ <SettingsSwitchRow
+ accessibilityLabel={t('settings.notifications.preview')}
+ label={t('settings.notifications.preview')}
+ value={pushPreview}
+ disabled={pushBusy || !pushEnabled}
+ onValueChange={() => {
+ const next = !pushPreview;
+ setPushBusy(true);
+ void writePushPreviewEnabled(next).then(() => {
+ setPushPreview(next);
+ return syncPushRegistration({ enabled: pushEnabled, apiFetch: auth.apiFetch });
+ }).catch(error => setPushMessage(formatRemoteError(error))).finally(() => setPushBusy(false));
+ }}
+ />
+ {isChatBackgroundSupported() ? <SettingsSwitchRow
+ accessibilityLabel={t('settings.notifications.background')}
+ label={t('settings.notifications.background')}
+ value={chatBackground}
+ disabled={pushBusy || !pushEnabled}
+ onValueChange={() => {
+ const next = !chatBackground;
+ void writeChatBackgroundEnabled(next).then(() => setChatBackground(next))
+ .catch(error => setPushMessage(formatRemoteError(error)));
+ }}
+ /> : null}
</SettingsGroup>
) : null}
diff --git a/apps/mobile/modules/cindy-chat-notifications/android/build.gradle b/apps/mobile/modules/cindy-chat-notifications/android/build.gradle
new file mode 100644
index 0000000000..3333df2aef
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/android/build.gradle
@@ -0,0 +1,16 @@
+plugins {
+ id 'com.android.library'
+ id 'expo-module-gradle-plugin'
+}
+group = 'app.cindy.notifications'
+version = '0.1.0'
+android {
+ namespace 'app.cindy.notifications'
+ defaultConfig { versionCode 1; versionName '0.1.0' }
+}
+dependencies {
+ implementation expoModule.getExpoDependency('expo-notifications')
+ implementation 'androidx.core:core:1.15.0'
+ implementation 'com.squareup.okhttp3:okhttp:4.12.0'
+ implementation 'com.google.firebase:firebase-messaging:25.0.1'
+}
diff --git a/apps/mobile/modules/cindy-chat-notifications/android/src/main/AndroidManifest.xml b/apps/mobile/modules/cindy-chat-notifications/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..3845b78874
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/AndroidManifest.xml
@@ -0,0 +1,17 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
+ <application>
+ <service android:name="expo.modules.notifications.service.ExpoFirebaseMessagingService" tools:node="remove" />
+ <service android:name=".ChatFirebaseService" android:exported="false">
+ <intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT" /></intent-filter>
+ </service>
+ <service android:name=".ChatConnectionService" android:exported="false" android:foregroundServiceType="specialUse">
+ <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
+ android:value="User-enabled real-time chat delivery over an authenticated connection when Google push is unavailable; visible ongoing notification with a stop action." />
+ </service>
+ <receiver android:name=".ChatNotificationsService" android:exported="false">
+ <intent-filter android:priority="10"><action android:name="expo.modules.notifications.NOTIFICATION_EVENT" /></intent-filter>
+ </receiver>
+ </application>
+</manifest>
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.kt
new file mode 100644
index 0000000000..400611f9e1
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatConnectionService.kt
@@ -0,0 +1,192 @@
+package app.cindy.notifications
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import androidx.core.app.NotificationCompat
+import androidx.core.app.ServiceCompat
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+import org.json.JSONArray
+import org.json.JSONObject
+import java.time.Instant
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+internal data class ChatConnection(val owner: String, val actor: String, val base: String, val token: String,
+ val title: String, val stopLabel: String, val preview: Boolean)
+
+/** User-visible, opt-in socket. No boot receiver, hidden restart or stored access token. */
+class ChatConnectionService : Service() {
+ companion object {
+ @Volatile private var configuration: ChatConnection? = null
+ @Volatile var running = false; private set
+ @Volatile var refreshRequested: (() -> Unit)? = null
+ internal fun configure(value: ChatConnection) { configuration = value }
+ fun clear() { configuration = null }
+ private const val CHANNEL = "chat-background"
+ private const val ID = 7041
+ private const val STOP = "app.cindy.notifications.STOP"
+ }
+ private val handler = Handler(Looper.getMainLooper())
+ private val executor = Executors.newSingleThreadExecutor()
+ private val http = OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
+ .callTimeout(25, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false).build()
+ private var socket: WebSocket? = null
+ @Volatile private var active: ChatConnection? = null
+ @Volatile private var stopped = false
+ private var retry = 1000L
+ private var cursor = Instant.now().minusSeconds(60).toString()
+ private var cursorId = "00000000-0000-0000-0000-000000000000"
+ private var drainPending = false
+ private fun scheduleDrain() {
+ handler.post {
+ if (stopped || drainPending) return@post
+ drainPending = true
+ // Match cloud delivery's grace period: a device reading this chat can
+ // acknowledge the message before the inbox rechecks eligibility.
+ handler.postDelayed({
+ drainPending = false
+ active?.takeIf { current(it) }?.let { config ->
+ executor.execute { try { drain(config) } catch (_: Exception) { socket?.close(1000, "Reconnect") } }
+ }
+ }, 2000)
+ }
+ }
+ private val refresh = object : Runnable {
+ override fun run() {
+ if (stopped) return
+ refreshRequested?.invoke() // JS AuthContext owns rotation and secure credential storage.
+ val next = configuration
+ if (next == null) { stopSelf(); return }
+ if (next != active) executor.execute { connect(next) }
+ handler.postDelayed(this, 60000)
+ }
+ }
+ override fun onBind(intent: Intent?): IBinder? = null
+ override fun onCreate() { super.onCreate(); running = true }
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == STOP) {
+ getSharedPreferences("cindy-chat-background", MODE_PRIVATE).edit().putBoolean("paused", true).apply()
+ clear(); stopSelf(); return START_NOT_STICKY
+ }
+ val config = configuration
+ if (config == null || getSharedPreferences("cindy-chat-background", MODE_PRIVATE).getBoolean("paused", false)) {
+ stopSelf(); return START_NOT_STICKY
+ }
+ val manager = getSystemService(NotificationManager::class.java)
+ if (Build.VERSION.SDK_INT >= 26) manager.createNotificationChannel(NotificationChannel(CHANNEL, config.title, NotificationManager.IMPORTANCE_LOW))
+ val stop = PendingIntent.getService(this, ID, Intent(this, ChatConnectionService::class.java).setAction(STOP), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val open = packageManager.getLaunchIntentForPackage(packageName)?.let {
+ PendingIntent.getActivity(this, ID, it, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ }
+ val notification = NotificationCompat.Builder(this, CHANNEL).setSmallIcon(android.R.drawable.stat_notify_chat)
+ .setContentTitle(config.title).setContentIntent(open).setOngoing(true).setSilent(true)
+ .addAction(0, config.stopLabel, stop).build()
+ ServiceCompat.startForeground(this, ID, notification,
+ if (Build.VERSION.SDK_INT >= 34) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0)
+ handler.removeCallbacks(refresh); handler.post(refresh)
+ return START_NOT_STICKY
+ }
+ override fun onDestroy() {
+ stopped = true; running = false; active = null; clear()
+ handler.removeCallbacksAndMessages(null); socket?.cancel(); socket = null
+ http.dispatcher.cancelAll(); executor.shutdownNow()
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ super.onDestroy()
+ }
+ private fun current(config: ChatConnection) = !stopped && active === config && configuration?.owner == config.owner
+ private 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 ->
+ if (response.code == 401) handler.post { refreshRequested?.invoke() }
+ check(response.isSuccessful) { "CHAT_REQUEST_FAILED" }
+ val body = response.body ?: throw Exception("CHAT_EMPTY_RESPONSE")
+ // Bound responses independently of Content-Length, including chunked bodies.
+ val output = java.io.ByteArrayOutputStream()
+ val input = body.byteStream(); val buffer = ByteArray(8192)
+ while (true) {
+ val count = input.read(buffer); if (count < 0) break
+ check(output.size() + count <= 512 * 1024)
+ output.write(buffer, 0, count)
+ }
+ val bytes = output.toByteArray()
+ check(current(config))
+ return String(bytes, Charsets.UTF_8)
+ }
+ }
+ private fun connect(config: ChatConnection) {
+ if (stopped || configuration?.owner != config.owner) return
+ val old = active; active = config; socket?.cancel()
+ if (old?.owner != config.owner) { cursor = Instant.now().minusSeconds(60).toString(); cursorId = "00000000-0000-0000-0000-000000000000" }
+ val request = Request.Builder().url(config.base.replaceFirst("https:", "wss:") + "/v1/ws").build()
+ socket = http.newWebSocket(request, object : WebSocketListener() {
+ override fun onOpen(ws: WebSocket, response: Response) {
+ if (!current(config)) { ws.cancel(); return }
+ ws.send(JSONObject().put("type", "auth").put("token", config.token).toString())
+ }
+ override fun onMessage(ws: WebSocket, text: String) {
+ if (!current(config) || text.length > 512 * 1024) return
+ executor.execute {
+ try {
+ if (!current(config)) return@execute
+ val frame = JSONObject(text)
+ when (frame.optString("type")) {
+ "ready" -> {
+ check(frame.getString("actorId") == config.actor)
+ // A compacted actor scope responds with scope_error/head; the inbox is the
+ // durable source, so neither a fresh connection nor replay can lose notices.
+ ws.send(JSONObject().put("type", "subscribe").put("scope", "actor:${config.actor}").put("after", "0").toString())
+ retry = 1000; scheduleDrain()
+ }
+ "changes" -> {
+ scheduleDrain()
+ ws.send(JSONObject().put("type", "ack").put("scope", frame.getString("scope")).put("cursor", frame.getString("cursor")).toString())
+ }
+ "scope_error" -> {
+ val head = frame.optJSONObject("error")?.optJSONObject("details")?.optString("head")
+ if (!head.isNullOrBlank()) {
+ scheduleDrain()
+ ws.send(JSONObject().put("type", "subscribe").put("scope", "actor:${config.actor}").put("after", head).toString())
+ } else ws.close(1000, "Reconnect")
+ }
+ "error" -> ws.close(1000, "Reconnect")
+ }
+ } catch (_: Exception) { ws.close(1000, "Reconnect") }
+ }
+ }
+ override fun onClosed(ws: WebSocket, code: Int, reason: String) = reconnect(config)
+ override fun onFailure(ws: WebSocket, error: Throwable, response: Response?) = reconnect(config)
+ })
+ }
+ private fun reconnect(config: ChatConnection) {
+ if (!current(config)) return
+ val delay = retry; retry = minOf(retry * 2, 30000)
+ handler.postDelayed({ configuration?.takeIf { current(config) }?.let { next -> executor.execute { connect(next) } } }, delay)
+ }
+ private fun drain(config: ChatConnection) {
+ for (page in 0 until 10) {
+ val query = okhttp3.HttpUrl.Builder().scheme("https").host("cursor.invalid").addQueryParameter("after", cursor).addQueryParameter("afterId", cursorId).build().encodedQuery
+ val rows = JSONArray(get(config, "/push/inbox?$query"))
+ for (i in 0 until rows.length()) {
+ if (!current(config)) return
+ val row = rows.getJSONObject(i); val payload = row.getJSONObject("payload")
+ if (!config.preview) { payload.remove("body"); payload.remove("sender"); payload.remove("senderName") }
+ ChatDelivery.receive(this, mapOf("tag" to payload.getString("collapseId"), "title" to payload.getString("title"),
+ "message" to payload.optString("body"), "body" to payload.toString(), "channelId" to "chat-messages"))
+ cursor = row.getString("cursor"); cursorId = row.getString("id")
+ }
+ if (rows.length() < 100) return
+ }
+ }
+}
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.kt
new file mode 100644
index 0000000000..eeadebfd63
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/ChatDelivery.kt
@@ -0,0 +1,118 @@
+package app.cindy.notifications
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.util.Base64
+import androidx.core.app.NotificationCompat
+import androidx.core.app.Person
+import androidx.core.graphics.drawable.IconCompat
+import com.google.firebase.messaging.RemoteMessage
+import expo.modules.notifications.service.ExpoFirebaseMessagingService
+import expo.modules.notifications.service.NotificationsService
+import expo.modules.notifications.service.delegates.ExpoPresentationDelegate
+import expo.modules.notifications.service.delegates.FirebaseMessagingDelegate
+import expo.modules.notifications.service.interfaces.PresentationDelegate
+import expo.modules.notifications.notifications.model.Notification
+import expo.modules.notifications.notifications.model.NotificationBehaviorRecord
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** Only actor/message IDs persist. Credentials and notification bodies never enter this store. */
+object ChatDelivery {
+ private const val STORE = "cindy-chat-notification-ids"
+ @Synchronized fun identity(context: Context, actor: String) {
+ val prefs = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
+ if (prefs.getString("actor", "") != actor) prefs.edit().clear().putString("actor", actor).apply()
+ }
+ @Synchronized fun receive(context: Context, data: Map<String, String>) {
+ val body = try { JSONObject(data["body"] ?: "{}") } catch (_: Exception) { return }
+ if (body.optString("category") == "chat-message") {
+ val prefs = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
+ val actor = prefs.getString("actor", "") ?: ""
+ if (actor.isEmpty() || body.optString("recipientId") != actor) return
+ val id = data["tag"] ?: return
+ if (!id.matches(Regex("[a-fA-F0-9-]{36}"))) return
+ val ids = try { JSONArray(prefs.getString("ids", "[]")) } catch (_: Exception) { JSONArray() }
+ if ((0 until ids.length()).any { ids.optString(it) == id }) return
+ val next = JSONArray()
+ for (i in maxOf(0, ids.length() - 255) until ids.length()) next.put(ids.getString(i))
+ next.put(id)
+ 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)) {
+ body.remove("sender"); body.remove("senderName"); body.remove("body")
+ display["body"] = body.toString(); display["message"] = ""
+ }
+ FirebaseMessagingDelegate(context).onMessageReceived(RemoteMessage.Builder("cindy").setData(display).build())
+ }
+}
+
+class ChatFirebaseService : ExpoFirebaseMessagingService() {
+ override fun onMessageReceived(remoteMessage: RemoteMessage) = ChatDelivery.receive(this, remoteMessage.data)
+}
+
+/** Keep Expo's pending-intent, cold-start response and foreground suppression contracts. */
+class ChatNotificationsService : NotificationsService() {
+ override fun getPresentationDelegate(context: Context): PresentationDelegate = object : ExpoPresentationDelegate(context) {
+ override suspend fun createNotification(notification: Notification, notificationBehavior: NotificationBehaviorRecord?): android.app.Notification {
+ val original = super.createNotification(notification, notificationBehavior)
+ val content = notification.notificationRequest.content
+ val data = content.body ?: return original
+ val chat = data.optString("category") == "chat-message"
+ val sender = data.optJSONObject("sender")
+ if (!chat && (data.optString("category") != "session-done" || sender == null)) return original
+ val name = if (chat) data.optString("senderName") else content.title ?: ""
+ if (name.isBlank()) return original
+ val person = Person.Builder().setName(name).setKey(sender?.optString("id") ?: name)
+ .setIcon(IconCompat.createWithBitmap(avatar(context, sender?.optJSONObject("avatar"), name))).build()
+ val text = (content.text ?: "").removePrefix("$name: ")
+ return NotificationCompat.Builder(context, original)
+ .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)
+ .addMessage(text, notification.originDate.time.takeIf { it > 0 } ?: System.currentTimeMillis(), person)).build()
+ }
+ }
+}
+
+private fun avatar(context: Context, data: JSONObject?, name: String): Bitmap {
+ val value = data?.optString("value") ?: ""
+ if (data?.optString("kind") == "preset" && value in listOf("cindy", "dash", "lizi")) {
+ val resource = context.resources.getIdentifier("cindy_teammate_$value", "drawable", context.packageName)
+ if (resource != 0) {
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeResource(context.resources, resource, bounds)
+ val sample = BitmapFactory.Options().apply { inSampleSize = maxOf(1, maxOf(bounds.outWidth, bounds.outHeight) / 80) }
+ BitmapFactory.decodeResource(context.resources, resource, sample)?.let {
+ return Bitmap.createScaledBitmap(it, 80, 80, true)
+ }
+ }
+ }
+ if (data?.optString("kind") == "jpeg" && value.length <= 2048) {
+ try {
+ val bytes = Base64.decode(value, Base64.DEFAULT)
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
+ if (bounds.outWidth in 1..128 && bounds.outHeight in 1..128) {
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.let { return it }
+ }
+ } catch (_: Exception) { /* readable identity fallback */ }
+ }
+ val bitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)
+ // Native system notification identity placeholder, independent of application themes.
+ val colors = context.obtainStyledAttributes(intArrayOf(android.R.attr.colorBackground, android.R.attr.textColorPrimary))
+ paint.color = colors.getColor(0, android.graphics.Color.TRANSPARENT); canvas.drawCircle(40f,40f,40f,paint)
+ paint.color = colors.getColor(1, android.graphics.Color.TRANSPARENT); colors.recycle()
+ paint.textSize = 36f; paint.textAlign = Paint.Align.CENTER
+ val symbol = if (data?.optString("kind") == "symbol" && value.length <= 32) value else name.take(1).uppercase()
+ canvas.drawText(symbol,40f,40f-(paint.ascent()+paint.descent())/2,paint)
+ return bitmap
+}
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.kt
new file mode 100644
index 0000000000..142679c17e
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/android/src/main/java/app/cindy/notifications/CindyChatNotificationsModule.kt
@@ -0,0 +1,48 @@
+package app.cindy.notifications
+
+import android.content.Intent
+import androidx.core.content.ContextCompat
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+import expo.modules.kotlin.functions.Queues
+import java.net.URI
+
+class CindyChatNotificationsModule : Module() {
+ override fun definition() = ModuleDefinition {
+ Name("CindyChatNotifications")
+ Events("refreshRequested")
+ AsyncFunction("isPaused") {
+ appContext.reactContext?.getSharedPreferences("cindy-chat-background", android.content.Context.MODE_PRIVATE)?.getBoolean("paused", false) ?: false
+ }
+ AsyncFunction("resume") {
+ appContext.reactContext?.getSharedPreferences("cindy-chat-background", android.content.Context.MODE_PRIVATE)?.edit()?.putBoolean("paused", false)?.apply()
+ }
+ OnCreate { ChatConnectionService.refreshRequested = { sendEvent("refreshRequested") } }
+ OnDestroy { ChatConnectionService.refreshRequested = null }
+ AsyncFunction("setIdentity") { actor: String ->
+ val context = appContext.reactContext ?: return@AsyncFunction
+ ChatDelivery.identity(context, actor)
+ }
+ AsyncFunction("setPreview") { enabled: Boolean ->
+ 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 ->
+ 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))
+ // Only a visible activity can initiate the foreground service. Token updates
+ // from an already-running service never start/restart an application.
+ if (!ChatConnectionService.running) {
+ check(appContext.currentActivity?.hasWindowFocus() == true) { "CHAT_OPEN_APP_REQUIRED" }
+ ContextCompat.startForegroundService(context, Intent(context, ChatConnectionService::class.java))
+ }
+ }.runOnQueue(Queues.MAIN)
+ AsyncFunction("stop") {
+ appContext.reactContext?.let { ChatConnectionService.clear(); it.stopService(Intent(it, ChatConnectionService::class.java)) }
+ }
+ }
+}
diff --git a/apps/mobile/modules/cindy-chat-notifications/expo-module.config.json b/apps/mobile/modules/cindy-chat-notifications/expo-module.config.json
new file mode 100644
index 0000000000..c8309e11ba
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/expo-module.config.json
@@ -0,0 +1,4 @@
+{
+ "platforms": ["android"],
+ "android": { "modules": ["app.cindy.notifications.CindyChatNotificationsModule"] }
+}
diff --git a/apps/mobile/modules/cindy-chat-notifications/package.json b/apps/mobile/modules/cindy-chat-notifications/package.json
new file mode 100644
index 0000000000..d1ac7f8bf1
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "cindy-chat-notifications",
+ "version": "0.1.0",
+ "private": true,
+ "main": "src/index.ts",
+ "license": "Apache-2.0"
+}
diff --git a/apps/mobile/modules/cindy-chat-notifications/src/index.ts b/apps/mobile/modules/cindy-chat-notifications/src/index.ts
new file mode 100644
index 0000000000..a3d3ce8f62
--- /dev/null
+++ b/apps/mobile/modules/cindy-chat-notifications/src/index.ts
@@ -0,0 +1,11 @@
+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>;
+ stop(): Promise<void>;
+ isPaused(): Promise<boolean>;
+ resume(): Promise<void>;
+ setIdentity(actor: string): Promise<void>;
+ setPreview(enabled: boolean): Promise<void>;
+ addListener(event: 'refreshRequested', listener: () => void): { remove(): void };
+}
+export default requireOptionalNativeModule<ChatNotificationsNative>('CindyChatNotifications');
diff --git a/apps/mobile/plugins/communication-notifications/NotificationService.swift b/apps/mobile/plugins/communication-notifications/NotificationService.swift
index d107c96b3a..f39b8ad1f6 100644
--- a/apps/mobile/plugins/communication-notifications/NotificationService.swift
+++ b/apps/mobile/plugins/communication-notifications/NotificationService.swift
@@ -2,7 +2,8 @@ import Intents
import UIKit
import UserNotifications
-/// Enrich only teammate replies. No network or access to the app's account storage.
+/// Native communication notifications for teammate replies and group messages.
+/// No network or access to the app's account storage.
final class NotificationService: UNNotificationServiceExtension {
private let completionLock = NSLock()
private var handler: ((UNNotificationContent) -> Void)?
@@ -18,26 +19,32 @@ final class NotificationService: UNNotificationServiceExtension {
completionLock.unlock()
let content = request.content
- guard content.userInfo["category"] as? String == "session-done",
+ let category = content.userInfo["category"] as? String
+ let isChat = category == "chat-message"
+ guard category == "session-done" || 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 {
finish(content)
return
}
+ let senderName = isChat ? (content.userInfo["senderName"] as? String ?? "") : content.title
+ guard !senderName.isEmpty else { finish(content); return }
+ let prefix = senderName + ": "
+ let message = isChat && content.body.hasPrefix(prefix) ? String(content.body.dropFirst(prefix.count)) : content.body
let sender = INPerson(
personHandle: INPersonHandle(value: id, type: .unknown),
nameComponents: nil,
- displayName: content.title,
- image: Self.avatar(senderData["avatar"], name: content.title),
+ displayName: senderName,
+ image: Self.avatar(senderData["avatar"], name: senderName),
contactIdentifier: nil,
customIdentifier: id
)
let intent = INSendMessageIntent(
recipients: nil,
outgoingMessageType: .outgoingMessageText,
- content: content.body,
- speakableGroupName: nil,
+ content: message,
+ speakableGroupName: isChat ? INSpeakableString(spokenPhrase: content.title) : nil,
conversationIdentifier: content.threadIdentifier,
serviceName: nil,
sender: sender,
diff --git a/apps/mobile/plugins/with-communication-notifications.js b/apps/mobile/plugins/with-communication-notifications.js
index 223e4458fd..2ee6021c1d 100644
--- a/apps/mobile/plugins/with-communication-notifications.js
+++ b/apps/mobile/plugins/with-communication-notifications.js
@@ -1,10 +1,15 @@
const fs = require('node:fs');
const path = require('node:path');
const plist = require('@expo/plist');
-const { withEntitlementsPlist, withInfoPlist, withXcodeProject } = require('@expo/config-plugins');
+const { withDangerousMod, withEntitlementsPlist, withInfoPlist, withXcodeProject } = require('@expo/config-plugins');
const TARGET = 'CindyNotificationService';
const ENTITLEMENT = 'com.apple.developer.usernotifications.communication';
+const portraits = {
+ cindy: '../desktop/src/renderer/assets/bot-presets/cindy.png',
+ dash: '../desktop/resources/legacy-teammate-avatars/dash.png',
+ lizi: '../desktop/resources/legacy-teammate-avatars/lizi.png',
+};
function extensionInfo() {
return {
@@ -30,11 +35,6 @@ function configureProject(project, config, platformRoot, projectRoot) {
fs.copyFileSync(path.join(__dirname, 'communication-notifications/NotificationService.swift'), path.join(directory, 'NotificationService.swift'));
fs.writeFileSync(path.join(directory, 'Info.plist'), plist.default.build(extensionInfo()));
fs.writeFileSync(path.join(directory, `${TARGET}.entitlements`), plist.default.build({ [ENTITLEMENT]: true }));
- const portraits = {
- cindy: '../desktop/src/renderer/assets/bot-presets/cindy.png',
- dash: '../desktop/resources/legacy-teammate-avatars/dash.png',
- lizi: '../desktop/resources/legacy-teammate-avatars/lizi.png',
- };
for (const [name, file] of Object.entries(portraits)) {
fs.copyFileSync(path.resolve(projectRoot, file), path.join(directory, `teammate-${name}.png`));
}
@@ -70,6 +70,17 @@ function configureProject(project, config, platformRoot, projectRoot) {
}
module.exports = function withCommunicationNotifications(config) {
+ config = withDangerousMod(config, ['android', async mod => {
+ const res = path.join(mod.modRequest.platformProjectRoot, 'app/src/main/res');
+ fs.mkdirSync(path.join(res, 'drawable-nodpi'), { recursive: true });
+ fs.mkdirSync(path.join(res, 'raw'), { recursive: true });
+ for (const [name, file] of Object.entries(portraits)) {
+ fs.copyFileSync(path.resolve(mod.modRequest.projectRoot, file), path.join(res, 'drawable-nodpi', `cindy_teammate_${name}.png`));
+ }
+ fs.writeFileSync(path.join(res, 'raw/cindy_chat_keep.xml'),
+ '<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@drawable/cindy_teammate_*" />');
+ return mod;
+ }]);
config = withEntitlementsPlist(config, mod => {
mod.modResults[ENTITLEMENT] = true;
return mod;
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 1db1add04d..f81e323e5b 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -31,6 +31,7 @@ const h = vi.hoisted(() => ({
}));
vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn(async () => ({})) }));
+vi.mock('@/components/ChatReplyIcon', () => ({ ChatReplyIcon: () => null }));
vi.mock('react-native', () => {
const box = (tag: string) => ({ children, testID, accessibilityLabel, style }: any) =>
el(tag, { 'data-testid': testID, 'aria-label': accessibilityLabel,
@@ -429,6 +430,33 @@ describe('group timeline', () => {
await render(newer);
await act(async () => h.scroll.onContentSizeChange(400, 3000));
expect(h.markRead).not.toHaveBeenCalled();
+ // The reader stays in history, sees the arrival, and can explicitly return to it.
+ const jump = byId('botGroup.newMessages') as HTMLButtonElement;
+ expect(jump.textContent).toContain('count=1');
+ h.scrollToEnd.mockClear();
+ await act(async () => jump.click());
+ expect(h.scrollToEnd).toHaveBeenCalledWith({ animated: false });
+ expect(h.markRead).not.toHaveBeenCalled();
+ await act(async () => scroll(2500, 3000));
+ expect(byId('botGroup.newMessages')).toBeNull();
+ });
+
+ it('notices arrivals after a notification opens history without acknowledging the tail', async () => {
+ const data = group();
+ h.chat = { ...h.chat, state: { kind: 'ready', group: data } };
+ const props = { deviceId: 'mac', deviceName: 'Mac', groupId: 'g1', messageId: data.messages[0].id };
+ await act(async () => root.render(el(BotGroupChatScreen, props)));
+ await act(async () => {
+ h.scroll.onLayout({ nativeEvent: { layout: { height: 500 } } });
+ h.scroll.onContentSizeChange(400, 2000);
+ });
+ h.scrollToEnd.mockClear();
+ h.chat = { ...h.chat, state: { kind: 'ready', group: { ...data, messages: [...data.messages, message('arrival', 20, {})] } } };
+ await act(async () => root.render(el(BotGroupChatScreen, props)));
+ await act(async () => h.scroll.onContentSizeChange(400, 2500));
+ expect(byId('botGroup.newMessages')?.textContent).toContain('count=1');
+ expect(h.markRead).not.toHaveBeenCalled();
+ expect(h.scrollToEnd).not.toHaveBeenCalled();
});
it('acknowledges a short conversation only after both native dimensions are measured', async () => {
@@ -620,6 +648,27 @@ describe('group composer', () => {
});
}
+ // Both Chat Server entry paths must carry the selected original through the real composer.
+ it.each([true, false])('sends a quote and retains it after failure (direct server %s)', async server => {
+ h.chat.server = server;
+ const originalId = '11111111-1111-4111-8111-111111111111';
+ await render(group({ serverBacked: true, openPlan: null, messages: [
+ message(originalId, 1, { authorName: '咪咪', authorBotId: 'mimi', content: '请回复这条' }),
+ ] }));
+ await click(`botGroup.reply.${originalId}`);
+ await type('引用回复');
+ h.chat.act.mockRejectedValueOnce(new Error('QUOTE_UNAVAILABLE'));
+ await click('botGroup.composer.send');
+ expect(h.row.value).toBe('引用回复');
+ expect(byId('botGroup.cancelReply')).not.toBeNull();
+ await click('botGroup.composer.send');
+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({
+ text: '引用回复', quote: { messageId: originalId }, clientId: 'uuid-1',
+ }));
+ expect(byId('botGroup.cancelReply')).toBeNull();
+ expect(h.row.value).toBe('');
+ });
+
it.each([true, false])('locks an existing draft when dissolved without being archived (direct server %s)', async server => {
h.chat.server = server;
const live = group({ openPlan: null, archived: false });
diff --git a/apps/mobile/src/__tests__/BotGroupListUnread.test.tsx b/apps/mobile/src/__tests__/BotGroupListUnread.test.tsx
index 08032797c9..c361a63dfd 100644
--- a/apps/mobile/src/__tests__/BotGroupListUnread.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupListUnread.test.tsx
@@ -8,7 +8,7 @@ vi.mock('react-native', async () => { const { createElement } = await import('re
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' } }) }));
vi.mock('@/session/BotGroupAvatars', () => ({ BotGroupDuoAvatar: () => null, useBotGroupIdentities: () => () => ({}) }));
-vi.mock('@/session/messageMarkdown', () => ({ parseMobileMarkdownInlines: () => [] }));
+vi.mock('@/session/messageMarkdown', () => ({ parseMobileMarkdownInlines: () => [], mobileMarkdownPreviewText: (value: string) => value }));
vi.mock('@/session/sessionList', () => ({ formatRemoteSessionSidebarTime: () => 'now' }));
vi.mock('expo-router', () => ({ useIsFocused: () => true }));
vi.mock('@/theme', () => ({ useThemedStyles: () => ({}) }));
diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.ts
index 037416a36c..9570666e80 100644
--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts
+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts
@@ -310,5 +310,9 @@ describe('actions', () => {
expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: false, botIds: ['new'] }).clientId).toBe('c2');
expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: false, botIds: ['other', 'picked'] }).clientId).toBe('c3');
expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: true, botIds: ['picked', 'other'] }).clientId).toBe('c4');
+ const quoted = nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: false, botIds: ['picked', 'other'] }, 'original');
+ expect(quoted.clientId).toBe('c5');
+ expect(nextBotGroupSendAttempt(quoted, '@Ann', false, next, [], { all: false, botIds: ['picked', 'other'] }, 'original')).toBe(quoted);
+ expect(nextBotGroupSendAttempt(quoted, '@Ann', false, next, [], { all: false, botIds: ['picked', 'other'] }, 'another').clientId).toBe('c6');
});
});
diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.ts
index d3b365641a..080cd4b338 100644
--- a/apps/mobile/src/__tests__/chatServerClient.test.ts
+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts
@@ -251,6 +251,45 @@ describe('direct Chat Server client', () => {
});
expect(request.mock.calls[0]).toEqual(request.mock.calls[1]);
});
+ // Product rule: quoting a present companion addresses that companion; a deleted
+ // original must not send a stale quote or silently lose the user's reply.
+ it('sends a fresh quote with the companion recipient and rejects a deleted original', async () => {
+ const original = { ...message(20), authorId: id(12), author: { kind: 'bot', name: 'Before rename' } };
+ const member = { ...snapshot().members[0], id: id(12), kind: 'bot', state: 'joined', name: 'Current name' };
+ const request = vi.fn().mockImplementation(async (path: string, method?: string) => {
+ if (method === 'POST') return { id: id(21) };
+ return path.endsWith('/members') ? [member] : original;
+ });
+ const client = createChatServerClient(request);
+ const input = { clientId: 'quote-reply-operation', text: 'Agreed', mentions: { all: false, botIds: [] }, quote: { messageId: id(20) } };
+ await client.send(id(1), input);
+ expect(request).toHaveBeenLastCalledWith(`/conversations/${id(1)}/messages`, 'POST', expect.objectContaining({
+ mentions: [id(12)], content: [expect.objectContaining({ type: 'card' }), { type: 'text', text: 'Agreed' }],
+ }));
+ original.deleted = true;
+ request.mockClear();
+ await expect(client.send(id(1), input)).rejects.toThrow('QUOTE_UNAVAILABLE');
+ expect(request.mock.calls.some(([, method]) => method === 'POST')).toBe(false);
+ });
+ it('retries a lost quoted-send response with the identical posted content', async () => {
+ const original = message(20);
+ let lost = true;
+ const request = vi.fn().mockImplementation(async (path: string, method?: string) => {
+ if (method === 'POST') {
+ if (lost) { lost = false; throw new Error('NETWORK_ERROR'); }
+ return { id: id(21) };
+ }
+ return path.endsWith('/members') ? snapshot().members : original;
+ });
+ const client = createChatServerClient(request);
+ const input = { clientId: 'lost-quote-operation', text: 'Agreed', mentions: { all: false, botIds: [] }, quote: { messageId: id(20) } };
+ await expect(client.send(id(1), input)).rejects.toThrow('NETWORK_ERROR');
+ const posted = request.mock.calls.at(-1);
+ original.deleted = true;
+ await client.send(id(1), input);
+ expect(request.mock.calls.at(-1)).toEqual(posted);
+ expect(request.mock.calls.filter(([, method]) => method !== 'POST')).toHaveLength(2);
+ });
it('reauthorizes and replaces loaded older history on refresh instead of retaining deleted text', async () => {
const recent = Array.from({ length: 100 }, (_, n) => message(200 - n));
const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(recent)
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index 14bb7e1401..a7ab6f5e92 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -108,6 +108,7 @@ it('imports read_seq and acknowledges only displayed incoming messages with thei
createdAt: '2026-10-09T10:00:00.123Z', deleted: false, threadRootId: null }));
const original = h.auth.apiFetch.getMockImplementation()!;
h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/read')) return { readSeq: options.body.readSeq };
if (path.includes('/messages?')) return messages;
const value = await original(path, options);
return path.endsWith('/snapshot') ? { ...value, messages, cursor: second, reads: [{ thread_key: 'main', read_seq: first }] } : value;
@@ -121,7 +122,11 @@ it('imports read_seq and acknowledges only displayed incoming messages with thei
expect(unread()).toBe(true);
await act(async () => { await chat.markRead!([messages[0].id, messages[1].id]); });
expect(unread()).toBe(false);
- expect(h.auth.apiFetch.mock.calls.some(([, options]) => options.method === 'POST')).toBe(false);
+ expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/read`, expect.objectContaining({
+ method: 'POST', body: { operationId: `read-main:${second}`, readSeq: second },
+ }));
+ await act(async () => { await chat.markRead!([messages[0].id, messages[1].id]); });
+ expect(h.auth.apiFetch.mock.calls.filter(([path]) => path.endsWith('/read'))).toHaveLength(1);
});
it('resolves everyone using authorized members at send time instead of the displayed snapshot', async () => {
const joined = '00000000-0000-4000-8000-000000000003';
diff --git a/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts b/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts
index af2228e354..42d2ce9176 100644
--- a/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts
+++ b/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts
@@ -1,27 +1,16 @@
-/**
- * Android 与 expo-notifications 原生模块解耦的守门(静态断言 + 面接口对齐)。
- *
- * expo-notifications 的 JS 入口在 **import 期**就 `requireNativeModule(...)`,原生模块
- * 缺失即抛;而 Android 推送从未实现(`isPushSupported()` 只放行 iOS),那颗原生模块只是
- * 把 Firebase Messaging / Installations / DataTransport 与消息权限带进 Android 包。
- * 因此约定:业务代码只经 `@/notifications/nativeNotifications` 访问该 SDK,Android 由
- * `nativeNotifications.android.ts` 顶成空实现,Android bundle 完全不引用真模块。
- *
- * 这两条断言拦的是**运行期才会暴露**的两类回归:
- * 1. 有人在别处直接 import 'expo-notifications' → Android 冷启动崩(typecheck 拦不住);
- * 2. 有人新增 `Notifications.foo()` 调用但没在 Android 替身里补 foo → Android 上
- * `undefined is not a function`。typecheck 已能拦第 2 类(替身按
- * NativeNotificationsApi 收敛),这里再加一道源码级兜底,顺带覆盖 app/ 路由文件。
- */
+/** SDK imports stay at the platform adapters; Android now has an actual FCM receiver. */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
-// 真模块拖 react-native 依赖链,node 环境下不可 import;替身只用到 PermissionStatus 枚举。
-vi.mock('expo-modules-core', () => ({
- PermissionStatus: { GRANTED: 'granted', UNDETERMINED: 'undetermined', DENIED: 'denied' },
+// Native calls are mocked at the SDK boundary; adapter surface remains checked.
+vi.mock('expo-notifications', () => ({
+ setNotificationHandler: vi.fn(), getPermissionsAsync: vi.fn(), requestPermissionsAsync: vi.fn(),
+ getDevicePushTokenAsync: vi.fn(), addPushTokenListener: vi.fn(), addNotificationResponseReceivedListener: vi.fn(),
+ getLastNotificationResponseAsync: vi.fn(), clearLastNotificationResponseAsync: vi.fn(),
+ setNotificationChannelAsync: vi.fn(), AndroidImportance: { HIGH: 4 }, AndroidNotificationVisibility: { PRIVATE: 0 },
}));
const SRC_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -31,6 +20,7 @@ const NOTIFICATIONS_DIR = path.join(SRC_ROOT, 'notifications');
/** 唯一允许出现 'expo-notifications' 的两个文件:真接入点与它的纯类型契约。 */
const SDK_ALLOWLIST = new Set([
path.join(NOTIFICATIONS_DIR, 'nativeNotifications.ts'),
+ path.join(NOTIFICATIONS_DIR, 'nativeNotifications.android.ts'),
path.join(NOTIFICATIONS_DIR, 'nativeNotifications.types.ts'),
]);
@@ -61,7 +51,7 @@ function allSourceFiles(): string[] {
return [...walkSourceFiles(SRC_ROOT), ...walkSourceFiles(APP_ROOT)];
}
-describe('Android 不引用 expo-notifications 原生模块', () => {
+describe('通知 SDK 只由平台适配层访问', () => {
// 守门自身的判据要有用例:正则悄悄失配会让上面两条断言变成永绿的假保险。
it('模块引用正则认得各种写法,且不被散文/相似词误命中', () => {
for (const violation of [
diff --git a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts
index 98e4779f11..16bc2071f8 100644
--- a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts
+++ b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
getPermissionsAsync: vi.fn(),
requestPermissionsAsync: vi.fn(),
getDevicePushTokenAsync: vi.fn(),
+ setNotificationHandler: vi.fn(),
}));
vi.mock('@react-native-async-storage/async-storage', () => ({
@@ -33,7 +34,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({
}));
vi.mock('expo-notifications', () => ({
- setNotificationHandler: vi.fn(),
+ setNotificationHandler: mocks.setNotificationHandler,
getPermissionsAsync: mocks.getPermissionsAsync,
requestPermissionsAsync: mocks.requestPermissionsAsync,
getDevicePushTokenAsync: mocks.getDevicePushTokenAsync,
@@ -59,6 +60,7 @@ vi.mock('@/config/devServerEnvironment', () => ({
}));
import {
+ configureForegroundNotificationBehavior,
retryPendingUnregister,
syncPushRegistration,
unregisterPushTokenBestEffort,
@@ -83,6 +85,20 @@ function readStoredRealms(key: string): string[] {
}
describe('push notification realm routing', () => {
+ // Same group, another thread must still be noticeable while reading the main timeline.
+ it('passes the thread route to the foreground visibility gate', async () => {
+ const room = '00000000-0000-4000-8000-000000000001';
+ const message = '00000000-0000-4000-8000-000000000002';
+ const thread = '00000000-0000-4000-8000-000000000003';
+ const reading = vi.fn((_route: string) => false);
+ configureForegroundNotificationBehavior(reading);
+ const handler = mocks.setNotificationHandler.mock.calls.at(-1)![0];
+ const notification = { request: { content: { data: { deepLink: `/companions/groups/${room}?messageId=${message}&threadRootId=${thread}` } } } };
+ expect(await handler.handleNotification(notification)).toMatchObject({ shouldShowBanner: true });
+ expect(reading.mock.calls[0][0]).toContain(`threadRootId=${thread}`);
+ reading.mockReturnValue(true);
+ expect(await handler.handleNotification(notification)).toMatchObject({ shouldShowBanner: false, shouldPlaySound: false });
+ });
beforeEach(() => {
vi.clearAllMocks();
store.clear();
@@ -161,7 +177,8 @@ describe('push notification realm routing', () => {
expect(readStoredRealms(DEV_REGISTERED_KEY)).toEqual(['cn']);
expect(readStoredRealms(RELEASE_REGISTERED_KEY)).toEqual(['cn']);
- expect(apiFetch).toHaveBeenCalledTimes(2);
+ expect(apiFetch).toHaveBeenCalledTimes(4); // Each environment registers task and chat delivery.
+ expect(apiFetch.mock.calls.filter(([path]) => path === '/v1/push-token')).toHaveLength(2);
});
it('注册期间切换 CindyDev 环境仍把补偿状态留在原 namespace', async () => {
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index fed3a29ef1..5c2dfda23c 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -5,6 +5,8 @@ import { botGroupExecutionFailureBatches, projectBotGroupExecutionFailures } fro
import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';
// The app's `@/i18n` sets up this default instance; importing it here would pull React bindings into a plain client.
import i18next from 'i18next';
+import { mobileMarkdownPreviewText } from '@/session/messageMarkdown';
+import { botGroupQuoteFromMessage, buildBotGroupQuoteCard } from '@cindy/maker-shared/botGroupChat';
export interface ChatRoom {
id: string; name: string; state?: string; kind: string; archived: boolean; dissolved_at?: string | null;
@@ -18,16 +20,16 @@ export interface ChatMember {
}
export interface ChatMessage {
id: string; seq: string; authorId: string; author: { kind: string; name: string };
- createdAt: string; deleted: boolean; threadRootId: string | null; origin?: string;
+ createdAt: string; deleted: boolean; threadRootId: string | null; origin?: string; mentions?: string[];
content: Array<{ type: string; text?: string; fallback?: string; mediaId?: string; caption?: string;
namespace?: string; schemaRevision?: number; data?: Record<string, unknown> }>;
}
-export interface ChatSnapshot { room: ChatRoom; members: ChatMember[]; messages: ChatMessage[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string }> }
+export interface ChatSnapshot { room: ChatRoom; members: ChatMember[]; messages: ChatMessage[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; muted?: boolean; following?: boolean }> }
export interface ChatExecutionFailure {
id: string; conversation_id?: string; source_message_id: string; bot_id: string; epoch: number; status?: string;
failure_code?: unknown; updated_at?: string; plan_id?: string | null;
}
-export interface ChatPage { snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[] }
+export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[] }
/** `actorId` acts as one of the account's own actors (Chat Server `X-Chat-Actor`). */
export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string) => Promise<T>;
/** An actor the account owns; a companion's `externalId` is its bot id on every computer. */
@@ -86,11 +88,12 @@ export function chatRoomRow(room: ChatRoom, snapshot?: ChatSnapshot, selfId?: st
.sort((a, b) => BigInt(chatCursor(a.seq)) < BigInt(chatCursor(b.seq)) ? 1 : -1)[0];
return { key: `chat:${room.id}`, host: { deviceId: '', deviceName: '' },
lastReplySequence: snapshot && selfId ? chatLastReplySequence(snapshot.messages, selfId) : undefined,
+ chatUnread: snapshot?.reads && selfId ? chatUnread(snapshot, selfId) : undefined,
groupMembers: snapshot ? members.map(chatMemberIdentity) : undefined, item: {
ref: { collectionId: 'bot-groups', kind: 'bot-group', id: room.id },
revision: String(room.head ?? room.revision), display: { title: room.name,
subtitle: members.map(memberName).join(' · '),
- ...(snapshot ? { preview: last ? (botGroupMessageSummaryText({ content: contentText(last), task: taskCardOf(last) ?? undefined, deleted: last.deleted }) || mediaNames(last)).slice(0, 160) || members.map(memberName).join(' · ') : '' } : {}),
+ ...(snapshot ? { preview: last ? mobileMarkdownPreviewText(botGroupMessageSummaryText({ content: contentText(last), task: taskCardOf(last) ?? undefined, deleted: last.deleted }) || mediaNames(last)).slice(0, 160) || members.map(memberName).join(' · ') : '' } : {}),
timestamp: Date.parse(last?.createdAt ?? room.updated_at),
lastReplyAt: snapshot && selfId ? chatLastReplyAt(snapshot.messages, selfId) : undefined },
links: members.map(member => ({ rel: 'member', label: memberName(member),
@@ -98,6 +101,21 @@ export function chatRoomRow(room: ChatRoom, snapshot?: ChatSnapshot, selfId?: st
} };
}
+/** Server-owned read/mute positions include followed and mentioned threads. */
+function chatUnread(snapshot: ChatSnapshot, selfId: string): NonNullable<HostedRemoteCollectionItem['chatUnread']> {
+ const main = snapshot.reads?.find(read => read.thread_key === 'main');
+ if (main?.muted || snapshot.room.archived || snapshot.room.dissolved_at) return { count: 0, mentioned: false, threadCount: 0, threadMentioned: false };
+ const messages = snapshot.messages.filter(message => {
+ if (message.deleted || message.authorId === selfId || message.origin === 'system' || message.origin === 'import') return false;
+ const read = message.threadRootId ? snapshot.reads?.find(read => read.thread_key === message.threadRootId) : main;
+ return !read?.muted && BigInt(chatCursor(message.seq)) > BigInt(chatCursor(read?.read_seq ?? '0'))
+ && (!message.threadRootId || read?.following || message.mentions?.includes(selfId));
+ });
+ return { count: messages.length, mentioned: messages.some(message => message.mentions?.includes(selfId)),
+ threadCount: messages.filter(message => message.threadRootId).length,
+ threadMentioned: messages.some(message => message.threadRootId && message.mentions?.includes(selfId)) };
+}
+
/** Only incoming main-timeline messages count; a system notice or our own send is not a reply. */
const incomingReply = (message: ChatMessage, selfId: string) => !message.deleted && !message.threadRootId
&& message.origin !== 'system' && message.authorId !== selfId;
@@ -156,7 +174,7 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly C
const messages: BotGroupMessageView[] = sorted.map((message, index) => {
const runtimeFailureCode = readImportedBotGroupRuntimeFailureCode(message);
const legacy = runtimeFailureCode ? message.content.find(block => block.type === 'card' && block.namespace === 'cindy.local-history' && block.schemaRevision === 1)?.data : undefined;
- if (runtimeFailureCode) return { id: message.id, sequence: index + 1, kind: 'notice', authorKind: 'system',
+ if (runtimeFailureCode) return { id: message.id, sequence: index + 1, serverSequence: chatCursor(message.seq), kind: 'notice', authorKind: 'system',
authorBotId: message.authorId, authorName: typeof legacy?.authorName === 'string' ? legacy.authorName : '', isSelf: false,
content: '', mentions: { all: false, botIds: [] }, noticeCode: runtimeFailureCode === 'RUNTIME_TIMEOUT' ? 'member-timeout' : 'member-failed',
runtimeFailureCode, planId: null, files: [], attachments: [], createdAt: Date.parse(message.createdAt) };
@@ -165,12 +183,12 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly C
block.type === 'card' && block.namespace === 'cindy.membership' && block.schemaRevision === 1 && block.data?.type === 'member.joined');
const quote = message.origin === 'system' ? null : readBotGroupQuote(message.content);
const task = message.origin === 'system' ? null : taskCardOf(message);
- return { id: message.id, sequence: index + 1, kind: message.origin === 'system' ? 'notice' : 'message',
+ return { id: message.id, sequence: index + 1, serverSequence: chatCursor(message.seq), kind: message.origin === 'system' ? 'notice' : 'message',
...(task ? { task } : {}),
authorKind: message.origin === 'system' ? 'system' : message.author.kind === 'human' ? 'user' : 'bot',
authorBotId: message.authorId, authorName: joined && typeof joined.data?.displayName === 'string' ? joined.data.displayName
: member ? memberName(member) : message.author.name,
- isSelf: message.authorId === selfId, content: contentText(message), mentions: { all: false, botIds: [] },
+ isSelf: message.authorId === selfId, content: contentText(message), mentions: { all: false, botIds: message.mentions ?? [] },
...(quote ? { quote: deletedIds.has(quote.messageId) ? { ...quote, originalDeleted: true } : quote } : {}),
noticeCode: joined ? 'member-joined' : null, planId: null, files: [],
attachments: message.deleted ? [] : message.content.flatMap(block => {
@@ -190,12 +208,15 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly C
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),
- lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: botGroupMessageSummaryText(last).slice(0, 80), createdAt: last.createdAt } : null,
+ lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: mobileMarkdownPreviewText(botGroupMessageSummaryText(last)).slice(0, 80), createdAt: last.createdAt } : null,
speakingBotIds: [], planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),
hasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };
}
export function createChatServerClient(request: ChatRequest, personalList = createConversationListState()) {
+ // Preserve the posted quote through a lost response. Retrying an operation must
+ // not change its content/recipients if the original is subsequently edited or removed.
+ const postedQuotes = new Map<string, { content: ChatMessage['content']; mentions: string[] }>();
async function failures(roomId: string, messages: ChatMessage[]): Promise<ChatExecutionFailure[]> {
const sources = new Set(messages.map(message => chatId(message.id)));
let value: ChatExecutionFailure[] = [];
@@ -344,27 +365,32 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
if (!Array.isArray(members)) throw new Error('INVALID_CHAT_MEMBERS');
return members;
},
- async load(roomId: string, oldest?: string): Promise<ChatPage> {
+ async load(roomId: string, oldest?: string, threadRootId?: string): Promise<ChatPage> {
const room = chatId(roomId);
+ const threadQuery = threadRootId ? `&threadRootId=${chatId(threadRootId)}` : '';
const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);
if (snapshot.room.id !== room || !Array.isArray(snapshot.members)) throw new Error('INVALID_CHAT_SNAPSHOT');
chatCursor(snapshot.cursor);
// Snapshot includes Thread replies; the message endpoint selects the main timeline.
- let batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100`);
+ let batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100${threadQuery}`);
const messages = [...batch];
let before = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;
// Reauthorize and re-read the displayed window on invalidation, including edits/removals.
while (oldest && before && BigInt(before) > BigInt(chatCursor(oldest))) {
- batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100&before=${before}`);
+ batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100&before=${before}${threadQuery}`);
const next = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;
if (next && BigInt(next) >= BigInt(before)) throw new Error('INVALID_CHAT_PAGE');
messages.push(...batch); before = next;
}
- return { snapshot, messages, before, failures: await failures(room, messages) };
+ if (threadRootId) {
+ const root = await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);
+ messages.push(root);
+ }
+ return { snapshot, messages, before, ...(threadRootId ? { threadRootId } : {}), failures: await failures(room, messages) };
},
async older(roomId: string, page: ChatPage): Promise<ChatPage> {
if (!page.before) return page;
- const messages = await request<ChatMessage[]>(`/conversations/${chatId(roomId)}/messages?limit=100&before=${chatCursor(page.before)}`);
+ const messages = await request<ChatMessage[]>(`/conversations/${chatId(roomId)}/messages?limit=100&before=${chatCursor(page.before)}${page.threadRootId ? `&threadRootId=${chatId(page.threadRootId)}` : ''}`);
const loaded = [...page.messages, ...messages];
return { ...page, messages: loaded, failures: await failures(roomId, loaded),
before: messages.length === 100 ? chatCursor(messages.at(-1)!.seq) : null };
@@ -376,9 +402,57 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
return { id: mediaId, name: media.name, mimeType: media.type, size, category: media.type.startsWith('image/') ? 'image' : 'file',
url: chatHttpsUrl(media.url), path: null };
},
- async send(roomId: string, input: { clientId: string; text: string; mentions: { all: boolean; botIds: string[] } }) {
- return request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
- content: [{ type: 'text', text: input.text }], mentions: input.mentions.botIds.map(chatId) });
+ async markRead(roomId: string, page: ChatPage, messageIds: readonly string[]) {
+ // Old servers omit reads. Never infer a read position from a presentation index.
+ if (!page.snapshot.reads) return;
+ const seen = new Set(messageIds);
+ const key = page.threadRootId ?? 'main';
+ const before = page.snapshot.reads.find(read => read.thread_key === key)?.read_seq ?? '0';
+ const newest = page.messages.reduce((latest, message) => seen.has(message.id) && (message.threadRootId ?? undefined) === page.threadRootId
+ && BigInt(chatCursor(message.seq)) > BigInt(latest) ? message.seq : latest, before);
+ if (BigInt(newest) <= BigInt(before)) return;
+ const saved = await request<{ readSeq: string }>(`/conversations/${chatId(roomId)}/read`, 'POST', {
+ operationId: `read-${key}:${newest}`, readSeq: newest, ...(page.threadRootId ? { threadRootId: page.threadRootId } : {}),
+ });
+ const readSeq = chatCursor(saved.readSeq);
+ const current = page.snapshot.reads.find(read => read.thread_key === key);
+ if (current) { if (BigInt(readSeq) > BigInt(current.read_seq)) current.read_seq = readSeq; }
+ else page.snapshot.reads.push({ thread_key: key, read_seq: readSeq });
+ },
+ async send(roomId: string, input: { clientId: string; text: string; mentions: { all: boolean; botIds: string[] }; quote?: { messageId: string }; threadRootId?: string }) {
+ const key = JSON.stringify([roomId, input.clientId, input.text, input.mentions, input.quote?.messageId, input.threadRootId]);
+ const known = input.quote ? postedQuotes.get(key) : undefined;
+ const content: ChatMessage['content'] = known?.content ?? [{ type: 'text', text: input.text }];
+ const mentions = new Set(known?.mentions ?? input.mentions.botIds.map(chatId));
+ if (input.quote && !known) {
+ const [original, members] = await Promise.all([
+ request<ChatMessage>(`/conversations/${chatId(roomId)}/messages/${chatId(input.quote.messageId)}`),
+ request<ChatMember[]>(`/conversations/${chatId(roomId)}/members`),
+ ]);
+ if (original.deleted || (original.threadRootId && original.threadRootId !== input.threadRootId) || original.origin === 'system') throw new Error('QUOTE_UNAVAILABLE');
+ const member = members.find(member => member.id === original.authorId);
+ const quote = botGroupQuoteFromMessage({ id: original.id, sequence: Number(original.seq), authorKind: original.author.kind === 'human' ? 'user' : 'bot',
+ authorName: member ? memberName(member) : original.author.name, content: contentText(original), task: taskCardOf(original) ?? undefined,
+ attachments: original.content.filter(block => block.type === 'media').map(block => ({ name: attachmentName(block) })) });
+ // Quote positions are only an optional UI hint; never round a server cursor into it.
+ if (!Number.isSafeInteger(quote.sequence)) quote.sequence = null;
+ content.unshift(buildBotGroupQuoteCard(quote));
+ if (member?.kind === 'bot' && member.state === 'joined') mentions.add(chatId(member.id));
+ }
+ if (input.quote) {
+ postedQuotes.set(key, { content, mentions: [...mentions] });
+ if (postedQuotes.size > 128) postedQuotes.delete(postedQuotes.keys().next().value!);
+ }
+ try {
+ const result = await request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
+ content, mentions: [...mentions], ...(input.threadRootId ? { threadRootId: chatId(input.threadRootId) } : {}) });
+ postedQuotes.delete(key);
+ return result;
+ } catch (error) {
+ const status = (error as { status?: number })?.status;
+ if (status && status >= 400 && status < 500 && status !== 408) postedQuotes.delete(key);
+ throw error;
+ }
},
};
}
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index c508131e08..0fa385f7bb 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -178,9 +178,9 @@ export function useChatServerRoster(enabled: boolean) {
}
/** Reads and sends use the account's Chat Server identity, never its computer identity. */
-export function useChatServerGroup(groupId: string, enabled: boolean) {
+export function useChatServerGroup(groupId: string, enabled: boolean, threadRootId?: string) {
const api = useChatClient();
- const identity = `${api.owner}:${groupId}`;
+ const identity = `${api.owner}:${groupId}:${threadRootId ?? 'main'}`;
const active = useRef(identity); active.current = identity;
const [state, setState] = useState<{ identity: string; value: BotGroupChatState; online: boolean; loadingOlder: boolean }>({ identity, value: { kind: 'loading' }, online: true, loadingOlder: false });
const page = useRef<{ identity: string; page: ChatPage; self: string; actors: ChatActor[] } | null>(null);
@@ -201,10 +201,10 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
try {
await api.client.syncListState(run.reasons.some(reason => ['focus', 'visible', 'connected'].includes(reason)));
const previous = page.current?.identity === identity ? page.current.page : null;
- const oldest = previous?.messages.reduce<string | undefined>((oldest, message) => !oldest || BigInt(message.seq) < BigInt(oldest) ? message.seq : oldest, undefined);
+ const oldest = previous?.messages.filter(message => !threadRootId || message.threadRootId === threadRootId).reduce<string | undefined>((oldest, message) => !oldest || BigInt(message.seq) < BigInt(oldest) ? message.seq : oldest, undefined);
// The account's actors say which computer runs each owned companion (live task cards);
// the group still reads when that list is unavailable.
- const [next, self, actors] = await Promise.all([api.client.load(groupId, oldest), api.client.me(), api.client.actors().catch((): ChatActor[] => [])]);
+ const [next, self, actors] = await Promise.all([api.client.load(groupId, oldest, threadRootId), api.client.me(), api.client.actors().catch((): ChatActor[] => [])]);
if (run.isStale() || !valid() || generation !== accessGeneration.current) return;
// Replace the reauthorized window; no stale history survives changed access.
if (api.client.personalList.hidden(groupId)) { loseAccess(); return; }
@@ -295,14 +295,18 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
if (mentions.botIds.some(id => !joined.some(member => member.id === id))) throw new Error('MENTION_UNAVAILABLE');
const recipients = mentions.all
? joined.map(member => member.id)
- : mentions.botIds;
- await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text),
+ : [...mentions.botIds];
+ const root = threadRootId ? latest.page.messages.find(message => message.id === threadRootId) : undefined;
+ if (root && joined.some(member => member.id === root.authorId && member.kind === 'bot')) recipients.push(root.authorId);
+ await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text), threadRootId,
+ ...(input.quote && typeof input.quote === 'object' && 'messageId' in input.quote
+ ? { quote: { messageId: String(input.quote.messageId) } } : {}),
mentions: { all: false, botIds: recipients.filter(id => id !== latest.self) } });
if (valid()) reload();
return { effects: [] };
} catch (error) {
// An unavailable mention is a draft correction, not a connectivity failure.
- if (error instanceof Error && error.message === 'MENTION_UNAVAILABLE') throw error;
+ if (error instanceof Error && ['MENTION_UNAVAILABLE', 'QUOTE_UNAVAILABLE'].includes(error.message)) throw error;
if (valid()) {
freshRead.current = false;
if (chatAccessLost(error)) loseAccess();
@@ -336,7 +340,13 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {
// Only the measured UI's messages are acknowledged, even if a newer read is settling.
const seen = new Set(messageIds);
const messages = latest.page.messages.filter(message => seen.has(message.id));
- await markRemoteResourceRead(api.userId, '', groupId, chatLastReplyAt(messages, latest.self), chatLastReplySequence(messages, latest.self));
+ if (!threadRootId) await markRemoteResourceRead(api.userId, '', groupId, chatLastReplyAt(messages, latest.self), chatLastReplySequence(messages, latest.self));
+ if (!api.current() || active.current !== identity) return;
+ try { await api.client.markRead(groupId, latest.page, messageIds); }
+ catch {
+ // The foreground recovery refresh retries from the measured viewport, never from the head.
+ if (api.current() && active.current === identity) freshRead.current = false;
+ }
}, [api, groupId, identity]);
const acceptListState = useCallback(async (value: unknown) => {
if (!api.current()) throw new Error('OWNER_CHANGED');
diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.ts
index 3bc11f7fa2..42012533c5 100644
--- a/apps/mobile/src/device-link/remoteResourceCache.ts
+++ b/apps/mobile/src/device-link/remoteResourceCache.ts
@@ -59,6 +59,11 @@ function normalize(raw: unknown): Snapshot {
avatarColor: typeof member.avatarColor === 'string' ? member.avatarColor.slice(0, 64) : '' }];
}) : undefined;
return [{ key: `chat:${item.ref.id}`, host: { deviceId: '', deviceName: '' }, item, groupMembers,
+ ...(row.chatUnread && Number.isInteger(row.chatUnread.count) && row.chatUnread.count >= 0
+ && typeof row.chatUnread.mentioned === 'boolean' && Number.isInteger(row.chatUnread.threadCount)
+ && row.chatUnread.threadCount >= 0 && row.chatUnread.threadCount <= row.chatUnread.count
+ && typeof row.chatUnread.threadMentioned === 'boolean'
+ ? { chatUnread: { count: Math.min(row.chatUnread.count, 999), mentioned: row.chatUnread.mentioned, threadCount: Math.min(row.chatUnread.threadCount, 999), threadMentioned: row.chatUnread.threadMentioned } } : {}),
...(validSequence(row.lastReplySequence) ? { lastReplySequence: row.lastReplySequence } : {}) }];
});
(out.chatRosters ??= {})[realm] = { items, ids: [...new Set(roster.ids.filter(id => typeof id === 'string' && id.length <= 160))].slice(-2000) };
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
index f943c4918b..bca0823651 100644
--- a/apps/mobile/src/device-link/remoteResources.ts
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -474,6 +474,7 @@ export interface HostedRemoteCollectionItem {
item: RemoteCollectionItem;
/** Local direct Chat Server projection; never changes the device-link wire display. */
lastReplySequence?: string;
+ chatUnread?: { count: number; mentioned: boolean; threadCount: number; threadMentioned: boolean };
/** Authorized server identities for direct group rows; display only, never cached as permissions. */
groupMembers?: readonly Pick<BotGroupMemberView, 'botId' | 'name' | 'avatar' | 'avatarUrl' | 'avatarColor'>[];
}
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index 4ed30b4fa4..5cd5c83111 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -60,6 +60,8 @@
"send": "Send"
},
"timeline": {
+ "newMessages_one": "{{count}} new message",
+ "newMessages_other": "{{count}} new messages",
"emptyTitle": "No messages in this group yet",
"emptyDescription": "Say something to get started and your teammates will join in. @ a teammate to have only them reply.",
"roundEnded": "Teammates are done",
@@ -80,7 +82,8 @@
"quote": {
"label": "Quoting {{name}}: {{summary}}",
"deleted": "Original message was deleted",
- "attachments": "{{name}} and others ({{total}} files)"
+ "attachments": "{{name}} and others ({{total}} files)",
+ "unavailable": "This message is no longer available."
},
"notice": {
"memberJoined": "{{name}} joined the group",
diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.json
index 00d76a9c35..309546070f 100644
--- a/apps/mobile/src/i18n/locales/en/settings.json
+++ b/apps/mobile/src/i18n/locales/en/settings.json
@@ -104,10 +104,16 @@
},
"notifications": {
"sectionTitle": "Notifications",
- "taskDone": "Task Completion Notifications",
- "taskDoneHint": "Get notified when a task on your computer finishes, fails, or needs your reply, with the latest response.",
- "permissionDenied": "Notifications are off. Allow them in iOS Settings → Notifications → {{appName}}.",
- "unregisterQueued": "Turned off. Unregistering will finish once you’re back online."
+ "taskDone": "Message and task notifications",
+ "taskDoneHint": "Get notified about chat messages and tasks that finish, fail, or need your reply.",
+ "permissionDenied": "Allow Cindy notifications in your system settings.",
+ "unregisterQueued": "Turned off. Unregistering will finish once you’re back online.",
+ "preview": "Show chat previews",
+ "background": "Keep chat connected in background",
+ "backgroundActive": "Receiving chat messages in background",
+ "backgroundStop": "Stop receiving",
+ "backgroundHint": "The background connection works without Google and shows an ongoing notification. You can stop it from that notification.",
+ "googleUnavailable": "Google push is unavailable. Enable the background chat connection to receive messages."
},
"about": {
"sectionTitle": "About This Phone",
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index 490d90eb82..4116aa8ef4 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -60,6 +60,8 @@
"send": "送信"
},
"timeline": {
+ "newMessages_one": "新着メッセージ {{count}} 件",
+ "newMessages_other": "新着メッセージ {{count}} 件",
"emptyTitle": "このグループにはまだメッセージがありません",
"emptyDescription": "話しかけると仲間たちが会話を続けます。@ で仲間を指名すると、その仲間だけが返信します。",
"roundEnded": "仲間たちの発言が終わりました",
@@ -80,7 +82,8 @@
"quote": {
"label": "{{name}} を引用:{{summary}}",
"deleted": "元のメッセージは削除されました",
- "attachments": "{{name}} など {{total}} 件"
+ "attachments": "{{name}} など {{total}} 件",
+ "unavailable": "このメッセージは見つかりません。"
},
"notice": {
"memberJoined": "{{name}}さんがグループに参加しました",
diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.json
index f62c0852ab..6709bb0b7d 100644
--- a/apps/mobile/src/i18n/locales/ja/settings.json
+++ b/apps/mobile/src/i18n/locales/ja/settings.json
@@ -104,10 +104,16 @@
},
"notifications": {
"sectionTitle": "通知",
- "taskDone": "タスク完了通知",
- "taskDoneHint": "パソコンのタスクが完了・失敗・返信待ちになると、最新の返信とともに通知します。",
- "permissionDenied": "通知がオフです。iOS の「設定 → 通知 → {{appName}}」で許可してください。",
- "unregisterQueued": "オフにしました。オンラインになると登録解除が完了します。"
+ "taskDone": "メッセージとタスクの通知",
+ "taskDoneHint": "チャットの新着や、タスクの完了・エラー・返信待ちを通知します。",
+ "permissionDenied": "システム設定で Cindy の通知を許可してください。",
+ "unregisterQueued": "オフにしました。オンラインになると登録解除が完了します。",
+ "preview": "チャット内容をプレビュー",
+ "background": "バックグラウンドで接続を維持",
+ "backgroundActive": "バックグラウンドでメッセージを受信中",
+ "backgroundStop": "受信を停止",
+ "backgroundHint": "Google を使わずに接続し、常駐通知を表示します。通知からいつでも停止できます。",
+ "googleUnavailable": "Google プッシュ通知を利用できません。バックグラウンド接続で受信できます。"
},
"about": {
"sectionTitle": "このスマートフォンについて",
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index 4724d1735a..60409e0034 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -60,6 +60,8 @@
"send": "보내기"
},
"timeline": {
+ "newMessages_one": "새 메시지 {{count}}개",
+ "newMessages_other": "새 메시지 {{count}}개",
"emptyTitle": "이 그룹에는 아직 메시지가 없습니다",
"emptyDescription": "한마디 하면 동료들이 이어서 대화합니다. @로 동료를 지정하면 그 동료만 답합니다.",
"roundEnded": "동료들이 말을 마쳤습니다",
@@ -80,7 +82,8 @@
"quote": {
"label": "{{name}} 인용: {{summary}}",
"deleted": "원본 메시지가 삭제되었습니다",
- "attachments": "{{name}} 등 {{total}}개"
+ "attachments": "{{name}} 등 {{total}}개",
+ "unavailable": "이 메시지를 찾을 수 없습니다."
},
"notice": {
"memberJoined": "{{name}} 님이 그룹에 참여했습니다",
diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.json
index 8bdf2cc9af..caeea3b032 100644
--- a/apps/mobile/src/i18n/locales/ko/settings.json
+++ b/apps/mobile/src/i18n/locales/ko/settings.json
@@ -104,10 +104,16 @@
},
"notifications": {
"sectionTitle": "알림",
- "taskDone": "작업 완료 알림",
- "taskDoneHint": "컴퓨터의 작업이 완료·실패하거나 회신이 필요하면 최신 응답과 함께 알려 드립니다.",
- "permissionDenied": "알림이 꺼져 있습니다. iOS 설정 → 알림 → {{appName}}에서 허용해 주세요.",
- "unregisterQueued": "껐습니다. 다시 온라인이 되면 등록 해제가 완료됩니다."
+ "taskDone": "메시지 및 작업 알림",
+ "taskDoneHint": "새 채팅 메시지와 작업 완료, 오류, 답변 대기를 알려줍니다.",
+ "permissionDenied": "시스템 설정에서 Cindy 알림을 허용해 주세요.",
+ "unregisterQueued": "껐습니다. 다시 온라인이 되면 등록 해제가 완료됩니다.",
+ "preview": "채팅 내용 미리 보기",
+ "background": "백그라운드 채팅 연결 유지",
+ "backgroundActive": "백그라운드에서 채팅 메시지 수신 중",
+ "backgroundStop": "수신 중지",
+ "backgroundHint": "Google 없이 연결하며 상시 알림이 표시됩니다. 알림에서 언제든 중지할 수 있습니다.",
+ "googleUnavailable": "Google 푸시를 사용할 수 없습니다. 백그라운드 채팅 연결로 메시지를 받을 수 있습니다."
},
"about": {
"sectionTitle": "이 휴대폰 정보",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index e28c5e40a4..5e00f11c36 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -60,6 +60,8 @@
"send": "发送"
},
"timeline": {
+ "newMessages_one": "{{count}} 条新消息",
+ "newMessages_other": "{{count}} 条新消息",
"emptyTitle": "群里还没有消息",
"emptyDescription": "说一句话开始,伙伴们会接着聊。@ 某位伙伴就只让它回答。",
"roundEnded": "伙伴们说完了",
@@ -80,7 +82,8 @@
"quote": {
"label": "引用 {{name}}:{{summary}}",
"deleted": "原消息已删除",
- "attachments": "{{name}} 等 {{total}} 个附件"
+ "attachments": "{{name}} 等 {{total}} 个附件",
+ "unavailable": "无法找到这条消息。"
},
"notice": {
"memberJoined": "{{name}}加入了群聊",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.json
index c7f7b2514d..593249d865 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json
@@ -104,10 +104,16 @@
},
"notifications": {
"sectionTitle": "通知",
- "taskDone": "任务完成通知",
- "taskDoneHint": "电脑上的任务完成、出错或等你回复时推送通知,并附上最新回复。",
- "permissionDenied": "通知权限未开启,请在 iOS「设置 → 通知 → {{appName}}」中允许。",
- "unregisterQueued": "已关闭,联网后自动完成注销。"
+ "taskDone": "消息与任务通知",
+ "taskDoneHint": "收到新消息,或任务完成、出错、等你回复时通知你。",
+ "permissionDenied": "通知权限未开启,请在系统设置中允许 Cindy 发送通知。",
+ "unregisterQueued": "已关闭,联网后自动完成注销。",
+ "preview": "显示消息内容预览",
+ "background": "在后台保持消息连接",
+ "backgroundActive": "正在后台接收消息",
+ "backgroundStop": "停止接收",
+ "backgroundHint": "后台连接不依赖 Google,会显示常驻通知;可随时在通知栏停止。",
+ "googleUnavailable": "Google 推送暂不可用。可开启后台消息连接接收消息。"
},
"about": {
"sectionTitle": "关于这台手机",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index 78aa706ad1..8a2bdcd473 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -60,6 +60,8 @@
"send": "傳送"
},
"timeline": {
+ "newMessages_one": "{{count}} 則新訊息",
+ "newMessages_other": "{{count}} 則新訊息",
"emptyTitle": "群聊裡還沒有訊息",
"emptyDescription": "說一句話開始,夥伴們會接著聊。@ 某位夥伴就只讓它回答。",
"roundEnded": "夥伴們說完了",
@@ -80,7 +82,8 @@
"quote": {
"label": "引用 {{name}}:{{summary}}",
"deleted": "原訊息已刪除",
- "attachments": "{{name}} 等 {{total}} 個附件"
+ "attachments": "{{name}} 等 {{total}} 個附件",
+ "unavailable": "無法找到這則訊息。"
},
"notice": {
"memberJoined": "{{name}}加入了群聊",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.json
index 401dee4098..76cb01db60 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json
@@ -104,10 +104,16 @@
},
"notifications": {
"sectionTitle": "通知",
- "taskDone": "任務完成通知",
- "taskDoneHint": "電腦上的任務完成、出錯或等你回覆時推送通知,並附上最新回覆。",
- "permissionDenied": "通知權限未開啟,請在 iOS「設定 → 通知 → {{appName}}」中允許。",
- "unregisterQueued": "已關閉,連網後自動完成註銷。"
+ "taskDone": "訊息與任務通知",
+ "taskDoneHint": "收到新訊息,或任務完成、出錯、等你回覆時通知你。",
+ "permissionDenied": "通知權限未開啟,請在系統設定中允許 Cindy 傳送通知。",
+ "unregisterQueued": "已關閉,連網後自動完成註銷。",
+ "preview": "顯示訊息內容預覽",
+ "background": "在背景保持訊息連線",
+ "backgroundActive": "正在背景接收訊息",
+ "backgroundStop": "停止接收",
+ "backgroundHint": "背景連線不依賴 Google,會顯示常駐通知;可隨時在通知欄停止。",
+ "googleUnavailable": "Google 推播暫時無法使用。可開啟背景訊息連線接收訊息。"
},
"about": {
"sectionTitle": "關於這臺手機",
diff --git a/apps/mobile/src/notifications/ChatBackgroundBridge.tsx b/apps/mobile/src/notifications/ChatBackgroundBridge.tsx
new file mode 100644
index 0000000000..bae5364099
--- /dev/null
+++ b/apps/mobile/src/notifications/ChatBackgroundBridge.tsx
@@ -0,0 +1,53 @@
+import { useEffect } from 'react';
+import { AppState } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { useChatClient } from '@/chat/useChatServer';
+import { ChatNotificationsNative as Native, readChatBackgroundEnabled, subscribeChatBackground } from './chatBackground';
+import { readPushEnabled, readPushPreviewEnabled, subscribePushPreferences } from './pushNotifications';
+
+/** The existing auth owner rotates tokens; Android receives only a current in-memory copy. */
+export function ChatBackgroundBridge() {
+ const api = useChatClient();
+ const { t } = useTranslation();
+ useEffect(() => {
+ const native = Native;
+ if (!native) return;
+ let cancelled = false;
+ let refreshing = false;
+ let requested = false;
+ const update = async () => {
+ if (cancelled) return;
+ if (refreshing) { requested = true; return; }
+ refreshing = true;
+ try {
+ if (!api.enabled) { await native.setIdentity(''); await native.stop(); return; }
+ const [enabled, preview] = await Promise.all([readPushEnabled(), readPushPreviewEnabled()]);
+ if (cancelled || !api.current()) return;
+ await native.setPreview(preview);
+ if (!enabled) { await native.setIdentity(''); await native.stop(); return; }
+ const actor = await api.client.me();
+ if (cancelled || !api.current()) return;
+ await native.setIdentity(actor);
+ if (!(await readChatBackgroundEnabled())) { await native.stop(); return; }
+ 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);
+ } catch { /* Foreground and the service's next token refresh retry transient failures. */ }
+ finally {
+ refreshing = false;
+ if (requested) { requested = false; void update(); }
+ }
+ };
+ const state = AppState.addEventListener('change', value => { if (value === 'active') void update(); });
+ const refresh = native.addListener('refreshRequested', () => { void update(); });
+ const prefs = subscribePushPreferences(signedOut => {
+ if (signedOut) { cancelled = true; void native.setIdentity(''); void native.stop(); }
+ else void update();
+ });
+ const background = subscribeChatBackground(() => { void update(); });
+ void update();
+ return () => { cancelled = true; state.remove(); refresh.remove(); prefs(); background(); void native.stop(); void native.setIdentity(''); };
+ }, [api, t]);
+ return null;
+}
diff --git a/apps/mobile/src/notifications/PushNotificationsBridge.tsx b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
index f5fae3891f..cb3a516169 100644
--- a/apps/mobile/src/notifications/PushNotificationsBridge.tsx
+++ b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
@@ -1,8 +1,9 @@
-import { useRouter } from 'expo-router';
+import { useGlobalSearchParams, usePathname, useRouter } from 'expo-router';
import { useCallback, useEffect, useRef } from 'react';
import { AppState } from 'react-native';
import { useAuth } from '@/auth/AuthContext';
import Notifications from './nativeNotifications';
+import { ChatBackgroundBridge } from './ChatBackgroundBridge';
import { notificationRecoveryRoute, parseNotificationResponseDeepLink } from './pushRegistrationModel';
import {
configureForegroundNotificationBehavior,
@@ -24,11 +25,15 @@ type NotificationResponse = Parameters<
* 1. 登录后按本机开关同步 token 注册(启动补偿:上次注册失败/换账号后自愈);
* 2. APNs token 轮换时重新上报;
* 3. 通知点击(前台/后台/冷启动)→ 解析 APNs / Expo 深链 → 路由到对应会话;
- * 4. 前台压掉系统横幅。
+ * 4. 只在前台正阅读对应群聊/话题时压掉横幅。
*/
export function PushNotificationsBridge() {
const auth = useAuth();
const router = useRouter();
+ const pathname = usePathname();
+ const { threadRootId } = useGlobalSearchParams<{ threadRootId?: string }>();
+ const visibleChat = useRef({ pathname, threadRootId });
+ visibleChat.current = { pathname, threadRootId };
const routerRef = useRef(router);
routerRef.current = router;
/** 冷启动点通知时 auth 可能未就绪,先存下待路由的深链。 */
@@ -46,7 +51,11 @@ export function PushNotificationsBridge() {
useEffect(() => {
if (!isPushSupported()) return;
- configureForegroundNotificationBehavior();
+ configureForegroundNotificationBehavior(route => {
+ const [path, query] = route.split('?');
+ const thread = new URLSearchParams(query).get('threadRootId') ?? undefined;
+ return visibleChat.current.pathname === path && visibleChat.current.threadRootId === thread;
+ });
}, []);
// 登录态就绪后同步注册状态(开关关闭 / 从未注册时是 no-op)
@@ -134,5 +143,5 @@ export function PushNotificationsBridge() {
flushPendingDeepLink();
}, [auth.initialized, auth.isAuthenticated, flushPendingDeepLink]);
- return null;
+ return <ChatBackgroundBridge />;
}
diff --git a/apps/mobile/src/notifications/chatBackground.ts b/apps/mobile/src/notifications/chatBackground.ts
new file mode 100644
index 0000000000..4567242b1b
--- /dev/null
+++ b/apps/mobile/src/notifications/chatBackground.ts
@@ -0,0 +1,18 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import Native from '../../modules/cindy-chat-notifications/src';
+const KEY = 'cindy.push.background';
+const listeners = new Set<() => void>();
+export function isChatBackgroundSupported() { return Native !== null; }
+export async function readChatBackgroundEnabled() {
+ return !!Native && (await AsyncStorage.getItem(KEY)) === '1' && !(await Native.isPaused());
+}
+export async function writeChatBackgroundEnabled(enabled: boolean) {
+ if (enabled) await Native?.resume();
+ else await Native?.stop();
+ await AsyncStorage.setItem(KEY, enabled ? '1' : '0');
+ for (const listener of listeners) listener();
+}
+export function subscribeChatBackground(listener: () => void) {
+ listeners.add(listener); return () => { listeners.delete(listener); };
+}
+export { Native as ChatNotificationsNative };
diff --git a/apps/mobile/src/notifications/nativeNotifications.android.ts b/apps/mobile/src/notifications/nativeNotifications.android.ts
index 0585a4d95e..c203a92455 100644
--- a/apps/mobile/src/notifications/nativeNotifications.android.ts
+++ b/apps/mobile/src/notifications/nativeNotifications.android.ts
@@ -1,47 +1,22 @@
-import { PermissionStatus } from 'expo-modules-core';
-
+import * as Notifications from 'expo-notifications';
import type { NativeNotificationsApi } from './nativeNotifications.types';
-/**
- * Android 的 expo-notifications 替身(Metro 平台扩展在 `platform === 'android'` 时
- * 顶掉 `nativeNotifications.ts`)。
- *
- * 为什么是替身而不是直接用真模块:见 `nativeNotifications.ts` 的说明——真模块在
- * import 期就要求原生模块存在,而 Android 推送从未实现(`isPushSupported()` 只放行
- * iOS),那颗原生模块只是把 Firebase Messaging / Installations / DataTransport 与消息
- * 权限带进包里。本文件让 Android bundle 完全不引用 expo-notifications。
- *
- * 因此这里的实现只需保证「被 import 不炸」:所有真实调用点都在 `isPushSupported()`
- * 之后,正常路径下一个都不会执行到。行为上取最保守语义(权限拒绝、订阅空实现、
- * 无历史通知),而 `getDevicePushTokenAsync` 直接抛——它没有任何合理的假值可返回,
- * 静默返回空串只会把坏数据发到 server 的注册表。
- *
- * 要给 Android 接推送时:实现应该落在本文件(接国内厂商通道或 FCM),而不是把
- * `isPushSupported()` 放开去用真模块——那会把整条 Google 链重新带回来。
- */
-
-const EMPTY_SUBSCRIPTION = { remove: () => {} };
-
-const DENIED: Awaited<
- ReturnType<NativeNotificationsApi['getPermissionsAsync']>
-> = {
- status: PermissionStatus.DENIED,
- expires: 'never',
- granted: false,
- canAskAgain: false,
-};
-
+// FCM and the independent background connection share the native message-ID store.
+async function prepareChannel() {
+ await Notifications.setNotificationChannelAsync('chat-messages', {
+ name: 'Cindy', importance: Notifications.AndroidImportance.HIGH,
+ lockscreenVisibility: Notifications.AndroidNotificationVisibility.PRIVATE,
+ });
+}
const nativeNotifications: NativeNotificationsApi = {
- setNotificationHandler: () => {},
- getPermissionsAsync: async () => DENIED,
- requestPermissionsAsync: async () => DENIED,
+ ...Notifications,
+ requestPermissionsAsync: async options => {
+ await prepareChannel();
+ return Notifications.requestPermissionsAsync(options);
+ },
getDevicePushTokenAsync: async () => {
- throw new Error('Push notifications are not supported on Android');
+ await prepareChannel();
+ return Notifications.getDevicePushTokenAsync();
},
- addPushTokenListener: () => EMPTY_SUBSCRIPTION,
- addNotificationResponseReceivedListener: () => EMPTY_SUBSCRIPTION,
- getLastNotificationResponseAsync: async () => null,
- clearLastNotificationResponseAsync: async () => {},
};
-
export default nativeNotifications;
diff --git a/apps/mobile/src/notifications/nativeNotifications.ts b/apps/mobile/src/notifications/nativeNotifications.ts
index 5d4240954b..aa2bb313b7 100644
--- a/apps/mobile/src/notifications/nativeNotifications.ts
+++ b/apps/mobile/src/notifications/nativeNotifications.ts
@@ -2,24 +2,7 @@ import * as Notifications from 'expo-notifications';
import type { NativeNotificationsApi } from './nativeNotifications.types';
-/**
- * expo-notifications 的接入点(iOS / Web / 单测走本文件;Android 由
- * `nativeNotifications.android.ts` 按 Metro 平台扩展顶掉)。
- *
- * 为什么要这层间接:expo-notifications 的 JS 入口在 **import 期**就
- * `requireNativeModule('ExpoNotificationsEmitter')`(见其
- * `build/NotificationsEmitterModule.native.js`),原生模块缺失即抛。而移动推送只实现了
- * iOS(APNs,见 `pushNotifications.ts` 的 `isPushSupported`),Android 从未走通:
- * 仓内没有 `google-services.json`,拿不到 FCM token,原生模块纯属搭载——却把
- * Firebase Messaging / Installations / DataTransport 与相关消息权限一整条链带进了包。
- *
- * 把 import 收进本模块后,Android bundle 里不会再出现 expo-notifications,
- * 该原生模块可以被安全剥离(是否剥离由出包侧决定,与本层解耦无关)。
- *
- * 与 `platform/appDistribution.ts` 的平台扩展方向相反(那里基础文件是兜底、
- * `.ios.ts` 才是原生):这里基础文件必须是真模块,才能让 iOS、Web 与 node 单测
- * (mock 'expo-notifications')都走真实接线,只有 Android 需要被顶掉。
- */
+/** SDK boundary; Android also prepares its notification channel. */
const nativeNotifications: NativeNotificationsApi = Notifications;
export default nativeNotifications;
diff --git a/apps/mobile/src/notifications/pushNotifications.ts b/apps/mobile/src/notifications/pushNotifications.ts
index 3ec6df2164..ca4d0af8bf 100644
--- a/apps/mobile/src/notifications/pushNotifications.ts
+++ b/apps/mobile/src/notifications/pushNotifications.ts
@@ -14,20 +14,9 @@ import {
type DevServerEnvironment,
} from '@/config/devServerEnvironment';
import Notifications from './nativeNotifications';
-import { buildPushTokenRegistrationBody } from './pushRegistrationModel';
-
-/**
- * 移动推送(任务完成通知)的 expo-notifications 接线层。
- *
- * - 开关持久化在本机(AsyncStorage),默认关闭;打开时才请求系统通知权限。
- * - 注册目标是 device-link server 的 PUT /push-token(Bearer 鉴权与 WS 同源);
- * 关闭开关 / 登出 / 换账号或区域时注销(DELETE,幂等)。
- * - 仅 iOS(APNs):Android 需 FCM / 国内厂商通道,二期接入(server 侧已预留
- * provider='fcm' 字段)。原生模块只在 iOS 存在,所有调用一律经
- * `./nativeNotifications`(Android 由平台扩展顶成空实现,原因见该文件)。
- * - App 在前台时压掉系统横幅(WS 活着,会话本来就在实时刷新)。
- */
+import { buildPushTokenRegistrationBody, parseNotificationResponseDeepLink } from './pushRegistrationModel';
+/** APNs / FCM registration, scoped to the current account realm and lifecycle. */
const PUSH_ENABLED_KEY = 'cindy.push.enabled';
/** 成功或可能成功注册过 token 的区域集合,避免把注销请求发到错误区域。 */
const PUSH_REGISTERED_KEY = 'cindy.push.registered';
@@ -201,6 +190,26 @@ function deviceLinkBaseForRealm(realm: ClientEndpointRegion): string {
return getMobileEndpointForRealm(realm, 'deviceLinkApiBaseUrl');
}
+function pushTargets(realm: ClientEndpointRegion) {
+ const targets = [{ baseUrl: deviceLinkBaseForRealm(realm), path: PUSH_TOKEN_PATH, optional: false }];
+ try {
+ const baseUrl = getMobileEndpointForRealm(realm, 'chatApiBaseUrl');
+ if (baseUrl) targets.push({ baseUrl, path: '/v1/push-token', optional: true });
+ } catch { /* Older endpoint snapshots do not advertise chat. */ }
+ return targets;
+}
+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')) } : {}) }); }
+ 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;
+ throw error;
+ }
+ }));
+ for (const result of results) if (result.status === 'rejected') throw result.reason;
+}
+
function pushDeleteBody(token: string | null): { token: string } | undefined {
return token ? { token } : undefined;
}
@@ -221,8 +230,9 @@ async function deletePushTokenWithAccessToken(
PUSH_UNREGISTER_TIMEOUT_MS,
);
try {
+ const results = await Promise.allSettled(pushTargets(realm).map(async target => {
const response = await fetch(
- deviceLinkBaseForRealm(realm) + PUSH_TOKEN_PATH,
+ target.baseUrl + target.path,
{
method: 'DELETE',
headers: {
@@ -235,18 +245,29 @@ async function deletePushTokenWithAccessToken(
signal: controller.signal,
},
);
- if (!response.ok) {
+ if (!response.ok && !(target.optional && [404,405].includes(response.status))) {
throw new Error(`unregister failed: ${response.status}`);
}
+ }));
+ for (const result of results) if (result.status === 'rejected') throw result.reason;
} finally {
clearTimeout(timer);
}
}
export function isPushSupported(): boolean {
- return Platform.OS === 'ios';
+ return Platform.OS === 'ios' || Platform.OS === 'android';
}
+const pushPreferenceListeners = new Set<(signedOut?: boolean) => void>();
+export function subscribePushPreferences(listener: (signedOut?: boolean) => void) {
+ pushPreferenceListeners.add(listener); return () => { pushPreferenceListeners.delete(listener); };
+}
+export async function readPushPreviewEnabled() { return (await AsyncStorage.getItem('cindy.push.preview')) !== '0'; }
+export async function writePushPreviewEnabled(enabled: boolean) {
+ await AsyncStorage.setItem('cindy.push.preview', enabled ? '1' : '0');
+ for (const listener of pushPreferenceListeners) listener();
+}
export async function readPushEnabled(): Promise<boolean> {
try {
return (await AsyncStorage.getItem(PUSH_ENABLED_KEY)) === '1';
@@ -257,20 +278,17 @@ export async function readPushEnabled(): Promise<boolean> {
export async function writePushEnabled(enabled: boolean): Promise<void> {
await AsyncStorage.setItem(PUSH_ENABLED_KEY, enabled ? '1' : '0');
+ for (const listener of pushPreferenceListeners) listener();
}
-/**
- * 前台通知行为:横幅/声音全部压掉(人在 App 里,会话流本来就在实时刷新;
- * 系统推送只服务后台/杀进程场景)。
- */
-export function configureForegroundNotificationBehavior(): void {
+/** Suppress a foreground banner only while its conversation and thread are visible. */
+export function configureForegroundNotificationBehavior(isReading: (path: string) => boolean = () => false): void {
Notifications.setNotificationHandler({
- handleNotification: async () => ({
- shouldShowBanner: false,
- shouldShowList: false,
- shouldPlaySound: false,
- shouldSetBadge: false,
- }),
+ handleNotification: async notification => {
+ const route = parseNotificationResponseDeepLink({ notification });
+ const show = !!route?.startsWith('/companions/groups/') && !isReading(route);
+ return { shouldShowBanner: show, shouldShowList: show, shouldPlaySound: show, shouldSetBadge: false };
+ },
});
}
@@ -279,6 +297,7 @@ export type PushSyncResult =
| 'unregistered'
| 'permission-denied'
| 'unsupported'
+ | 'local-only'
| 'skipped';
/** AuthContext.apiFetch 的最小形状(带 Bearer + 401 自动 refresh)。 */
@@ -302,7 +321,6 @@ async function syncPushRegistrationInternal(
if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
const realm = getActiveMobileSessionRealm();
const stateScope = capturePushStateScope(realm);
- const baseUrl = deviceLinkBaseForRealm(realm);
if (!opts.enabled) {
const registeredRealms = await readPushRealms(
@@ -314,11 +332,7 @@ async function syncPushRegistrationInternal(
const token = await getNativeDeviceTokenBestEffort();
if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
try {
- await opts.apiFetch(PUSH_TOKEN_PATH, {
- baseUrl,
- method: 'DELETE',
- ...(token ? { body: pushDeleteBody(token) } : {}),
- });
+ await mutatePushTokens(opts.apiFetch, realm, 'DELETE', pushDeleteBody(token));
} catch (error) {
await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm, stateScope).catch(
() => undefined,
@@ -338,12 +352,19 @@ async function syncPushRegistrationInternal(
}
if (permission.status !== 'granted') return 'permission-denied';
- const deviceToken = await Notifications.getDevicePushTokenAsync();
+ let deviceToken;
+ try { deviceToken = await Notifications.getDevicePushTokenAsync(); }
+ catch (error) {
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
+ if (Platform.OS === 'android') return 'local-only';
+ throw error;
+ }
if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
const body = buildPushTokenRegistrationBody({
token: typeof deviceToken.data === 'string' ? deviceToken.data : '',
region: AUTH_REGION,
isDevBuild: __DEV__,
+ platform: Platform.OS === 'android' ? 'android' : 'ios',
});
if (!body) return 'skipped';
@@ -355,11 +376,7 @@ async function syncPushRegistrationInternal(
return 'skipped';
}
try {
- await opts.apiFetch(PUSH_TOKEN_PATH, {
- baseUrl,
- method: 'PUT',
- body,
- });
+ await mutatePushTokens(opts.apiFetch, realm, 'PUT', { ...body, preview: await readPushPreviewEnabled() });
} catch (error) {
if (lifecycleGeneration !== pushLifecycleGeneration) {
await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm, stateScope).catch(
@@ -423,6 +440,7 @@ export function unregisterPushTokenBestEffort(
realm: ClientEndpointRegion = getActiveMobileSessionRealm(),
): Promise<void> {
pushLifecycleGeneration += 1;
+ for (const listener of pushPreferenceListeners) listener(true);
// 不进入 pushMutationTail:当前 tail 可能正在 apiFetch → terminal handler →
// clearLocalSession → 本函数。等待 tail 会形成自等待死锁。
return unregisterPushTokenBestEffortInternal(realm, accessToken);
@@ -446,11 +464,7 @@ async function retryPendingUnregisterInternal(
try {
const token = await getNativeDeviceTokenBestEffort();
- await apiFetch(PUSH_TOKEN_PATH, {
- baseUrl: deviceLinkBaseForRealm(realm),
- method: 'DELETE',
- ...(token ? { body: pushDeleteBody(token) } : {}),
- });
+ await mutatePushTokens(apiFetch, realm, 'DELETE', pushDeleteBody(token));
await removePushRealm(PUSH_PENDING_UNREGISTER_KEY, realm, stateScope);
await removePushRealm(PUSH_REGISTERED_KEY, realm, stateScope);
} catch {
diff --git a/apps/mobile/src/notifications/pushRegistrationModel.ts b/apps/mobile/src/notifications/pushRegistrationModel.ts
index 8c1dc9be18..e2011a90b3 100644
--- a/apps/mobile/src/notifications/pushRegistrationModel.ts
+++ b/apps/mobile/src/notifications/pushRegistrationModel.ts
@@ -19,10 +19,10 @@ export function resolvePushAppVariant(region: 'cn' | 'global' | 'dev'): PushAppV
export interface PushTokenRegistrationBody {
token: string;
- platform: 'ios';
- provider: 'apns';
+ platform: 'ios' | 'android';
+ provider: 'apns' | 'fcm';
appVariant: PushAppVariant;
- apnsEnv: 'prod' | 'sandbox';
+ apnsEnv?: 'prod' | 'sandbox';
}
/**
@@ -34,16 +34,17 @@ export function buildPushTokenRegistrationBody(opts: {
token: string;
region: 'cn' | 'global' | 'dev';
isDevBuild: boolean;
+ platform?: 'ios' | 'android';
}): PushTokenRegistrationBody | null {
const appVariant = resolvePushAppVariant(opts.region);
const token = opts.token.trim();
if (!token) return null;
return {
token,
- platform: 'ios',
- provider: 'apns',
+ platform: opts.platform ?? 'ios',
+ provider: opts.platform === 'android' ? 'fcm' : 'apns',
appVariant,
- apnsEnv: opts.isDevBuild ? 'sandbox' : 'prod',
+ ...(opts.platform === 'android' ? {} : { apnsEnv: opts.isDevBuild ? 'sandbox' as const : 'prod' as const }),
};
}
@@ -68,7 +69,7 @@ function decodedDeepLinkId(value: string): string | null {
/**
* 分工一步停下时的群聊提醒(bot-group-chat.md §8.3):`/companions/groups/<groupId>?deviceId=<id>`。
- * 形状逐项校验:群 id 必须是规范编码的单段路径,查询串只能有一个非空的 deviceId,不带片段;
+ * 云端群消息可不带电脑,但必须带规范消息 ID;旧分工通知继续接受 deviceId。
* 通过后按规范形式重建,绝不原样转发。
*/
function parseBotGroupDeepLink(deepLink: string): string | null {
@@ -79,10 +80,19 @@ function parseBotGroupDeepLink(deepLink: string): string | null {
if (!groupId || encodeURIComponent(groupId) !== encodedGroupId) return null;
const params = new URLSearchParams(query);
const keys = [...params.keys()];
- if (keys.length !== 1 || keys[0] !== 'deviceId') return null;
+ if (new Set(keys).size !== keys.length || keys.some(key => !['deviceId', 'messageId', 'threadRootId'].includes(key))) return null;
const deviceId = params.get('deviceId') ?? '';
- if (!deviceId || deviceId.length > MAX_DEEP_LINK_ID_CHARS || hasControlCharacter(deviceId)) return null;
- return `/companions/groups/${encodeURIComponent(groupId)}?deviceId=${encodeURIComponent(deviceId)}`;
+ const messageId = params.get('messageId');
+ const threadRootId = params.get('threadRootId');
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+ if ((!deviceId && (!messageId || !uuid.test(groupId))) || (params.has('deviceId') && !deviceId)
+ || deviceId.length > MAX_DEEP_LINK_ID_CHARS || hasControlCharacter(deviceId)
+ || (messageId !== null && !uuid.test(messageId)) || (threadRootId !== null && (!messageId || !uuid.test(threadRootId)))) return null;
+ const clean = new URLSearchParams();
+ if (deviceId) clean.set('deviceId', deviceId);
+ if (messageId) clean.set('messageId', messageId);
+ if (threadRootId) clean.set('threadRootId', threadRootId);
+ return `/companions/groups/${encodeURIComponent(groupId)}?${clean}`;
}
/**
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index 37f845679c..d3eb1d30ee 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -13,6 +13,7 @@ import {
Alert,
KeyboardAvoidingView,
Platform,
+ Pressable,
ScrollView,
StyleSheet,
View,
@@ -28,6 +29,9 @@ import {
BOT_GROUP_REMOTE_COLLECTION_ID,
isBotGroupRuntimeFailureCode,
resolveBotGroupQuote,
+ botGroupQuoteFromMessage,
+ isBotGroupMessageQuotable,
+ type BotGroupQuoteView,
type BotGroupAttachment,
type BotGroupMemberView,
type BotGroupQuoteDisplay,
@@ -39,6 +43,7 @@ import {
} from '@cindy/maker-shared/botGroupChat';
import {
botGroupComposerPlanState,
+ botGroupNewMessageCount,
botGroupMemberNames,
botGroupNoticeVariant,
botGroupPlanFollowUp,
@@ -51,6 +56,7 @@ import { useIsFocused } from 'expo-router';
import { AppState } from 'react-native';
import { useAuth } from '@/auth/AuthContext';
import { Text } from '@/components/AppText';
+import { ChatReplyIcon } from '@/components/ChatReplyIcon';
import { MainWindowActionButton, MainWindowEmptyState } from '@/components/MobilePrimitives';
import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';
import type { RemoteResourceHostTarget } from '@/device-link/remoteResources';
@@ -66,7 +72,7 @@ import {
} from './BotGroupAvatars';
import { CHAT_HEADER_BLUR_FADE_INSIDE, ChatIdentityHeader } from './ChatIdentityHeader';
import { SessionHeaderNativeBlur } from './SessionHeaderNativeControls';
-import { CompanionEntering } from './CompanionEntering';
+import { CompanionEntering, CompanionFadeIn } from './CompanionEntering';
import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';
import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
import { BotGroupTaskCard } from './BotGroupTaskCard';
@@ -108,17 +114,20 @@ const REPLY_AVATAR_GAP = 10;
/** One short line gets the compact bubble, as in the 1:1 chat. */
const COMPACT_BUBBLE_MAX_CHARS = 140;
-export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId: string; deviceName: string; groupId: string }) {
+export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, notificationResponse, threadRootId }: {
+ deviceId: string; deviceName: string; groupId: string; messageId?: string; notificationResponse?: string; threadRootId?: string;
+}) {
const { t, i18n } = useTranslation();
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const router = useRouter();
const { user, accountGeneration } = useAuth();
const host = useMemo<RemoteResourceHostTarget>(() => ({ deviceId, deviceName: deviceName || deviceId }), [deviceId, deviceName]);
- const chat = useBotGroupChat(host, groupId);
+ const chat = useBotGroupChat(host, groupId, threadRootId);
const identity = useBotGroupIdentities(deviceId);
const resolveMedia = useBotGroupRemoteMedia(deviceId);
const [settings, setSettings] = useState(false);
+ const [replyTo, setReplyTo] = useState<BotGroupQuoteView | null>(null);
const leaveAfterSettings = useRef(false);
const [continuing, setContinuing] = useState(false);
const [planPending, setPlanPending] = useState<PlanPending | null>(null);
@@ -128,15 +137,30 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
const floatingHeader = Platform.OS === 'ios';
const insets = useSafeAreaInsets();
const [headerHeight, setHeaderHeight] = useState(0);
- const stickToBottom = useRef(true);
+ const stickToBottom = useRef(!messageId);
+ const [jumpTarget, setJumpTarget] = useState(messageId ?? '');
+ const [highlightId, setHighlightId] = useState('');
+ const jumpAttempts = useRef(0);
+ const messagePositions = useRef(new Map<string, number>());
const group = chat.state.kind === 'ready' ? chat.state.group : null;
const focused = useIsFocused();
- const viewportOwner = `${user?.id ?? ''}:${accountGeneration}:${deviceId}:${groupId}`;
+ const viewportOwner = `${user?.id ?? ''}:${accountGeneration}:${deviceId}:${groupId}:${threadRootId ?? 'main'}`;
+ const [seen, setSeen] = useState<{ owner: string; sequence: string } | null>(null);
+ const latestSequence = group?.messages.reduce((latest, message) => {
+ const position = message.serverSequence ?? String(message.sequence);
+ return BigInt(position) > BigInt(latest) ? position : latest;
+ }, '0') ?? '0';
+ // Opening an older notification establishes an arrival boundary without marking
+ // the latest messages read. Later arrivals must still show the return-to-bottom hint.
+ useEffect(() => {
+ if (group) setSeen(previous => previous?.owner === viewportOwner ? previous : { owner: viewportOwner, sequence: latestSequence });
+ }, [group, viewportOwner, latestSequence]);
+ const newMessageCount = botGroupNewMessageCount(group?.messages ?? [], seen?.owner === viewportOwner ? seen.sequence : null, threadRootId);
const viewport = useRef({ owner: viewportOwner, group, measuredGroup: null as typeof group,
contentHeight: 0, viewportHeight: 0, offsetY: 0 });
if (viewport.current.owner !== viewportOwner) {
viewport.current = { owner: viewportOwner, group, measuredGroup: null, contentHeight: 0, viewportHeight: 0, offsetY: 0 };
- stickToBottom.current = true;
+ stickToBottom.current = !messageId;
} else if (viewport.current.group !== group) {
if (!viewport.current.group || !group) {
// Loading/error unmounts the ScrollView; its next instance starts unmeasured.
@@ -154,13 +178,15 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
if (measured.owner !== viewportOwner || measured.measuredGroup !== group
|| measured.viewportHeight <= 0 || measured.contentHeight <= 0
|| measured.contentHeight - measured.offsetY - measured.viewportHeight >= STICK_TO_BOTTOM_PX) return;
+ setSeen(previous => previous?.owner === viewportOwner && previous.sequence === latestSequence
+ ? previous : { owner: viewportOwner, sequence: latestSequence });
const incoming = group.messages.filter(message => message.kind === 'message' && message.isSelf !== true
&& (message.authorKind === 'bot' || (message.authorKind === 'user' && message.isSelf === false))
);
if (chat.server && chat.markRead) { void chat.markRead(incoming.map(message => message.id)); return; }
const at = incoming.reduce((latest, message) => Math.max(latest, message.createdAt), 0);
if (at > 0) void markRemoteResourceRead(user?.id ?? '', deviceId, groupId, at);
- }, [focused, group, user?.id, deviceId, groupId, viewportOwner, chat.server, chat.markRead]);
+ }, [focused, group, user?.id, deviceId, groupId, viewportOwner, latestSequence, chat.server, chat.markRead]);
useEffect(() => {
const frame = requestAnimationFrame(acknowledge);
const subscription = AppState.addEventListener('change', state => { if (state === 'active') acknowledge(); });
@@ -193,6 +219,39 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
const report = useCallback((error: unknown, fallbackKey: string) => {
Alert.alert(chat.online ? botGroupActionErrorText(t, error, fallbackKey) : t(offlineKey));
}, [chat.online, offlineKey, t]);
+ const locateMessage = useCallback((id: string) => {
+ stickToBottom.current = false;
+ jumpAttempts.current = 0;
+ setJumpTarget(id);
+ }, []);
+ useEffect(() => { if (messageId) locateMessage(messageId); }, [messageId, notificationResponse, locateMessage]);
+ const positionAtMessage = useCallback((id: string, y: number) => {
+ stickToBottom.current = false;
+ scrollRef.current?.scrollTo({ y: Math.max(0, y - (floatingHeader ? headerHeight : 0) - spacing.md), animated: false });
+ setHighlightId(id);
+ setJumpTarget('');
+ }, [floatingHeader, headerHeight]);
+ useEffect(() => {
+ if (!highlightId) return;
+ const timer = setTimeout(() => setHighlightId(''), 2000);
+ return () => clearTimeout(timer);
+ }, [highlightId]);
+ const loadForJump = useRef(false);
+ const [jumpPass, setJumpPass] = useState(0);
+ useEffect(() => {
+ if (!jumpTarget || !group || loadForJump.current) return;
+ if (group.messages.some(message => message.id === jumpTarget)) {
+ const y = messagePositions.current.get(jumpTarget);
+ if (y !== undefined) positionAtMessage(jumpTarget, y);
+ return;
+ }
+ if (!group.hasMoreBefore || !chat.loadOlder || jumpAttempts.current >= 5) {
+ Alert.alert(t('groupChat.quote.unavailable')); setJumpTarget(''); return;
+ }
+ loadForJump.current = true; jumpAttempts.current++;
+ void chat.loadOlder().catch(error => { report(error, 'groupChat.loadFailedTitle'); setJumpTarget(''); })
+ .finally(() => { loadForJump.current = false; setJumpPass(pass => pass + 1); });
+ }, [jumpTarget, group, chat.loadOlder, positionAtMessage, report, t, jumpPass]);
const hidePending = useRef(false);
const hideScope = useRef('');
@@ -263,15 +322,18 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
const send = async (input: BotGroupSendInput) => {
stickToBottom.current = true;
+ const quote = replyTo;
try {
await chat.act('send', {
text: input.text,
mentions: input.mentions,
clientId: input.clientId,
+ ...(quote ? { quote: { messageId: quote.messageId } } : {}),
...(input.division ? { division: true } : {}),
// Only a computer that declared `supportsAttachments` is offered any (see the composer).
...(input.attachments.length > 0 ? { attachments: input.attachments } : {}),
});
+ if (quote) setReplyTo(current => current?.messageId === quote.messageId ? null : current);
} catch (error) {
report(error, 'groupChat.composer.sendFailed');
throw error;
@@ -284,6 +346,8 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
+ if (stickToBottom.current) setSeen(previous => previous?.owner === viewportOwner && previous.sequence === latestSequence
+ ? previous : { owner: viewportOwner, sequence: latestSequence });
Object.assign(viewport.current, { measuredGroup: group, contentHeight: contentSize.height,
offsetY: contentOffset.y, viewportHeight: layoutMeasurement.height });
stickToBottom.current = contentSize.height - contentOffset.y - layoutMeasurement.height < STICK_TO_BOTTOM_PX;
@@ -300,11 +364,11 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
mark={<BotGroupDuoAvatar deviceId={deviceId} members={headerMembers} online={chat.online} variant="header"
working={group?.round.status === 'running'} />}
title={title}
- subtitle={memberLine}
+ subtitle={threadRootId ? t('message.renderer.reply') : memberLine}
identityLabel={[title, memberLine].filter(Boolean).join(', ')}
identityHint={t('groupChat.settings.open')}
controlsReady={!!group}
- onBack={leave}
+ onBack={threadRootId ? () => router.replace(`/companions/groups/${groupId}?messageId=${threadRootId}` as never) : leave}
onOpenSettings={() => setSettings(true)}
settingsLabel={t('groupChat.settings.open')} />;
@@ -348,6 +412,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
>
{floatingHeader ? null : offlineNote}
{group.dissolvedAt ? <Text style={styles.offline}>{t('groupChat.lifecycle.dissolved')}</Text> : null}
+ <View style={styles.flex}>
<ScrollView ref={scrollRef} style={styles.flex} contentContainerStyle={[styles.timeline, floatingHeader && { paddingTop: headerHeight + spacing.md }]}
scrollIndicatorInsets={floatingHeader ? { top: headerHeight } : undefined} keyboardShouldPersistTaps="handled"
keyboardDismissMode="interactive"
@@ -362,6 +427,12 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
}}
testID="botGroup.timeline">
<BotGroupTimeline group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}
+ highlightId={highlightId} onLocateMessage={locateMessage}
+ onReply={(chat.server || group.serverBacked) && !group.archived && !group.dissolvedAt ? message => setReplyTo(botGroupQuoteFromMessage(message)) : undefined}
+ onMessageLayout={(id, y) => {
+ messagePositions.current.set(id, y);
+ if (jumpTarget === id) positionAtMessage(id, y);
+ }}
resolveMedia={resolveMedia} resolveServerMedia={chat.media}
loadOlder={chat.loadOlder ? () => { stickToBottom.current = false; void chat.loadOlder!().catch(error => report(error, 'groupChat.loadFailedTitle')); } : undefined}
loadingOlder={chat.loadingOlder} continuing={continuing} planPending={planPending}
@@ -370,7 +441,23 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId
onEditStep={(planId, step, action, botId) => void editPlanStep(planId, step, action, botId)}
onInteractionError={(message) => { if (message) Alert.alert(message); }} />
</ScrollView>
+ {newMessageCount > 0 ? <View style={styles.newMessages} accessibilityLiveRegion="polite">
+ <CompanionFadeIn play distance={spacing.xs}>
+ <MainWindowActionButton density="compact" style={styles.newMessagesButton} action={{
+ label: t('groupChat.timeline.newMessages', { count: newMessageCount }),
+ accessibilityLabel: t('message.renderer.newMessagesToBottom'),
+ testID: 'botGroup.newMessages',
+ onPress: () => { stickToBottom.current = true; scrollRef.current?.scrollToEnd({ animated: false }); },
+ }} />
+ </CompanionFadeIn>
+ </View> : null}
+ </View>
+ {replyTo ? <View style={styles.replyDraft}>
+ <View style={styles.flex}><BotGroupQuote display={resolveBotGroupQuote(replyTo, group.messages)} onPress={() => locateMessage(replyTo.messageId)} /></View>
+ <MainWindowActionButton density="compact" action={{ label: t('message.quote.remove'), onPress: () => setReplyTo(null), testID: 'botGroup.cancelReply' }} />
+ </View> : null}
<BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online && !group.archived && !group.dissolvedAt}
+ focusKey={replyTo?.messageId}
running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group), group.replyMode)}
divisionSupported={!chat.server && (!group.singleSpeaker || group.supportsDivision === true)} attachmentsSupported={group.supportsAttachments === true} onSend={send} onStop={stop} />
</KeyboardAvoidingView>;
@@ -407,6 +494,7 @@ function followUpPending(action: PlanPending['action'] | null): BotGroupFollowUp
export function BotGroupTimeline({
group, deviceId, online, identityFor, resolveMedia, resolveServerMedia, loadOlder, loadingOlder, continuing, planPending, onContinue, onPlanAction, onEditStep, onInteractionError,
+ onMessageLayout, onLocateMessage, highlightId, onReply,
}: {
group: BotGroupRemoteChatData;
deviceId: string;
@@ -423,6 +511,10 @@ export function BotGroupTimeline({
onPlanAction(action: BotGroupPlanAction, planId: string): void;
onEditStep(planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string): void;
onInteractionError(message: string | null): void;
+ onMessageLayout?: (id: string, y: number) => void;
+ onLocateMessage?: (id: string) => void;
+ highlightId?: string;
+ onReply?: (message: BotGroupMessageView) => void;
}) {
const { t, i18n } = useTranslation();
const styles = useThemedStyles(makeStyles);
@@ -450,11 +542,13 @@ export function BotGroupTimeline({
// G2: the same teammate speaking again inside one time group keeps its avatar and name once.
const continued = groupTime === undefined && message.kind === 'message' && message.authorKind === 'bot'
&& previous?.kind === 'message' && previous.authorKind === 'bot' && previous.authorBotId === message.authorBotId;
- return <View key={message.id} style={styles.item}>
+ return <View key={message.id} style={[styles.item, highlightId === message.id && styles.locatedMessage]}
+ onLayout={event => onMessageLayout?.(message.id, event.nativeEvent.layout.y)}>
{groupTime !== undefined ? <Text style={styles.time}>{formatBotMessageGroupTime(groupTime, i18n.language)}</Text> : null}
<CompanionEntering id={message.id} createdAt={message.createdAt} kind={message.authorKind === 'user' ? 'send' : 'reply'}>
<BotGroupTimelineItem message={message} continued={continued} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, messages) : undefined}
+ onLocateQuote={message.quote && onLocateMessage ? () => onLocateMessage(message.quote!.messageId) : undefined}
members={group.members} deviceId={deviceId} online={online} identityFor={identityFor} mentionLabels={mentionLabels}
resolveMedia={resolveMedia} resolveServerMedia={resolveServerMedia}
canContinue={message.id === continueId} continuing={continuing} onContinue={onContinue}
@@ -465,6 +559,12 @@ export function BotGroupTimeline({
onPlanAction={(action) => { if (message.planId) onPlanAction(action, message.planId); }}
onEditStep={(step, action, botId) => { if (message.planId) onEditStep(message.planId, step, action, botId); }} />
</CompanionEntering>
+ {onReply && isBotGroupMessageQuotable(message) ? <Pressable
+ accessibilityRole="button" accessibilityLabel={t('message.renderer.reply')}
+ testID={`botGroup.reply.${message.id}`} onPress={() => onReply(message)}
+ style={[styles.replyAction, message.isSelf === true && styles.ownReplyAction]}>
+ <ChatReplyIcon size={16} color={styles.replyIcon.color} />
+ </Pressable> : null}
</View>;
})}
{openPlan && followUp ? <View style={styles.indented}>
@@ -485,7 +585,7 @@ export function BotGroupTimeline({
}
function BotGroupTimelineItem({
- message, continued = false, quoteDisplay, member, members, deviceId, online, identityFor, mentionLabels, resolveMedia, resolveServerMedia, canContinue, continuing, onContinue,
+ message, continued = false, quoteDisplay, onLocateQuote, member, members, deviceId, online, identityFor, mentionLabels, resolveMedia, resolveServerMedia, canContinue, continuing, onContinue,
plan, planActionable, planReassignable, planPending, onPlanAction, onEditStep,
}: {
message: BotGroupMessageView;
@@ -493,6 +593,7 @@ function BotGroupTimelineItem({
continued?: boolean;
/** 引用回复: how the quoted message reads now. */
quoteDisplay?: BotGroupQuoteDisplay;
+ onLocateQuote?: () => void;
member: BotGroupMemberView | undefined;
members: readonly BotGroupMemberView[];
deviceId: string;
@@ -541,7 +642,7 @@ function BotGroupTimelineItem({
const compact = message.content.length <= COMPACT_BUBBLE_MAX_CHARS && !message.content.includes('\n');
return <View style={styles.userRow} testID="botGroup.message.user">
<View style={styles.userColumn}>
- {quoteDisplay ? <BotGroupQuote display={quoteDisplay} align="right" /> : null}
+ {quoteDisplay ? <BotGroupQuote display={quoteDisplay} align="right" onPress={onLocateQuote} /> : null}
{attachments.length > 0
? <BotGroupMessageAttachments messageId={message.id} attachments={attachments} align="right" onResolveRemoteMedia={resolveMedia} resolveServerMedia={resolveServerMedia} />
: null}
@@ -576,7 +677,7 @@ function BotGroupTimelineItem({
actionable={planActionable} reassignable={planReassignable} pending={planPending}
onStart={() => onPlanAction('start')} onDismiss={() => onPlanAction('dismiss')} onEditStep={onEditStep} />
: <>
- {quoteDisplay ? <BotGroupQuote display={quoteDisplay} /> : null}
+ {quoteDisplay ? <BotGroupQuote display={quoteDisplay} onPress={onLocateQuote} /> : null}
{/* A task this teammate started from the group; mine is live, another owner's is a snapshot.
An author no longer in the group is unknown: its task may run on another computer, so it
stays a snapshot rather than a lookup on this one (same rule as the desktop timeline).
@@ -596,6 +697,13 @@ function BotGroupTimelineItem({
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
screen: { flex: 1, backgroundColor: colors.surface },
flex: { flex: 1 },
+ newMessages: { position: 'absolute', bottom: spacing.md, alignSelf: 'center', maxWidth: '90%' },
+ newMessagesButton: { backgroundColor: colors.surfaceElevated },
+ locatedMessage: { backgroundColor: colors.surfaceElevated, borderRadius: radius.container },
+ replyDraft: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },
+ replyAction: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center', marginLeft: BOT_GROUP_MESSAGE_AVATAR_SIZE + REPLY_AVATAR_GAP },
+ ownReplyAction: { alignSelf: 'flex-end', marginLeft: 0 },
+ replyIcon: { color: colors.textSecondary },
floatingHeader: { position: 'absolute', top: 0, left: 0, right: 0, zIndex: 10 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.xl },
emptyActions: { flexDirection: 'row', justifyContent: 'center', gap: spacing.sm, marginTop: spacing.lg },
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index 725b604406..62ffc1e079 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -15,7 +15,7 @@
* 或等继续时不能再安排新的:小菜单时点「+」只说明原因,面板里这一行置灰并写明原因(同桌面)。
* 占位文字跟随未结束的安排。
*/
-import { useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert, Platform, Pressable, ScrollView, StyleSheet, View, type TextInput as NativeTextInput } from 'react-native';
import { randomUUID } from 'expo-crypto';
import { Camera, Folder, Image as ImageIcon, Plus, Square, Users, X } from 'lucide-react-native';
@@ -75,7 +75,7 @@ type MentionOption =
| { kind: 'member'; label: string; member: BotGroupMemberView };
export function BotGroupComposer({
- members, identityFor, deviceId, online, running, planState, attachmentsSupported, divisionSupported = true, onSend, onStop,
+ members, identityFor, deviceId, online, running, planState, attachmentsSupported, divisionSupported = true, focusKey, onSend, onStop,
}: {
members: readonly BotGroupMemberView[];
identityFor: BotGroupIdentityLookup;
@@ -86,6 +86,7 @@ export function BotGroupComposer({
/** The computer takes attachments on `send` (`BotGroupRemoteChatData.supportsAttachments`). */
attachmentsSupported: boolean;
divisionSupported?: boolean;
+ focusKey?: string;
/** Rejects with the host's error; the draft (and its tag) come back and the attachments stay. */
onSend(input: BotGroupSendInput): Promise<void>;
onStop(): Promise<void>;
@@ -104,6 +105,7 @@ export function BotGroupComposer({
const waitForLeaveDecision = useConfirmLeaveWhileUploading(waitingUploads);
const [stopping, setStopping] = useState(false);
const inputRef = useRef<NativeTextInput>(null);
+ useEffect(() => { if (focusKey) inputRef.current?.focus(); }, [focusKey]);
const textRef = useRef(text); textRef.current = text;
const selectionRef = useRef({ start: 0, end: 0 });
const sendingRef = useRef(false);
@@ -211,7 +213,7 @@ export function BotGroupComposer({
tracked: draftTracked,
});
// Targets, tag and attachments are part of the same send intent.
- const attempt = nextBotGroupSendAttempt(attemptRef.current, draftText, draftDivision, randomUUID, attachmentIds, mentions);
+ const attempt = nextBotGroupSendAttempt(attemptRef.current, draftText, draftDivision, randomUUID, attachmentIds, mentions, focusKey);
attemptRef.current = attempt;
release = tray.holdForSend(attachmentIds);
await onSend({ text: attempt.text, mentions, clientId: attempt.clientId, division: attempt.division, attachments });
diff --git a/apps/mobile/src/session/BotGroupList.tsx b/apps/mobile/src/session/BotGroupList.tsx
index e0a723e8ef..f8b9275198 100644
--- a/apps/mobile/src/session/BotGroupList.tsx
+++ b/apps/mobile/src/session/BotGroupList.tsx
@@ -30,7 +30,10 @@ export function BotGroupListRow({ row, online, last = false, onPress }: {
const { user } = useAuth();
useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);
const display = row.item.display;
- const unread = isRemoteResourceUnread(user?.id ?? '', row.host.deviceId, row.item.ref.id, display.lastReplyAt, row.lastReplySequence);
+ const mainUnread = isRemoteResourceUnread(user?.id ?? '', row.host.deviceId, row.item.ref.id, display.lastReplyAt, row.lastReplySequence);
+ const unreadCount = row.chatUnread ? mainUnread ? row.chatUnread.count : row.chatUnread.threadCount : undefined;
+ const unread = unreadCount !== undefined ? unreadCount > 0 : mainUnread;
+ const mentioned = row.chatUnread && (mainUnread ? row.chatUnread.mentioned : row.chatUnread.threadMentioned);
const title = resolveRemoteText(display.title, i18n.language);
const preview = display.preview ? parseMobileMarkdownInlines(resolveRemoteText(display.preview, i18n.language))
.map((inline) => inline.type === 'image' ? inline.alt : inline.text).join('').replace(/\s+/g, ' ').trim() : '';
@@ -53,6 +56,8 @@ export function BotGroupListRow({ row, online, last = false, onPress }: {
preview={offline ? `${offline} · ${summary}` : summary}
previewTone={offline ? 'tertiary' : 'secondary'}
unread={unread}
+ unreadCount={unreadCount}
+ mentioned={mentioned}
unreadLabel={t('devices.companions.unread')}
disabled={!online}
last={last}
diff --git a/apps/mobile/src/session/CompanionListRow.tsx b/apps/mobile/src/session/CompanionListRow.tsx
index 1d0406cb6c..1841d96b00 100644
--- a/apps/mobile/src/session/CompanionListRow.tsx
+++ b/apps/mobile/src/session/CompanionListRow.tsx
@@ -23,7 +23,7 @@ export type CompanionRowTrailing = { kind: 'time'; text: string } | { kind: 'wor
export function CompanionListRow({
avatar, title, device, trailing, preview, previewTone = 'secondary', previewPrefix, previewPrefixTestID,
- unread = false, unreadLabel, disabled = false, last = false, accessibilityLabel, onPress, testID,
+ unread = false, unreadCount, mentioned = false, unreadLabel, disabled = false, last = false, accessibilityLabel, onPress, testID,
}: {
/** Content of the 44pt avatar box (the caller draws presence dot and ring inside it). */
avatar: ReactNode;
@@ -38,6 +38,8 @@ export function CompanionListRow({
previewPrefix?: string;
previewPrefixTestID?: string;
unread?: boolean;
+ unreadCount?: number;
+ mentioned?: boolean;
unreadLabel?: string;
disabled?: boolean;
last?: boolean;
@@ -67,7 +69,11 @@ export function CompanionListRow({
{preview}
</Text>
: <View style={styles.previewSlot}>{preview}</View>}
- {unread ? <View style={styles.unread} accessibilityLabel={unreadLabel} testID="companion.row.unread" /> : null}
+ {unread ? unreadCount !== undefined
+ ? <Text style={styles.unreadCount} accessibilityLabel={unreadLabel} testID="companion.row.unread">
+ {`${mentioned ? '@ ' : ''}${unreadCount > 99 ? '99+' : unreadCount}`}
+ </Text>
+ : <View style={styles.unread} accessibilityLabel={unreadLabel} testID="companion.row.unread" /> : null}
</View>
</View>
</Pressable>;
@@ -101,6 +107,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
previewQuiet: { color: colors.textTertiary },
previewSlot: { flex: 1, minWidth: 0, flexDirection: 'row' },
prefix: { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.subtitle, fontWeight: fontWeight.medium },
+ unreadCount: { color: colors.botUnread, fontSize: typeScale.footnote, lineHeight: lineHeight.body, fontWeight: fontWeight.medium, fontVariant: ['tabular-nums'] },
unread: { width: COMPANION_ROW_DOT_SIZE, height: COMPANION_ROW_DOT_SIZE, borderRadius: radius.pill, backgroundColor: colors.botUnread },
presence: { position: 'absolute', right: 0, bottom: 0, padding: 2, borderRadius: radius.pill, backgroundColor: colors.surface },
});
diff --git a/apps/mobile/src/session/HomeUnreadContext.tsx b/apps/mobile/src/session/HomeUnreadContext.tsx
index 79aa798142..374238cdc1 100644
--- a/apps/mobile/src/session/HomeUnreadContext.tsx
+++ b/apps/mobile/src/session/HomeUnreadContext.tsx
@@ -48,7 +48,8 @@ function HomeUnreadContent({ children }: { children: ReactNode }) {
return count;
}, [sessions, homeStatusVersion, scheduleUnread]);
const teammates = [...roster.items, ...groups.items].filter(row =>
- isRemoteResourceUnread(user?.id ?? '', row.host.deviceId, row.item.ref.id, row.item.display.lastReplyAt, row.lastReplySequence)).length;
+ (row.chatUnread?.threadCount ?? 0) > 0 || ((row.chatUnread?.count ?? 1) > 0
+ && isRemoteResourceUnread(user?.id ?? '', row.host.deviceId, row.item.ref.id, row.item.display.lastReplyAt, row.lastReplySequence))).length;
return <ScheduleUnreadContext.Provider value={setScheduleUnread}><RosterContext.Provider value={{ roster, groups }}><CountsContext.Provider value={{ tasks, teammates }}>{children}</CountsContext.Provider></RosterContext.Provider></ScheduleUnreadContext.Provider>;
}
export const useHomeUnreadCounts = () => useContext(CountsContext);
diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.ts
index 70f3da679f..84da62974d 100644
--- a/apps/mobile/src/session/botGroupRemote.ts
+++ b/apps/mobile/src/session/botGroupRemote.ts
@@ -224,6 +224,7 @@ function parseMessage(value: unknown): BotGroupMessageView | null {
return {
id: messageId,
sequence,
+ ...(typeof record.serverSequence === 'string' && /^\d{1,30}$/.test(record.serverSequence) ? { serverSequence: record.serverSequence } : {}),
kind,
authorKind,
authorBotId: optionalId(record.authorBotId),
@@ -473,6 +474,7 @@ export interface BotGroupSendAttempt {
attachmentIds: readonly string[];
/** Explicit target identity, independent of the displayed names. */
mentionSignature?: string;
+ quoteMessageId?: string;
clientId: string;
}
@@ -487,13 +489,16 @@ export function nextBotGroupSendAttempt(
newClientId: () => string,
attachmentIds: readonly string[] = [],
mentions?: BotGroupMention,
+ quoteMessageId?: string,
): BotGroupSendAttempt {
const mentionSignature = mentions === undefined ? undefined : JSON.stringify([mentions.all, mentions.botIds]);
return previous && previous.text === text && previous.division === division
+ && previous.quoteMessageId === quoteMessageId
&& previous.mentionSignature === mentionSignature
&& previous.attachmentIds.length === attachmentIds.length
&& previous.attachmentIds.every((attachmentId, index) => attachmentId === attachmentIds[index])
? previous
: { text, division, attachmentIds: [...attachmentIds], clientId: newClientId(),
- ...(mentionSignature === undefined ? {} : { mentionSignature }) };
+ ...(mentionSignature === undefined ? {} : { mentionSignature }),
+ ...(quoteMessageId ? { quoteMessageId } : {}) };
}
diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.ts
index 96fd404f97..498fa35c41 100644
--- a/apps/mobile/src/session/messageMarkdown.ts
+++ b/apps/mobile/src/session/messageMarkdown.ts
@@ -11,7 +11,8 @@ import {
toWorkdirRel,
} from '@/session/chatPathCandidate';
import { DEEP_LINK_SCHEME_GROUP } from '@/session/sessionLinks';
-import { i18n } from '@/i18n';
+// App bootstrap initializes this instance; parsing summaries must not initialize React bindings.
+import i18n from 'i18next';
// 加粗 / 斜体 / 删除线里的内容会继续按行内语法解析(`**https://…**` 的链接照样可点,
// 与桌面 remark 同口径),结果拍平进同一层 inline 列表:里面的纯文本就是该强调类型本身,
@@ -67,6 +68,16 @@ export type MobileMarkdownBlock =
| { type: 'math'; key: string; srcLine?: number; text: string }
| { type: 'code'; key: string; srcLine?: number; language?: string; text: string };
+/** 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 => {
+ 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;
+ }).join(' ').replace(/\s+/gu, ' ').trim();
+}
+
export interface ParseMobileMarkdownOptions {
/**
* 给每个块附上源码起始行 srcLine(0-based)。供文件阅读器「渲染态定位到源码行」
diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.ts
index 0dc5b79b64..f3932fd393 100644
--- a/apps/mobile/src/session/useBotGroupChat.ts
+++ b/apps/mobile/src/session/useBotGroupChat.ts
@@ -28,8 +28,8 @@ const PUSH_COALESCE_MS = 150;
* re-reads the whole projection on it, never patches the timeline locally. Actions go
* through the same resource and are followed by a read.
*/
-export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string) {
- const server = useChatServerGroup(groupId, !host.deviceId);
+export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string, threadRootId?: string) {
+ const server = useChatServerGroup(groupId, !host.deviceId, threadRootId);
const { invoke, openLink, status, connectionEpoch, presenceVersion, getPresenceAvailability, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
const { accountGeneration } = useAuth();
const { i18n } = useTranslation();
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 26398db5e1..6c3979d796 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -334,7 +334,7 @@ SDK 规则随依赖一起进入应用的最终 R8 配置,不在应用侧重复
`plugins/with-communication-notifications.js` 为当前 bundle identity 生成
`CindyNotificationService` 扩展,启用 Communication Notifications,并向 EAS 登记扩展签名。
-扩展仅消费伙伴回复的可选 `sender` 数据;保留正文、深链和系统隐私设置,任何处理失败或
+扩展消费伙伴回复与群消息的可选 `sender` 数据;保留正文、深链和系统隐私设置,任何处理失败或
系统超时都回退原通知,且只交付一次。头像不发起网络请求、不读取用户账号存储。
Swift 源码和打包头像显式进入 fingerprint。首次发布需要原生新包和重新生成的签名配置;
服务端须先支持可选发送者透传和 `aps.mutable-content = 1`,未升级双方保持普通推送。
@@ -451,3 +451,21 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。
定向测试为对应的 `androidInstallController.test.ts` 与 `androidInstaller.test.ts`,构建配置
边界由 `src/__tests__/nativeAppConfig.test.ts` 验证。原生验证还应检查授权/拒绝返回、系统
安装取消、签名不匹配拒绝与同签名覆盖安装;不能把 JS 单测当作这些原生路径的实测。
+
+### 群消息通知与 Android 后台连接
+
+`CINDY_ANDROID_GOOGLE_SERVICES_FILE` 可指向仓库外的 `google-services.json`;未配置仍可构建,
+通知设置会说明 Google 推送不可用。服务端 Chat Server 和 device-link 分别配置同一 Firebase 项目的
+`FCM_PROJECT_ID` 与 ADC(例如仓库外 `GOOGLE_APPLICATION_CREDENTIALS`)。不要把密钥提交到仓库。
+
+`cindy-chat-notifications` 是 Android Expo 本地模块,复用 Expo 的 token、通知点击和冷启动响应;
+FCM data 消息与显式开启的前台服务都通过同一通知入口,按账号/消息去重。预览关闭时本机再次去除内容与
+发送者头像。群通知使用 MessagingStyle;伙伴回复有发送者时也使用 Person。普通任务仍沿用原通知。
+
+后台连接声明 `specialUse` 前台服务,持续显示运行通知和停止按钮;没有开机启动、隐藏重启或凭证落盘。
+发行到 Play 前须完成对应前台服务用途申报。Doze、厂商电池策略和强行停止可能中断连接;FCM 也需要 Google
+服务及有效项目配置,不能承诺所有设备强杀后送达。
+
+本次 Swift 扩展、Android 原生模块和头像资源都需要新原生包,不能只发 OTA;按冷更门由指定把关人明确
+批准。上线顺序为服务端兼容接口/通道配置、各端原生包,再验证 token 注册、前后台、拒绝权限、预览关闭、
+停止后台连接、断网重连、通知点击定位及人/伙伴头像。旧服务端没有 chat push API 时手机保留已有任务通知。
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 297a8721cc..e4fbfcbe5c 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -625,11 +625,12 @@ Dash 提出:群聊需要有别于原「回复」的引用回复,原来的「
- **持久化**:服务器的 `replyToId` 只允许指向同一 Thread 内的消息(主时间线用它会被
`REPLY_THREAD_MISMATCH` 拒绝),所以主时间线的引用存为消息内容里的版本化卡片
`cindy.quote`(revision 1,见 `packages/maker-shared/src/botGroupQuote.ts`),与 `cindy.plan`
- 等同一扩展机制,由 Chat Server 保存、同步。发送端只交原消息 ID,摘要由电脑在发送时按当前账号的
- 权限从服务器读取同群原消息生成:别的群、权限外、Thread 内、系统事件或已删除的消息一律拒绝
+ 等同一扩展机制,由 Chat Server 保存、同步。界面只交原消息 ID,摘要由实际发送端(电脑或直连手机)
+ 在发送时按当前账号的权限从服务器读取同群原消息生成:别的群、权限外、其它 Thread、系统事件或已删除的消息一律拒绝
(`QUOTE_UNAVAILABLE`)。卡片读取时逐字段校验,不合规的块不算引用、按普通文本显示其 fallback。
-- **范围**:电脑端主时间线可发起与跳转;话题内暂不提供引用回复(服务器已支持 Thread 内 `replyToId`,
- 后续可补)。手机(经电脑与直连两条路径)显示引用块与删除降级,暂不提供发起与跳转。
+- **范围**:电脑端主时间线可发起与跳转;电脑话题面板暂不提供引用回复。手机经电脑与直连两条路径
+ 均可发起引用回复并定位原消息;直连话题通知打开对应话题,回复保持在该话题内。原消息不再可读时保留
+ 输入内容并提示失败,不把引用静默丢掉后发送。
- **旧端**:不认识卡片的旧电脑和旧手机直连显示 fallback(`> 作者: 摘要`)后接正文;经电脑查看的旧手机
只显示正文、没有引用块。回归见 `botGroupQuote.test.ts`、`chatServer.test.ts`(引用回复)、
`BotGroupChatView.test.tsx`(引用回复)、`chatServerClient.test.ts` 与 `BotGroupChatScreen.test.tsx`。
@@ -752,7 +753,7 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;
- **关注开关**:话题面板右上角「关注」,默认关;打开后显示「已关注」,这个话题的新回复会进群聊右下角的提示。
在话题里回复、被 @ 都不会自动关注(Chris:「以免回了一个就关注了,一直通知」),服务端同时去掉了自动关注并清空历史自动关注
(cindy-server#1003)。关注状态存在服务器(`POST /conversations/:id/read` 的 `following`,重述原已读位置,不改变已读),
- 多台电脑一致;服务器不保存已读状态时不显示开关。群聊目前没有系统通知(桌面弹窗、手机推送),关注暂不触发系统通知,另行决定。
+ 多台电脑一致;服务器不保存已读状态时不显示开关。系统通知沿用关注与静音状态,见下节。
- **面板里的「新回复」分隔线**:打开时记下原来的已读位置,在它之后第一条别人的回复前画一条带蓝点的「新回复」分隔线;
新回复就是从第一条开始时不画。分隔线在面板开着期间不随已读移动。
- **同时发到主聊天**:话题输入框有「同时发到群聊」,默认不选、每次发送后恢复默认、切换话题不继承。先发话题回复,成功后再贴回主聊天;
@@ -791,3 +792,21 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;
实现:`maker-ipc/chatServerThreads.ts`、`chatServer.ts`(`decorateThreads`、`shareToMain`)、`renderer/features/bots/BotGroupThreadViews.tsx`、
`ChatThreadPanel.tsx`。回归:`chatServerThreads.test.ts`、`chatServer.test.ts`(thread previews and main-chat shares)、
`BotGroupChatView.test.tsx`(thread previews and posting to the main chat)、`maker-shared` 的 `botGroupThreadShare.test.ts`。
+
+### 收到消息后的注意、定位与回应
+
+- 桌面运行时由 Chat Server 实时事件触发原生通知;手机由 Chat Server 直接发 APNs/FCM,不依赖电脑在线。
+ 桌面完全退出后没有常驻接收进程,不承诺继续弹窗。伙伴私聊的任务回复继续复用原有任务通知链。
+- 主时间线未读来自服务器精确序号,只计别人发来的可见消息;列表同时显示 @。最新快照窗口最多 100 条,
+ 计数为该窗口中的未读数。系统事件、已删除、导入与自己的消息不提醒。话题只提醒点名或主动关注的回复。
+- 只有前台实际读到底部才推进读位;阅读历史时保留位置,显示新消息按钮。按钮返回最新消息;打开通知
+ 按群与消息 ID 定位,话题消息进入对应话题。定位最多补读 5 页,找不到明确提示,不跳到相邻消息冒充成功。
+- 通知标题保留群名,正文为实际发送者名称和去除 Markdown/引用卡元数据的摘要。头像取当前成员头像/
+ 原身份头像;iOS 使用 Communication Notifications,Android 使用 MessagingStyle Person。
+ 桌面通过 Electron 原生 icon 提供头像,其显示受操作系统控制(macOS 横幅可能仍只用 App 图标)。
+- 静音、隐藏/归档、离群和服务端已读状态在发送时重新核对。手机可关闭内容预览;权限拒绝保持不可用提示。
+ 云推送延迟短暂合并读位,Android 云推送与本机后台通道按账号/消息 ID 去重。不同设备尚未读过的消息
+ 仍可能各自收到通知;服务端读位抑制后续发送,不声称撤回已送达其它设备的系统通知。
+- Android 可另行开启可见的后台连接,持续通知提供停止按钮;不依赖 Google 服务。它受系统休眠、厂商限制、
+ 用户强行停止和网络影响,不是强杀后保活。凭证仅在内存,由现有登录模块刷新;未授权通知时不启动。
+- 原生接线与服务端部署、FCM 项目配置和真机送达是独立交付项,构建通过不能代替收到通知的实测。
diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
index 6d6ce582d8..369b205c93 100644
--- a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
@@ -10,9 +10,29 @@ import {
projectBotGroupExecutionFailures,
botGroupExecutionFailureBatches,
chatGroupMembership,
+ botGroupNewMessageCount,
} from '../botGroupPresentation.js';
import { chatGroupTalkRouteKey, groupLaneOfRouteKey, isChatOnlyGroupLane, BOT_GROUP_RUNTIME_FAILURE_CODES, readBotGroupExecutionFailure, type BotGroupErrorCode, type BotGroupExecutionFailureView, type BotGroupMemberView, type BotGroupMessageView, type BotGroupNoticeCode, type BotGroupPlanView } from '../botGroupChat.js';
+// Unit: history browsing needs an actionable count; old-page loads and repeated pushes are not arrivals.
+it('counts only new messages from other people and companions below the observed tail', () => {
+ const message = { id: 'new', sequence: 11, kind: 'message', authorKind: 'bot' } as BotGroupMessageView;
+ const messages = [message, message, { ...message, id: 'human', isSelf: false, authorKind: 'user' as const },
+ { ...message, id: 'history', sequence: 2 }, { ...message, id: 'mine', isSelf: true },
+ { ...message, id: 'removed', deleted: true }, { ...message, id: 'thread', threadRootId: 'root' },
+ { ...message, id: 'system', authorKind: 'system' as const }];
+ expect(botGroupNewMessageCount(messages, null)).toBe(0);
+ expect(botGroupNewMessageCount(messages, 10)).toBe(2);
+ expect(botGroupNewMessageCount(messages, 11)).toBe(0);
+ expect(botGroupNewMessageCount(messages, 10, 'root')).toBe(1);
+ // Mobile presentation indices shift when history is prepended; server positions do not.
+ expect(botGroupNewMessageCount([
+ { ...message, id: 'history', sequence: 1, serverSequence: '9007199254740991' },
+ { ...message, id: 'read', sequence: 2, serverSequence: '9007199254740992' },
+ { ...message, id: 'arrival', sequence: 3, serverSequence: '9007199254740993' },
+ ], '9007199254740992')).toBe(1);
+});
+
describe('server group membership affordances', () => {
const self = { actorId: 'self', isSelf: true, isOwned: true, role: 'member' } as BotGroupMemberView;
const ownBot = { actorId: 'own-bot', actorKind: 'bot', isOwned: true, role: 'owner' } as BotGroupMemberView;
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 72e8c5833a..dc7abcf06a 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -156,6 +156,8 @@ export interface BotGroupMessageView {
reactions?: Array<{ emoji: string; count: number; me: boolean }>;
id: string;
sequence: number;
+ /** Stable decimal server position; presentation indices can change when history is loaded. */
+ serverSequence?: string;
kind: BotGroupMessageKind;
authorKind: BotGroupAuthorKind;
authorBotId: string | null;
@@ -445,6 +447,8 @@ export interface BotGroupRoundView {
export interface BotGroupSummary {
serverBacked?: boolean;
+ /** Authoritative unread window for this account, including followed thread replies. */
+ serverUnread?: { count: number; mentioned: boolean };
/** Explicit server capabilities; absent on old servers/hosts. */
supportsDissolve?: boolean;
/** Upgraded host forwards leave explicitly; absent on old compatibility hosts. */
@@ -794,6 +798,7 @@ export interface ChatInvitePreview {
reusable?: boolean;
}
export type ChatGroupAction =
+ | { type: 'read'; messageId: string }
| { 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 } }
diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.ts
index 14e061584c..f5abb1e34c 100644
--- a/packages/maker-shared/src/botGroupPresentation.ts
+++ b/packages/maker-shared/src/botGroupPresentation.ts
@@ -60,6 +60,19 @@ export function botGroupPreviewLine(text: string): string {
return text.replace(/\s+/g, ' ').trim();
}
+/** New arrivals below a reader's viewport, excluding history pages and repeat snapshots. */
+export function botGroupNewMessageCount(messages: readonly BotGroupMessageView[], seenThrough: number | string | null, threadRootId?: string): number {
+ if (seenThrough === null) return 0;
+ const incoming = new Set<string>();
+ for (const message of messages) {
+ if (BigInt(message.serverSequence ?? message.sequence) <= BigInt(seenThrough) || message.deleted || (message.threadRootId ?? undefined) !== threadRootId || message.isSelf === true
+ || (message.kind !== 'message' && message.kind !== 'plan')
+ || (message.authorKind !== 'bot' && message.isSelf !== false) || message.authorKind === 'system') continue;
+ incoming.add(message.id);
+ }
+ return incoming.size;
+}
+
/**
* The only round-end that may offer 「继续讨论」: the newest one, and only while
* the host says the round can be continued.