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。

fix(bots): 显示持久化入群系统提示 (#5585)

Chris Zhangf913fbb2c38a
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
index 335dff0b9a..0010b799d5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
@@ -169,6 +169,15 @@ describe('bot group remote resources', () => {
expect(botGroupRemotePreview(summary())).toMatchObject({ translations: { 'zh-CN': '阿布:写好了' } });
});
+ it('localizes join previews for every phone language without an author prefix', () => {
+ const preview = botGroupRemotePreview(summary({ openPlan: null, lastMessage: { authorKind: 'system',
+ authorName: 'Taylor', noticeCode: 'member-joined', preview: 'Fallback', createdAt: 50 } }));
+ expect(preview).toEqual({ fallback: 'Taylor joined the group', translations: {
+ 'zh-CN': 'Taylor加入了群聊', 'zh-TW': 'Taylor加入了群聊',
+ ja: 'Taylorさんがグループに参加しました', ko: 'Taylor 님이 그룹에 참여했습니다',
+ } });
+ });
+
it('sends the chat only to controllers that understand it, without host paths', async () => {
const rich = await remoteResourceRegistry.get(context, { client: client([BOT_GROUP_CHAT_PRIMITIVE]), ref: ref('g1') });
expect(rich.blocks?.[0]).toMatchObject({ primitive: BOT_GROUP_CHAT_PRIMITIVE });
@@ -184,6 +193,16 @@ describe('bot group remote resources', () => {
expect(plain.blocks?.[0]?.fallbackMarkdown).toContain('**阿布**: 写好了');
});
+ it.each(['member-joined', null] as const)('keeps system notices (%s) visible to old phones through the plain fallback', async noticeCode => {
+ const joined = { ...detail().messages[0]!, kind: 'notice' as const, authorKind: 'system' as const,
+ noticeCode, authorName: 'Taylor', content: 'Taylor joined the group' };
+ service.getGroup.mockResolvedValue({ ok: true, group: detail({ messages: [joined] }) });
+ const plain = await remoteResourceRegistry.get(context, { client: client(), ref: ref('g1') });
+ expect(plain.blocks?.[0]?.fallbackMarkdown).toBe('Taylor joined the group');
+ const rich = botGroupRemoteChatData(detail({ messages: [joined] }));
+ expect(rich.messages[0]).toMatchObject({ authorKind: 'system', noticeCode, authorName: 'Taylor' });
+ });
+
it('forwards actions to the group service and reports its error code when refused', async () => {
const send = await remoteResourceRegistry.invoke(context, {
client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId: 'send', resourceRef: ref('g1'),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
new file mode 100644
index 0000000000..07c1ce9919
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const fixture = vi.hoisted(() => ({ download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[] }));
+vi.mock('../../authManager.js', () => ({ getAccessToken: () => 'isolated-test-token', refresh: vi.fn(async () => true) }));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
+vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: vi.fn(async () => []), download: fixture.download }) }));
+vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('electron', () => ({ app: { get isPackaged() { return fixture.packaged; }, getPath: () => '/isolated' } }));
+vi.mock('node:fs', () => ({ existsSync: fixture.exists, readFileSync: () => fixture.config || '{"baseUrl":"https://example.com","token":"test"}' }));
+vi.mock('../botGroupChatService.js', () => ({ readPersistedReplyText: vi.fn() }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: {
+ select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve(fixture.profiles), { limit: async () => [{ id: 'existing-local-group' }] }) }) }),
+ insert: () => ({ values: () => ({ onConflictDoNothing: async () => undefined }) }),
+} }) }));
+vi.mock('node:http', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { request: (url: string, options: { method: string }, callback: (response: unknown) => void) => {
+ fixture.urls.push(String(url));
+ const req = Object.assign(new EventEmitter(), {
+ end: (data?: string) => {
+ void Promise.resolve().then(() => fixture.handle(new URL(url).pathname.slice(3) + new URL(url).search, options.method, data ? JSON.parse(data) : undefined))
+ .then(result => {
+ const response = Object.assign(new EventEmitter(), { statusCode: result?.status ?? 200 });
+ callback(response);
+ response.emit('data', Buffer.from(JSON.stringify(result?.body ?? {})));
+ response.emit('end');
+ }, error => req.emit('error', error));
+ },
+ destroy: (error: Error) => req.emit('error', error),
+ });
+ return req;
+ } };
+});
+vi.mock('node:https', async () => ({ request: (await import('node:http')).request }));
+vi.mock('ws', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { default: class extends EventEmitter {
+ static OPEN = 1; readyState = 0; send = vi.fn();
+ constructor(url: URL) { super(); fixture.wsUrls.push(String(url)); fixture.sockets.push(this as unknown as import('ws').WebSocket); }
+ close() { this.emit('close'); }
+ } };
+});
+import { withChatServer } from '../chatServer.js';
+import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';
+
+describe('Chat Server membership notices', () => {
+ const roomId = '10000000-0000-4000-8000-000000000001';
+ const memberId = '20000000-0000-4000-8000-000000000001';
+ const selfId = '30000000-0000-4000-8000-000000000001';
+ const joined = () => ({ id: '40000000-0000-4000-8000-000000000001', seq: '12', origin: 'system',
+ authorId: memberId, author: { kind: 'human', name: 'Current profile name' },
+ content: [{ type: 'card', namespace: 'cindy.membership', schemaRevision: 1,
+ fallback: 'Taylor joined the group', data: { type: 'member.joined', actorId: memberId, displayName: 'Taylor' } }],
+ threadRootId: null, deleted: false, createdAt: '2026-10-08T00:00:00Z' });
+ let messages: ReturnType<typeof joined>[];
+ let service: BotGroupChatService;
+ const dispatch = vi.fn();
+ const changed = vi.fn();
+ beforeEach(() => {
+ vi.useFakeTimers();
+ fixture.packaged = true; fixture.profiles = []; fixture.sockets = []; fixture.urls = [];
+ messages = [joined()];
+ fixture.handle.mockImplementation(route => {
+ if (route === '/me') return { body: { actor: { id: selfId } } };
+ if (route === '/conversations?limit=100') return { body: [{ id: roomId, state: 'joined' }] };
+ if (route === '/executions/claim') return { body: { execution: null } };
+ if (route.endsWith('/snapshot')) return { body: {
+ room: { id: roomId, name: 'Group', response_mode: 'all', speaking_mode: 'auto',
+ created_at: '2026-10-08T00:00:00Z', updated_at: '2026-10-08T00:00:00Z' },
+ members: [{ id: memberId, kind: 'human', name: 'Renamed after joining', state: 'left', ownerActorId: memberId, ownerName: '' }],
+ messages, cursor: '12',
+ } };
+ if (route.includes('/messages?')) return { body: messages };
+ return { body: [] };
+ });
+ service = withChatServer({ dispose: vi.fn(), listGroups: async () => ({ ok: true, groups: [] }) } as unknown as BotGroupChatService,
+ { dispatch, onChanged: changed } as unknown as BotGroupChatServiceDeps);
+ });
+ afterEach(() => { service.dispose(); vi.useRealTimers(); vi.clearAllMocks(); });
+
+ 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({
+ id: joined().id, sequence: 12, kind: 'notice', authorKind: 'system', noticeCode: 'member-joined',
+ authorName: 'Taylor', authorBotId: null, isSelf: false, threadRootId: null, planId: null,
+ })]);
+ expect(result.ok && result.group.lastMessage).toMatchObject({ authorKind: 'system', authorName: 'Taylor', noticeCode: 'member-joined' });
+ expect(result.ok && result.group.round.canContinue).toBe(false);
+ expect(result.ok && result.group.lastReplyAt).toBe(0);
+ });
+
+ it('preserves an incoming reply timestamp behind a later admission event', async () => {
+ const replyAt = '2026-10-07T23:59:00Z';
+ messages = [joined(), { ...joined(), id: '40000000-0000-4000-8000-000000000002',
+ seq: '11', origin: 'user', createdAt: replyAt }];
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group.lastReplyAt).toBe(Date.parse(replyAt));
+ });
+
+ it('keeps separate admissions for the same member after leaving and rejoining', async () => {
+ messages = [{ ...joined(), id: '40000000-0000-4000-8000-000000000002', seq: '20' }, joined()];
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group.messages.map(m => [m.sequence, m.authorName])).toEqual([[12, 'Taylor'], [20, 'Taylor']]);
+ });
+
+ it.each(['user', 'bot', 'integration', 'import'])('does not trust a membership card from %s', async origin => {
+ messages = [{ ...joined(), origin, authorId: memberId, author: { kind: 'human', name: 'Taylor' } }];
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group.messages[0]).toMatchObject({ kind: 'message', noticeCode: null, authorKind: 'user' });
+ });
+
+ it.each(['unknown-version', 'invalid-subject', 'unknown-event', 'deleted'])('uses the system fallback for %s', async change => {
+ const message = joined();
+ if (change === 'unknown-version') message.content[0]!.schemaRevision = 2;
+ if (change === 'invalid-subject') message.content[0]!.data.actorId = 'invalid';
+ if (change === 'unknown-event') message.content[0]!.data.type = 'member.left';
+ if (change === 'deleted') message.deleted = true;
+ messages = [message];
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group.messages[0]).toMatchObject({ kind: 'notice', authorKind: 'system', noticeCode: null });
+ });
+
+ it('re-reads the same persisted record after duplicate changes and reconnect without sending or dispatching', async () => {
+ await service.getGroup(roomId);
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets[0]!;
+ Object.defineProperty(socket, 'readyState', { value: 1 });
+ for (const event of [{ type: 'ready' }, { type: 'changes', scope: `conversation:${roomId}`, cursor: '12',
+ changes: [{ type: 'message.system.created', entityId: joined().id }] }]) {
+ socket.emit('message', JSON.stringify(event));
+ socket.emit('message', JSON.stringify(event));
+ const result = await service.getGroup(roomId);
+ expect(result.ok && result.group.messages.map(m => m.id)).toEqual([joined().id]);
+ }
+ expect(changed).toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(fixture.handle.mock.calls.some(([route, method]) => method === 'POST' && route.includes('/messages'))).toBe(false);
+ });
+
+ it('never continues a discussion from an admission event', async () => {
+ expect((await service.continueRound(roomId)).ok).toBe(false);
+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/continue'))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
index 3648dc67c9..7626d57217 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
@@ -96,6 +96,13 @@ const COPY = {
ja: '{name}:{text}',
ko: '{name}: {text}',
},
+ memberJoined: {
+ en: '{name} joined the group',
+ 'zh-CN': '{name}加入了群聊',
+ 'zh-TW': '{name}加入了群聊',
+ ja: '{name}さんがグループに参加しました',
+ ko: '{name} 님이 그룹에 참여했습니다',
+ },
} satisfies Record<string, Copy>;
function fill(template: string, vars: Record<string, string | number>): string {
@@ -128,6 +135,8 @@ export function botGroupRemotePreview(group: BotGroupSummary): RemoteLocalizedTe
}
const last = group.lastMessage;
if (!last) return undefined;
+ if (last.authorKind === 'system' && last.noticeCode === 'member-joined')
+ return localized(COPY.memberJoined, { name: last.authorName });
return last.authorKind === 'bot' && last.authorName
? localized(COPY.lastMessage, { name: last.authorName, text: last.preview })
: last.preview;
@@ -183,7 +192,9 @@ export function botGroupRemoteChatData(detail: BotGroupDetail): BotGroupRemoteCh
function fallbackMarkdown(detail: BotGroupDetail): string {
const lines = detail.messages
- .filter((message) => message.kind === 'message' && (message.content.trim() || message.attachments.length > 0))
+ .filter((message) => (message.kind === 'message' || (message.kind === 'notice' && message.authorKind === 'system' &&
+ (message.noticeCode === 'member-joined' || message.noticeCode === null))) &&
+ (message.content.trim() || message.attachments.length > 0))
.slice(-FALLBACK_MESSAGES)
.map((message) => {
// Older phones cannot show attachments; they still see what was attached.
@@ -192,6 +203,7 @@ function fallbackMarkdown(detail: BotGroupDetail): string {
const clipped = Array.from(text).length > FALLBACK_MESSAGE_CHARS
? `${Array.from(text).slice(0, FALLBACK_MESSAGE_CHARS - 1).join('')}…`
: text;
+ if (message.authorKind === 'system') return clipped;
return message.authorKind === 'user' ? `> ${clipped}` : `**${message.authorName}**: ${clipped}`;
});
return lines.length > 0 ? lines.join('\n\n') : detail.name;
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 671af56bd3..05b197893e 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -35,7 +35,7 @@ interface Member { id: string; kind: 'human' | 'bot' | 'integration'; name: stri
guestAccess: 'none' | 'chat' | 'tools'; accessRevision: number }
interface Message {
id: string; seq: string; authorId: string; replyCount?: number; reactions?: Array<{ emoji: string; count: number; me: boolean }>; author: { kind: string; name: string };
- content: Array<{ type: string; text?: string; fallback?: string; namespace?: string; data?: Record<string, unknown>; mediaId?: string; caption?: string }>;
+ content: Array<{ type: string; text?: string; fallback?: string; namespace?: string; schemaRevision?: number; data?: Record<string, unknown>; mediaId?: string; caption?: string }>;
origin?: string; createdAt: string; deleted: boolean; threadRootId: string | null;
}
interface Room {
@@ -390,6 +390,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
return profiles.find(p => p.id === actor?.externalId);
}
function messageView(m: Message, members: Member[]): BotGroupMessageView {
+ // Only the server-owned origin establishes a system event. A user-supplied
+ // card with the same namespace must remain an ordinary chat message.
+ if (m.origin === 'system') {
+ 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,
+ authorBotId: null, authorName: joined ? String(joined.data!.displayName) : '', content: bodyText(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) };
+ }
const member = members.find(member => member.id === m.authorId);
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;
@@ -440,6 +451,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// Sidebar refresh must not download every attachment in every group's history.
const messages = summaryOnly ? [] : (await messageViews(roomId, page, s.members)).sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
+ const lastView = last ? messageView(last, s.members) : null;
return { serverBacked: true, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
members: s.members.filter(m => m.state === 'joined').map(m => {
const p = localBot(m.id);
@@ -448,15 +460,15 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
isOwned: m.ownerActorId === selfId, guestAccess: m.guestAccess, accessRevision: m.accessRevision,
avatarUrl: m.avatar?.startsWith('https://') ? m.avatar : null,
name: memberName(m), avatar: p?.avatar ?? (m.avatar?.startsWith('https://') ? '' : m.avatar) ?? '', avatarColor: p?.avatarColor ?? 'violet', status: p?.status ?? 'active' };
- }), organizerBotId: s.room.organizer_id ? localBot(s.room.organizer_id)?.id ?? s.room.organizer_id : s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id ?? null, projectDir: workspace?.projectDir ?? null, lastMessage: last ? {
- isSelf: last.authorId === selfId, authorKind: last.author.kind === 'human' ? 'user' : 'bot', authorName: messageView(last, s.members).authorName,
- preview: bodyText(last).slice(0, 80), createdAt: Date.parse(last.createdAt),
+ }), organizerBotId: s.room.organizer_id ? localBot(s.room.organizer_id)?.id ?? s.room.organizer_id : s.members.find(m => m.kind === 'bot' && m.state === 'joined')?.id ?? null, projectDir: workspace?.projectDir ?? null, lastMessage: lastView ? {
+ isSelf: lastView.isSelf, authorKind: lastView.authorKind, authorName: lastView.authorName, noticeCode: lastView.noticeCode,
+ preview: lastView.content.slice(0, 80), createdAt: lastView.createdAt,
} : 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 } : null,
- lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.authorId !== selfId
+ lastReplyAt: s.messages.reduce((latest, m) => !m.deleted && m.origin !== 'system' && m.authorId !== selfId
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
messages, hasMoreBefore: page.length === (o.limit ?? 100), plans,
- round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id) || s.messages.some(m => !m.deleted && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping','needs_input'].includes(e.status)) } };
+ round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id) || s.messages.some(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping','needs_input'].includes(e.status)) } };
}
function planView(plan: ServerPlan, members: Member[], workspace: ReturnType<ReturnType<typeof chatServerWorkspaces>['read']>): BotGroupPlanView {
return { id: plan.id, status: plan.status, organizerBotId: localBot(plan.organizer_id)?.id ?? plan.organizer_id,
@@ -894,7 +906,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const room = await resolveGroup(id.parse(groupId));
const history = await api<Message[]>(`/conversations/${room}/messages?limit=100`);
const executions = await api<Execution[]>(`/conversations/${room}/executions`);
- const sourceId = executions.find(e => !e.plan_id)?.source_message_id ?? history.find(m => !m.deleted && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))?.id;
+ const sourceId = executions.find(e => !e.plan_id)?.source_message_id ?? history.find(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))?.id;
if (!sourceId) throw new Error('MESSAGE_NOT_FOUND');
await api(`/conversations/${room}/messages/${sourceId}/continue`, 'POST', { operationId: randomUUID() });
changed(room); return { ok: true as const };
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
index 9c65a096a8..b9e27e5a58 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx
@@ -21,6 +21,7 @@ import { BotGenerationLabel } from './BotGenerationLabel';
import { BotGroupDuoAvatar } from './BotGroupAvatars';
import { isBotGroupLaneSession } from './botGroupLane';
import {
+ botGroupNoticeKey,
botGroupPreviewLine,
botGroupSidebarPlanPreview,
isRunningBotGroupSidebarPreview,
@@ -74,6 +75,10 @@ export function BotGroupSidebarRow({
if (plan?.kind === 'waiting') return t('bots.groupChat.sidebar.planWaitingAnonymous');
const last = group.lastMessage;
if (!last) return t('bots.groupChat.sidebar.empty');
+ if (last.authorKind === 'system') {
+ const key = botGroupNoticeKey(last.noticeCode ?? null, false);
+ return key ? t(key, { name: last.authorName }) : botGroupPreviewLine(last.preview);
+ }
const text = botGroupPreviewLine(last.preview);
if (last.authorKind === 'user' && last.isSelf !== false) return t('bots.groupChat.sidebar.previewYou', { text });
if (last.authorName.trim()) {
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 90f8b0a673..8d72194ccd 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -427,6 +427,17 @@ describe('BotGroupChatView', () => {
expect(document.querySelector('[data-controlled-banner-chip]')).toBeNull();
});
+ it('renders a joined member as a localized system line without message actions', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [msg({ id: 'join', kind: 'notice',
+ authorKind: 'system', authorName: 'Taylor', authorBotId: null, noticeCode: 'member-joined', content: 'Fallback text' })] }) });
+ renderView();
+ const notice = await screen.findByText('bots.groupChat.notice.memberJoined:Taylor');
+ expect(notice.tagName).toBe('P');
+ expect(notice.closest('article')).toBeNull();
+ expect(screen.queryByText('Fallback text')).toBeNull();
+ expect(mocks.sendBotGroupMessage).not.toHaveBeenCalled();
+ });
+
it('renders user, teammate, notice and round-end rows with the header lockup', async () => {
renderView();
expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
index 6afe8c12d7..5ac012815b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
@@ -341,3 +341,11 @@ describe('BotsSidebar group chats', () => {
expect(mocks.sendNotification).not.toHaveBeenCalled();
});
});
+
+it('localizes the join preview without presenting its subject as a chat author', async () => {
+ mocks.groups = [group({ lastMessage: { authorKind: 'system', authorName: 'Taylor',
+ noticeCode: 'member-joined', preview: 'Fallback text', createdAt: 30 } })];
+ await renderSidebar();
+ expect(screen.getByText('bots.groupChat.notice.memberJoined:{"name":"Taylor"}')).toBeTruthy();
+ expect(screen.queryByText(/Fallback text/)).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
index d69b2b1ffa..2c94994af7 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botReadState.test.ts
@@ -132,6 +132,17 @@ describe('Bot read positions', () => {
expect(listener).toHaveBeenCalledTimes(1);
});
+ it('does not count a system admission as an incoming reply or hide a pending reply', () => {
+ setBotReadStateOwner('owner-1');
+ markBotRead(botGroupReadKey('g'), 100);
+ const lastMessage = { authorKind: 'system' as const, isSelf: false, authorName: 'Taylor',
+ noticeCode: 'member-joined' as const, preview: 'Taylor joined the group', createdAt: 300 };
+ expect(isBotGroupUnread({ id: 'g', lastMessage })).toBe(false);
+ expect(isBotGroupUnread({ id: 'g', lastReplyAt: 100, lastMessage })).toBe(false);
+ expect(isBotGroupUnread({ id: 'g', lastReplyAt: 200, lastMessage })).toBe(true);
+ expect(getBotLastReadAt(botGroupReadKey('g'))).toBe(100);
+ });
+
it('degrades to an empty map when the stored value is corrupt', () => {
setBotReadStateOwner('owner-1');
window.localStorage.setItem('cindy.bots.readState.v1.owner-1', 'not json');
diff --git a/apps/desktop/src/renderer/features/bots/botReadState.ts b/apps/desktop/src/renderer/features/bots/botReadState.ts
index b4a11e65f6..c524fe6539 100644
--- a/apps/desktop/src/renderer/features/bots/botReadState.ts
+++ b/apps/desktop/src/renderer/features/bots/botReadState.ts
@@ -152,7 +152,7 @@ function latestGroupReplyAt(group: GroupReadSummary): number {
// Older hosts may omit lastReplyAt; other humans count just like companions.
const last = group.lastMessage;
return Math.max(group.lastReplyAt ?? 0,
- last && (last.authorKind === 'bot' || last.isSelf === false) ? last.createdAt : 0);
+ last && last.authorKind !== 'system' && (last.authorKind === 'bot' || last.isSelf === false) ? last.createdAt : 0);
}
export function isBotGroupUnread(group: GroupReadSummary): boolean {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a862db804f..665f6d4734 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8469,6 +8469,7 @@
"planDoneGeneric": "Work split finished"
},
"notice": {
+ "memberJoined": "{{name}} joined the group",
"memberFailed": "{{name}} couldn’t reply this time",
"memberTimeout": "{{name}} took too long to reply and was skipped this time",
"memberUnavailable": "{{name}} is unavailable and didn’t speak this time",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d4fc064494..eb642d64c5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8454,6 +8454,7 @@
"planDoneGeneric": "役割分担が完了しました"
},
"notice": {
+ "memberJoined": "{{name}}さんがグループに参加しました",
"memberFailed": "{{name}} は今回返信できませんでした",
"memberTimeout": "{{name}} の返信に時間がかかりすぎたため、今回はスキップしました",
"memberUnavailable": "{{name}} は現在利用できないため、今回は発言しませんでした",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e751b9145e..a68af2b664 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8454,6 +8454,7 @@
"planDoneGeneric": "역할 분담을 마쳤습니다"
},
"notice": {
+ "memberJoined": "{{name}} 님이 그룹에 참여했습니다",
"memberFailed": "{{name}} 님이 이번에는 답하지 못했습니다",
"memberTimeout": "{{name}} 님의 답이 너무 늦어 이번에는 건너뛰었습니다",
"memberUnavailable": "{{name}} 님을 지금 사용할 수 없어 이번에는 발언하지 않았습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 55ed4b62a8..f409c00a36 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8454,6 +8454,7 @@
"planDoneGeneric": "分工做完了"
},
"notice": {
+ "memberJoined": "{{name}}加入了群聊",
"memberFailed": "{{name}}这次没能回复",
"memberTimeout": "{{name}}太久没有回复,这次先跳过",
"memberUnavailable": "{{name}}现在不可用,这次没有发言",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 09127ec1c4..d11d60adc1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8454,6 +8454,7 @@
"planDoneGeneric": "分工做完了"
},
"notice": {
+ "memberJoined": "{{name}}加入了群聊",
"memberFailed": "{{name}}這次沒能回覆",
"memberTimeout": "{{name}}太久沒有回覆,這次先跳過",
"memberUnavailable": "{{name}}現在無法使用,這次沒有發言",
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index c67e327605..53045fe936 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -324,6 +324,14 @@ describe('group timeline', () => {
expect(h.markRead).toHaveBeenLastCalledWith('owner', 'mac', 'g1', 7000);
});
+ it('renders the joined member as a localized system line without a chat bubble', async () => {
+ await render(group({ messages: [message('join', 1, { kind: 'notice', authorKind: 'system',
+ authorName: 'Taylor', authorBotId: null, noticeCode: 'member-joined', content: 'Fallback text' })] }));
+ expect(all('botGroup.notice').map(entry => entry.textContent)).toEqual(['groupChat.notice.memberJoined(name=Taylor)']);
+ expect(all('botGroup.message.user')).toHaveLength(0);
+ expect(all('botGroup.message.bot')).toHaveLength(0);
+ });
+
it('renders messages, notices, round ends and plan ends like the desktop timeline', async () => {
await render();
expect(byId('botGroup.message.user')?.textContent).toBe('@咪咪 帮我做官网');
diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.ts
index e4f1dc13a2..4f9de39dc2 100644
--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts
+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts
@@ -45,6 +45,16 @@ function chatData(overrides: Record<string, unknown> = {}) {
}
describe('parseBotGroupChatData', () => {
+ it('preserves a server join notice through the phone projection', () => {
+ const joined = { id: 'joined', sequence: 20, kind: 'notice', authorKind: 'system', authorBotId: null,
+ authorName: 'Taylor', content: 'Taylor joined the group', noticeCode: 'member-joined',
+ planId: null, createdAt: 20 };
+ const parsed = parseBotGroupChatData(chatData({ messages: [joined],
+ lastMessage: { authorKind: 'system', authorName: 'Taylor', preview: joined.content, noticeCode: joined.noticeCode, createdAt: 20 } }))!;
+ expect(parsed.messages[0]).toMatchObject(joined);
+ expect(parsed.lastMessage).toMatchObject({ authorKind: 'system', noticeCode: 'member-joined', authorName: 'Taylor' });
+ });
+
it('validates the host projection field by field and keeps host paths off the phone', () => {
const parsed = parseBotGroupChatData(chatData())!;
expect(parsed.messages.map((message) => message.id)).toEqual(['m1', 'm2', 'm4']);
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index 7444ffc9e8..5bcf89255e 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -78,6 +78,7 @@
"olderOnComputer": "Earlier messages are on your computer"
},
"notice": {
+ "memberJoined": "{{name}} joined the group",
"memberFailed": "{{name}} couldn’t reply this time",
"memberTimeout": "{{name}} took too long to reply and was skipped this time",
"memberUnavailable": "{{name}} is unavailable and didn’t speak this time",
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index cfd16f92a1..a4f3012b40 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -78,6 +78,7 @@
"olderOnComputer": "それより前のメッセージはパソコンで確認できます"
},
"notice": {
+ "memberJoined": "{{name}}さんがグループに参加しました",
"memberFailed": "{{name}} は今回返信できませんでした",
"memberTimeout": "{{name}} の返信に時間がかかりすぎたため、今回はスキップしました",
"memberUnavailable": "{{name}} は現在利用できないため、今回は発言しませんでした",
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index 67eca285ec..050549a8fe 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -78,6 +78,7 @@
"olderOnComputer": "이전 메시지는 컴퓨터에서 확인하세요"
},
"notice": {
+ "memberJoined": "{{name}} 님이 그룹에 참여했습니다",
"memberFailed": "{{name}} 님이 이번에는 답하지 못했습니다",
"memberTimeout": "{{name}} 님의 답이 너무 늦어 이번에는 건너뛰었습니다",
"memberUnavailable": "{{name}} 님을 지금 사용할 수 없어 이번에는 발언하지 않았습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index a343f2fa99..43f0642693 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -78,6 +78,7 @@
"olderOnComputer": "更早的消息请在电脑上查看"
},
"notice": {
+ "memberJoined": "{{name}}加入了群聊",
"memberFailed": "{{name}}这次没能回复",
"memberTimeout": "{{name}}太久没有回复,这次先跳过",
"memberUnavailable": "{{name}}现在不可用,这次没有发言",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index f5c6986697..d40d38a3ea 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -78,6 +78,7 @@
"olderOnComputer": "更早的訊息請在電腦上查看"
},
"notice": {
+ "memberJoined": "{{name}}加入了群聊",
"memberFailed": "{{name}}這次沒能回覆",
"memberTimeout": "{{name}}太久沒有回覆,這次先跳過",
"memberUnavailable": "{{name}}現在無法使用,這次沒有發言",
diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.ts
index 333c08fbac..31d5b5268b 100644
--- a/apps/mobile/src/session/botGroupRemote.ts
+++ b/apps/mobile/src/session/botGroupRemote.ts
@@ -99,7 +99,7 @@ const MEMBER_STATUSES = new Set<BotGroupMemberStatus>(['active', 'paused', 'erro
const MESSAGE_KINDS = new Set<BotGroupMessageView['kind']>(['message', 'round-end', 'notice', 'plan', 'plan-end']);
const AUTHOR_KINDS = new Set<BotGroupMessageView['authorKind']>(['user', 'bot', 'system']);
const NOTICE_CODES = new Set<string>([
- 'member-failed', 'member-timeout', 'member-unavailable', 'plan-failed', 'plan-stopped', 'workdir-unavailable',
+ 'member-joined', 'member-failed', 'member-timeout', 'member-unavailable', 'plan-failed', 'plan-stopped', 'workdir-unavailable',
]);
const PLAN_STATUSES = new Set<BotGroupPlanView['status']>([
'proposed', 'running', 'waiting', 'done', 'stopped', 'dismissed', 'superseded',
@@ -294,6 +294,8 @@ function parseLastMessage(value: unknown): BotGroupLastMessage | null {
authorKind,
authorName: text(record.authorName, MAX_NAME) ?? '',
preview: text(record.preview, 4_096) ?? '',
+ ...(typeof record.noticeCode === 'string' && NOTICE_CODES.has(record.noticeCode)
+ ? { noticeCode: record.noticeCode as BotGroupMessageView['noticeCode'] } : {}),
createdAt,
};
}
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index a6275924c6..3fcc36c723 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -84,3 +84,27 @@ XDT_CDP_PORT=9239 pnpm restart:desktop:remote --region=global -- --isolated=chat
## 服务器历史回拉(2026-10-03)
普通群默认共享既往历史,后来加入的人和伙伴均能读入群前消息与 Thread;每页 100 条是响应上限,不是保留上限。服务端回归覆盖 125 条历史跨页读取、旧 Thread、搜索和重连增量;持久库重启与覆盖恢复保护也已通过。实际将当前 24 张表迁入持久开发目录,逐表记录数/内容摘要一致,不带恢复参数重启后仍一致;两个真实账号 DEV 自动重连并能读取原群历史。生产负载和容灾仍未验收。
+
+## 入群系统提示的兼容接线
+
+Desktop 将服务端持久消息 `origin: "system"` 中的
+`card(namespace: "cindy.membership", schemaRevision: 1)`、
+`data: { type: "member.joined", actorId, displayName }` 映射为 `member-joined` 系统提示。
+只有服务端 origin 可信;用户、伙伴或导入内容里同名 card 仍是普通消息。
+使用入群时保存的显示名,不根据当前成员列表反推加入,也不因成员改名或退群改写历史。
+未知系统事件版本保留普通系统文本回退,不猜测事件含义。
+
+主消息流与侧栏摘要使用阅读者的界面语言(五种语言)。手机复用现有 Remote Resource
+投影,`noticeCode` 是新增可选摘要字段;旧手机忽略它,时间线可读消息 fallback,
+不支持群聊原语的旧手机保留 Markdown 回退。WebSocket 收到
+`message.system.created` 时沿现有群 scope 刷新并重新读取相同的持久消息 ID,
+客户端不插入临时消息或触发伙伴回复;“继续讨论”也不以入群事件作为来源。
+入群提示不算他人回复,不推动 `lastReplyAt` 或未读摘要回退;已有待读回复仍保留,读位不变。
+
+客户端可先发布,旧服务端不产生事件时保持现状。服务端对应修复负责真实加入事务、
+事件去重、历史可见下界与系统记录保护;只发布本客户端不会补出入群记录。
+建议先客户端后服务端,新服务端先发布时旧客户端仍可读取 card fallback,但会沿旧式
+作者气泡呈现,不等于已获得本地化系统样式。旧加入历史不从成员现状补造。
+
+本次客户端回归使用离线 HTTP/WebSocket fixture、桌面与手机组件测试;不代表安装版、
+线上服务或真实双账号已经验收。普通项目任务与伙伴私聊不经过本次群提示投影。
diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
index 9b0e0226b8..30091c6b78 100644
--- a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
@@ -20,6 +20,7 @@ const plan = (overrides: Partial<BotGroupPlanView> = {}): BotGroupPlanView => ({
describe('bot group copy variants (shared by desktop and phone)', () => {
it('speaks about a step for member notices inside a plan', () => {
+ expect(botGroupNoticeVariant('member-joined', false)).toBe('memberJoined');
expect(botGroupNoticeVariant('member-failed', false)).toBe('memberFailed');
expect(botGroupNoticeVariant('member-failed', true)).toBe('stepFailed');
expect(botGroupNoticeVariant('plan-stopped', true)).toBe('planStopped');
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index abf9bfcb68..82720ebfbb 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -29,6 +29,7 @@ export type BotGroupAuthorKind = 'user' | 'bot' | 'system';
*/
export type BotGroupMessageKind = 'message' | 'round-end' | 'notice' | 'plan' | 'plan-end';
export type BotGroupNoticeCode =
+ | 'member-joined'
| 'member-failed'
| 'member-timeout'
| 'member-unavailable'
@@ -180,6 +181,8 @@ export interface BotGroupLastMessage {
isSelf?: boolean;
authorKind: BotGroupAuthorKind;
authorName: string;
+ /** Optional for older hosts; localize system notices in the reader's language. */
+ noticeCode?: BotGroupNoticeCode | null;
preview: string;
createdAt: number;
}
diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.ts
index e0e6e71f23..9e57724fbe 100644
--- a/packages/maker-shared/src/botGroupPresentation.ts
+++ b/packages/maker-shared/src/botGroupPresentation.ts
@@ -165,6 +165,7 @@ export function isBotGroupDivisionBlocked(state: BotGroupComposerPlanState | nul
/** Copy variant for a timeline notice; plan-scoped member notices speak about a step. */
export type BotGroupNoticeVariant =
+ | 'memberJoined'
| 'memberFailed'
| 'memberTimeout'
| 'memberUnavailable'
@@ -176,6 +177,7 @@ export type BotGroupNoticeVariant =
| 'stepUnavailable';
const NOTICE_VARIANTS: ReadonlyMap<string, BotGroupNoticeVariant> = new Map<BotGroupNoticeCode, BotGroupNoticeVariant>([
+ ['member-joined', 'memberJoined'],
['member-failed', 'memberFailed'],
['member-timeout', 'memberTimeout'],
['member-unavailable', 'memberUnavailable'],