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。

Merge group-task-home-reply-timeout into bots-ux

Chriseca613eb470c
diff --cc apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index bc733a08ea,38d6a184c4..e798bfde83
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@@ -1925,305 -1913,375 +1969,675 @@@ describe('Chat Server result delivery a
expect(fixture.handle.mock.calls.some(([route]) => route.includes('/messages?'))).toBe(false);
});
+ describe('latency and push contract', () => {
+ const peerId = '60000000-0000-4000-8000-000000000009';
+ const botMember = { id: botId, kind: 'bot', name: 'Bot', state: 'joined', role: 'member', ownerActorId: selfId, ownerName: 'Me', guestAccess: 'chat' };
+ const selfMember = { id: selfId, kind: 'human', name: 'Me', state: 'joined', role: 'owner', ownerActorId: selfId, ownerName: 'Me' };
+ const snapshotOf = (messages: unknown[] = [], cursor = '1') => ({ body: { room: room(roomId), members: [selfMember, botMember], messages, cursor } });
+ const routesSince = (from: number) => fixture.handle.mock.calls.slice(from).map(([route, method]) => `${method} ${route}`)
+ .filter(call => !call.includes('/executions/claim') && !call.endsWith(' /me') && !call.endsWith(' /actors') && !call.includes('/profile/refresh'));
+ const send = (clientId: string, mentions = { all: false, botIds: [] as string[] }) =>
+ service.sendMessage({ groupId: roomId, text: 'Make a draft', clientId, mentions });
+ /** Opens the realtime connection created by the first poll and follows the room. */
+ async function live() {
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets[0]!;
+ Object.defineProperty(socket, 'readyState', { value: 1 });
+ socket.emit('message', JSON.stringify({ type: 'ready' }));
+ expect((await service.getGroup(roomId)).ok).toBe(true);
+ await vi.advanceTimersByTimeAsync(150);
+ vi.mocked(deps.onChanged!).mockClear();
+ return socket;
+ }
+ const pushes = () => vi.mocked(deps.onChanged!).mock.calls.filter(([payload]) => payload.groupId === roomId).length;
+
+ beforeEach(() => {
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/snapshot')) return snapshotOf();
+ if (route.endsWith('/members')) return { body: [selfMember, botMember] };
+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: '90000000-0000-4000-8000-000000000001' } };
+ return response(route);
+ });
+ });
+
+ it('reads what a send needs in one round trip and skips the member read for an unaddressed message', async () => {
+ await service.chatServer!.ownedBots();
+ let release: (() => void) | undefined;
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/snapshot')) return release ? snapshotOf() : new Promise(resolve => { release = () => resolve(snapshotOf()); });
+ if (route.endsWith('/members')) return { body: [selfMember, botMember] };
+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: '90000000-0000-4000-8000-000000000001' } };
+ return response(route);
+ });
+ const from = fixture.handle.mock.calls.length;
+ const sent = send('latency-send-1', { all: false, botIds: [botId] });
+ await vi.advanceTimersByTimeAsync(0);
+ // Plans and members were requested while the snapshot was still unanswered.
+ expect(routesSince(from).sort()).toEqual([`GET /conversations/${roomId}/members`, `GET /conversations/${roomId}/plans`, `GET /conversations/${roomId}/snapshot`]);
+ release!();
+ expect(await sent).toMatchObject({ ok: true });
+ expect(routesSince(from).at(-1)).toBe(`POST /conversations/${roomId}/messages`);
+ expect(routesSince(from)).toHaveLength(4);
+ const plain = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-2')).toMatchObject({ ok: true });
+ expect(routesSince(plain).sort()).toEqual([`GET /conversations/${roomId}/plans`, `GET /conversations/${roomId}/snapshot`, `POST /conversations/${roomId}/messages`]);
+ });
+
+ it('reuses the snapshot a live subscription vouches for and pushes the send once, on its echo', async () => {
+ const socket = await live();
+ const from = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-3')).toMatchObject({ ok: true });
+ expect(routesSince(from)).toEqual([`GET /conversations/${roomId}/plans`, `POST /conversations/${roomId}/messages`]);
+ await vi.advanceTimersByTimeAsync(150);
+ // The followed room reports the stored message itself: no local push before the echo.
+ expect(pushes()).toBe(0);
+ for (const cursor of ['2', '3']) socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor,
+ changes: [{ type: 'message.created', entityId: '90000000-0000-4000-8000-000000000001' }] }));
+ await vi.advanceTimersByTimeAsync(150);
+ expect(pushes()).toBe(1);
+ // A change notice makes the next send read a fresh snapshot.
+ const next = fixture.handle.mock.calls.length;
+ expect(await send('latency-send-4')).toMatchObject({ ok: true });
+ expect(routesSince(next)).toContain(`GET /conversations/${roomId}/snapshot`);
+ });
+
+ it('still pushes a send locally while the realtime connection is down', async () => {
+ expect(await send('latency-send-5')).toMatchObject({ ok: true });
+ expect(pushes()).toBe(0);
+ await vi.advanceTimersByTimeAsync(150);
+ expect(pushes()).toBe(1);
+ });
+
+ it('answers a send before the replaced arrangement is cancelled, and still cancels it', async () => {
+ const base = fixture.handle.getMockImplementation()!;
+ let finishCancel!: () => void;
+ const sources: string[] = [];
+ fixture.handle.mockImplementation((route, method, data) => {
+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } };
+ if (route.endsWith('/messages') && method === 'POST') { sources.push(data.operationId); return { body: { id: `5000000${sources.length}-0000-4000-8000-000000000001` } }; }
+ if (route.endsWith('/cancel-planning')) return new Promise(resolve => { finishCancel = () => resolve({ body: {} }); });
+ return base(route, method, data);
+ });
+ deps.decidePlan = vi.fn(() => new Promise(() => {})) as typeof deps.decidePlan;
+ expect(await send('latency-plan-a')).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.decidePlan).toHaveBeenCalledOnce();
+ const second = await send('latency-plan-b');
+ expect(second).toMatchObject({ ok: true, messageId: '50000002-0000-4000-8000-000000000001' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/messages/50000001-0000-4000-8000-000000000001/cancel-planning`, 'POST',
+ expect.objectContaining({ failed: false }));
+ finishCancel();
+ await vi.advanceTimersByTimeAsync(0);
+ // B's own arrangement starts only after A's cancel has been answered.
+ expect(deps.decidePlan).toHaveBeenCalledTimes(2);
+ });
+
+ it('retries at once when cancelling a send that a newer send overtook fails', async () => {
+ const base = fixture.handle.getMockImplementation()!;
+ let finishFirst!: () => void;
+ const cancels: string[] = [];
+ let posts = 0;
+ fixture.handle.mockImplementation((route, method, data) => {
+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } };
+ if (route.endsWith('/messages') && method === 'POST') {
+ posts += 1;
+ const body = { id: `5000000${posts}-0000-4000-8000-000000000001` };
+ // The first send is answered only after the second one has installed its intent.
+ return posts === 1 ? new Promise(resolve => { finishFirst = () => resolve({ body }); }) : { body };
+ }
+ if (route.endsWith('/cancel-planning')) {
+ cancels.push(route);
+ return cancels.length === 1 ? { status: 503, body: { error: { code: 'UNAVAILABLE' } } } : { body: {} };
+ }
+ return base(route, method, data);
+ });
+ deps.decidePlan = vi.fn(() => new Promise(() => {})) as typeof deps.decidePlan;
+ const first = send('latency-plan-d');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await send('latency-plan-e')).toMatchObject({ ok: true, messageId: '50000002-0000-4000-8000-000000000001' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.decidePlan).toHaveBeenCalledOnce();
+ finishFirst();
+ expect(await first).toMatchObject({ ok: true, messageId: '50000001-0000-4000-8000-000000000001' });
+ await vi.advanceTimersByTimeAsync(0);
+ // The overtaken message is cancelled; the transient failure is retried right away, and
+ // the overtaken message never starts an arrangement of its own.
+ const cancel = `/conversations/${roomId}/messages/50000001-0000-4000-8000-000000000001/cancel-planning`;
+ expect(cancels).toEqual([cancel, cancel]);
+ expect(deps.decidePlan).toHaveBeenCalledOnce();
+ });
+
+ it('keeps retrying an overtaken send\'s cancel with backoff until it lands', async () => {
+ const base = fixture.handle.getMockImplementation()!;
+ let finishFirst!: () => void;
+ const cancels: string[] = [];
+ let posts = 0;
+ fixture.handle.mockImplementation((route, method, data) => {
+ if (route === '/me') return { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } };
+ if (route.endsWith('/messages') && method === 'POST') {
+ posts += 1;
+ const body = { id: `5000000${posts}-0000-4000-8000-000000000001` };
+ return posts === 1 ? new Promise(resolve => { finishFirst = () => resolve({ body }); }) : { body };
+ }
+ if (route.endsWith('/cancel-planning')) {
+ cancels.push(route);
+ // The cancel and its immediate retry both fail, and so does the first backoff retry.
+ return cancels.length <= 3 ? { status: 503, body: { error: { code: 'UNAVAILABLE' } } } : { body: {} };
+ }
+ return base(route, method, data);
+ });
+ deps.decidePlan = vi.fn(() => new Promise(() => {})) as typeof deps.decidePlan;
+ const first = send('latency-plan-f');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await send('latency-plan-g')).toMatchObject({ ok: true });
+ finishFirst();
+ expect(await first).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cancels).toHaveLength(2);
+ // No newer message or control action follows; the deferred message is still released.
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(cancels).toHaveLength(3);
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(cancels).toHaveLength(4);
+ await vi.advanceTimersByTimeAsync(120_000);
+ const cancel = `/conversations/${roomId}/messages/50000001-0000-4000-8000-000000000001/cancel-planning`;
+ expect(cancels).toEqual([cancel, cancel, cancel, cancel]);
+ });
+
+ it('shows the organizer as a planning speaker while the decision runs and removes it after', async () => {
+ let decide!: (value: null) => void;
+ deps.decidePlan = vi.fn(() => new Promise(resolve => { decide = resolve; })) as typeof deps.decidePlan;
+ expect(await send('latency-plan-c')).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ const deciding = await service.getGroup(roomId);
+ expect(deciding).toMatchObject({ ok: true, group: { planningBotId: botId, speakingBotIds: [botId],
+ round: { status: 'running', speakers: [{ botId, sessionId: null, activity: 'planning' }] } } });
+ decide(null);
+ await vi.advanceTimersByTimeAsync(0);
+ const decided = await service.getGroup(roomId);
+ expect(decided).toMatchObject({ ok: true, group: { planningBotId: null, round: { status: 'idle', speakers: [] } } });
+ // 「不要」 continues the message as an ordinary discussion.
+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/continue'))).toBe(true);
+ });
+
+ it('lists incoming message times oldest first, without this account, notices, system events or deleted messages', async () => {
+ const at = (minute: number) => `2026-10-03T00:${String(minute).padStart(2, '0')}:00Z`;
+ const message = (n: number, overrides: Record<string, unknown>) => ({ id: `90000000-0000-4000-8000-0000000000${String(n).padStart(2, '0')}`, seq: String(n),
+ deleted: false, threadRootId: null, createdAt: at(n), content: [{ type: 'text', text: `m${n}` }], ...overrides });
+ const snapshotMessages = [
+ message(9, { authorId: peerId, author: { kind: 'human', name: 'Peer' }, origin: 'chat' }),
+ message(8, { authorId: selfId, author: { kind: 'human', name: 'Me' }, origin: 'chat' }),
+ message(7, { authorId: peerId, author: { kind: 'human', name: 'Peer' }, origin: 'system', content: [{ type: 'card', namespace: 'cindy.membership', schemaRevision: 1,
+ fallback: 'Peer joined', data: { type: 'member.joined', actorId: peerId, displayName: 'Peer' } }] }),
+ message(6, { authorId: botId, author: { kind: 'bot', name: 'Bot' }, origin: 'integration', content: [{ type: 'card', namespace: 'cindy.group-notice',
+ schemaRevision: 1, fallback: 'failed', data: { noticeCode: 'member-failed' } }] }),
+ message(5, { authorId: botId, author: { kind: 'bot', name: 'Bot' }, origin: 'chat', deleted: true }),
+ message(4, { authorId: botId, author: { kind: 'bot', name: 'Bot' }, origin: 'chat' }),
+ ];
+ fixture.handle.mockImplementation(route => route.endsWith('/snapshot') ? snapshotOf(snapshotMessages)
+ : route === '/conversations?limit=100' ? { body: [room(roomId)] } : response(route));
+ const detail = await service.getGroup(roomId);
+ expect(detail.ok && detail.group.incomingMessageTimes).toEqual([at(4), at(9)].map(value => new Date(value).toISOString()));
+ const list = await service.listGroups();
+ expect(list.ok && list.groups[0]!.incomingMessageTimes).toEqual([at(4), at(9)].map(value => new Date(value).toISOString()));
+ });
+
+ it('re-reads only the sidebar rooms whose change head moved', async () => {
+ const second = '10000000-0000-4000-8000-000000000002';
+ const heads = new Map([[roomId, '5'], [second, '9']]);
+ fixture.handle.mockImplementation(route => {
+ if (route === '/conversations?limit=100') return { body: [roomId, second].map(id => ({ ...room(id), head: heads.get(id) })) };
+ if (route.endsWith('/snapshot')) return { body: { ...snapshotOf().body, room: room(route.split('/')[2]!) } };
+ return response(route);
+ });
+ expect((await service.listGroups()).ok).toBe(true);
+ const from = fixture.handle.mock.calls.length;
+ expect((await service.listGroups()).ok).toBe(true);
+ expect(routesSince(from)).toEqual(['GET /conversations?limit=100']);
+ heads.set(second, '10');
+ const moved = fixture.handle.mock.calls.length;
+ const result = await service.listGroups();
+ expect(result.ok && result.groups.map(group => group.id)).toEqual([roomId, second]);
+ expect(routesSince(moved).filter(call => call.includes(roomId))).toEqual([]);
+ expect(routesSince(moved).filter(call => call.includes(`${second}/snapshot`))).toHaveLength(1);
+ });
+
+ it('claims newly queued work from its realtime notice instead of waiting for the poll', async () => {
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ claimed = true;
+ const socket = await live();
+ const claims = () => fixture.handle.mock.calls.filter(([route]) => route === '/executions/claim').length;
+ // The next poll is at 4s; the notice arrives just after the first one.
+ vi.setSystemTime(Date.now());
+ const before = claims();
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '7',
+ changes: [{ type: 'execution.changed', entityId: execution.id, data: { status: 'queued', botId: peerId } }] }));
+ await vi.advanceTimersByTimeAsync(300);
+ // Work for a companion of another device is not this device's to claim.
+ expect(claims()).toBe(before);
+ claimed = false;
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '8',
+ changes: [{ type: 'execution.changed', entityId: execution.id, data: { status: 'queued', botId } }] }));
+ await vi.advanceTimersByTimeAsync(249);
+ expect(claims()).toBe(before);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(claims()).toBe(before + 1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ });
+
+ it('keeps realtime claims inside the poll backoff after a 429', async () => {
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ const socket = await live();
+ fixture.handle.mockImplementation(route => route === '/executions/claim'
+ ? { status: 429, headers: { 'retry-after': '120' }, body: { error: { code: 'RATE_LIMITED' } } } : response(route));
+ await vi.advanceTimersByTimeAsync(2000);
+ const claims = () => fixture.handle.mock.calls.filter(([route]) => route === '/executions/claim').length;
+ const limited = claims();
+ expect(limited).toBeGreaterThan(0);
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '9',
+ changes: [{ type: 'execution.changed', entityId: execution.id, data: { status: 'queued', botId } }] }));
+ await vi.advanceTimersByTimeAsync(110_000);
+ expect(claims()).toBe(limited);
+ });
+
+ it('claims for several owned companions at once', async () => {
+ const otherBot = '20000000-0000-4000-8000-000000000002';
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }, { id: 'other-bot', displayName: 'Other', avatar: null, status: 'active' }];
+ const pending: string[] = [];
+ fixture.handle.mockImplementation((route, _method, _body) => {
+ if (route === '/actors') return { body: [{ id: botId, kind: 'bot', externalId: 'local-bot', name: 'Bot' }, { id: otherBot, kind: 'bot', externalId: 'other-bot', name: 'Other' }] };
+ if (route === '/executions/claim') { pending.push(route); return new Promise(() => {}); }
+ return response(route);
+ });
+ await vi.advanceTimersByTimeAsync(2000);
+ // Both claims are in flight together, neither waiting for the other's answer.
+ expect(pending).toHaveLength(2);
+ });
+
+ it('renews the lease once, right before the dispatch, after preparing the turn', async () => {
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ let heartbeatsAtDispatch = -1;
+ deps.dispatch = vi.fn(async (input: Parameters<BotGroupChatServiceDeps['dispatch']>[0]) => {
+ heartbeatsAtDispatch = fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'heartbeat').length;
+ await input.onAccepted?.(); return { ok: true as const, targetSessionId: input.targetSessionId, wakeKind: 'queued' as const };
+ }) as unknown as BotGroupChatServiceDeps['dispatch'];
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ expect(heartbeatsAtDispatch).toBe(1);
+ });
+ });
++
+ describe('thread previews and main-chat shares', () => {
+ const aliceId = '30000000-0000-4000-8000-0000000000a1';
+ const rootId = '70000000-0000-4000-8000-000000000001';
+ const botReply = '70000000-0000-4000-8000-000000000002';
+ const aliceReply = '70000000-0000-4000-8000-000000000003';
+ const deletedReply = '70000000-0000-4000-8000-000000000004';
+ const member = (id: string, kind: 'human' | 'bot', name: string, ownerActorId: string, ownerName: string) => ({ id, kind, name, state: 'joined', role: 'member',
+ displayName: name, avatar: null, nickname: null, ownerActorId, ownerName, guestAccess: 'none', accessRevision: 1 });
+ const members = [member(selfId, 'human', 'Me', selfId, 'Me'), member(botId, 'bot', 'Bot', selfId, 'Me'), member(aliceId, 'human', 'Alice', aliceId, 'Alice')];
+ const msg = (id: string, seq: number, authorId: string, extra: Record<string, unknown> = {}) => ({ id, seq: String(seq), authorId, origin: 'user', deleted: false, threadRootId: null,
+ createdAt: new Date(Date.UTC(2026, 9, 3, 0, seq)).toISOString(), author: { kind: authorId === botId ? 'bot' : 'human', name: members.find(m => m.id === authorId)?.name ?? '?' },
+ content: [{ type: 'text', text: `text of ${id}` }], ...extra });
+ const shareCard = (messageId: string, threadRoot = rootId) => [{ type: 'card', namespace: 'cindy.thread-share', schemaRevision: 1, fallback: '↪ someone: forged words', data: { messageId, threadRootId: threadRoot } }];
+ const root = msg(rootId, 1, aliceId, { replyCount: 2, content: [{ type: 'text', text: '周末去哪? @Bot' }] });
+ const replies = [
+ msg(botReply, 2, botId, { threadRootId: rootId, content: [{ type: 'text', text: '@Alice 去爬山' }, { type: 'media', mediaId: '80000000-0000-4000-8000-000000000001', caption: 'map.png' }] }),
+ msg(deletedReply, 3, aliceId, { threadRootId: rootId, deleted: true, content: [] }),
+ msg(aliceReply, 4, aliceId, { threadRootId: rootId, revision: 2 }),
+ ];
+ const shares = [
+ msg('90000000-0000-4000-8000-000000000001', 5, selfId, { content: shareCard(botReply) }),
+ msg('90000000-0000-4000-8000-000000000002', 6, aliceId, { content: shareCard(aliceReply) }),
+ msg('90000000-0000-4000-8000-000000000003', 7, aliceId, { content: shareCard(botReply, aliceReply) }),
+ msg('90000000-0000-4000-8000-000000000004', 8, aliceId, { content: shareCard(deletedReply) }),
+ ];
+ function threadResponse(route: string, method?: string, body?: Record<string, unknown>) {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [...shares, ...replies, root].sort((a, b) => Number(b.seq) - Number(a.seq)), cursor: '8' } };
+ if (route.endsWith('/members')) return { body: members };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [...shares].reverse().concat(root) };
+ const single = /\/messages\/([0-9a-f-]{36})$/.exec(route)?.[1];
+ if (single && method === 'GET') {
+ const found = [root, ...replies, ...shares].find(m => m.id === single);
+ return found ? { body: found } : { status: 404, body: { error: { code: 'MESSAGE_NOT_FOUND' } } };
+ }
+ if (route === `/conversations/${roomId}/messages` && method === 'POST') return { body: { id: `share-of-${(body?.content as Array<{ data: { messageId: string } }>)[0].data.messageId}` } };
+ return response(route);
+ }
+ beforeEach(() => {
+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ fixture.download.mockResolvedValue({ id: 'map', name: 'map.png', category: 'image', mimeType: 'image/png', size: 1, url: 'cindy-media://map', path: null });
+ claimed = true;
+ fixture.handle.mockImplementation(threadResponse);
+ });
+
+ it.each([undefined, ' '])('uses the ordinary attachment name for caption %s in previews and share fallback', async caption => {
+ const source = msg(botReply, 2, botId, { threadRootId: rootId, content: [{ type: 'media', mediaId: '80000000-0000-4000-8000-000000000001', caption }] });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [source, root], cursor: '8' } };
+ if (route.endsWith(`/messages/${botReply}`)) return { body: source };
+ return threadResponse(route, method, body);
+ });
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ expect(result.group.messages.find(m => m.id === rootId)!.threadPreview!.replies[0]!.attachments)
+ .toEqual([{ name: 'Attachment', category: 'file' }]);
+ expect((await service.chatServer!.shareToMain({ groupId: roomId, messageId: botReply })).ok).toBe(true);
+ const posted = fixture.handle.mock.calls.find(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST')![2];
+ expect(posted).toMatchObject({ content: [{ fallback: '↪ Bot (Me): Attachment' }] });
+ });
+
+ it('resolves every loaded old reference without a 200-card cutoff', async () => {
+ const shownShares = Array.from({ length: 201 }, (_, i) => ({ id: `90000000-0000-4000-8000-${String(i + 100).padStart(12, '0')}`, messageId: botReply, threadRootId: rootId }));
+ const result = await service.getGroup(roomId, { shownShares });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(Object.keys(result.group.threadShareUpdates!)).toHaveLength(201);
+ expect(Object.values(result.group.threadShareUpdates!).every(share => share.status === 'available')).toBe(true);
+ });
+
+ it('previews the newest replies and resolves each share from the server copy, not the card', async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ const byId = new Map(result.group.messages.map(m => [m.id, m]));
+ expect(byId.get(rootId)!.threadPreview!.replies.map(r => [r.id, r.authorName, r.text, r.attachments])).toEqual([
+ [botReply, 'Bot (Me)', '@Alice 去爬山', [{ name: 'map.png', category: 'image' }]],
+ [aliceReply, 'Alice', `text of ${aliceReply}`, []],
+ ]);
+ const [mine, alices, forged, deleted] = shares.map(share => byId.get(share.id)!.threadShare!);
+ expect(mine).toMatchObject({ status: 'available', messageId: botReply, threadRootId: rootId, authorName: 'Bot (Me)', authorBotId: 'local-bot',
+ authorKind: 'bot', sharedByAuthor: false, content: '@Alice 去爬山', edited: false });
+ expect(alices).toMatchObject({ status: 'available', authorName: 'Alice', sharedByAuthor: true, edited: true });
+ // A card that names the wrong thread or a deleted reply shows no borrowed words.
+ expect(forged).toMatchObject({ status: 'unavailable', authorName: '', content: '' });
+ expect(deleted).toMatchObject({ status: 'unavailable', content: '' });
+ expect(JSON.stringify(result.group.messages.map(m => m.threadShare))).not.toContain('forged words');
+ // Old phones read `content`: keep the server fallback there.
+ expect(byId.get(shares[0].id)!.content).toBe('↪ someone: forged words');
+ // Everything came from the snapshot window: no per-root or per-share reads.
+ expect(fixture.handle.mock.calls.filter(([route]) => route.includes('threadRootId=') || /\/messages\/[0-9a-f-]{36}$/.test(route))).toHaveLength(0);
+ });
+
+ it('posts a share as the current user, addressed only to them, with one stable operation per reply', async () => {
+ const first = await service.chatServer!.shareToMain({ groupId: roomId, messageId: botReply });
+ const again = await service.chatServer!.shareToMain({ groupId: roomId, messageId: botReply });
+ expect(first).toEqual({ ok: true, messageId: `share-of-${botReply}`, alreadyShared: false });
+ expect(again).toEqual(first);
+ const posts = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST');
+ expect(posts).toHaveLength(2);
+ expect(posts[0][2]).toEqual(posts[1][2]);
+ expect(posts[0][2]).toEqual({
+ operationId: `thread-share:${botReply}`, mentions: [selfId],
+ content: [{ type: 'card', namespace: 'cindy.thread-share', schemaRevision: 1, fallback: '↪ Bot (Me): @Alice 去爬山', data: { messageId: botReply, threadRootId: rootId } }],
+ });
+ // No thread placement, no deferred companion round, no X-Chat-Actor impersonation.
+ expect(posts[0][2]).not.toHaveProperty('threadRootId');
+ expect(posts[0][2]).not.toHaveProperty('deferExecution');
+ });
+
+ it.each([['a root message', rootId], ['a deleted reply', deletedReply], ['an unknown message', '70000000-0000-4000-8000-0000000000ff']])(
+ 'refuses to share %s', async (_label, messageId) => {
+ const result = await service.chatServer!.shareToMain({ groupId: roomId, messageId });
+ // A missing reply reads as unavailable here; MESSAGE_NOT_FOUND stays generic elsewhere.
+ expect(result).toMatchObject({ ok: false, errorCode: 'SHARE_UNAVAILABLE' });
+ expect(fixture.handle.mock.calls.some(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST')).toBe(false);
+ });
+
+ it('reports a repeat after the reply changed as already shared instead of posting again', async () => {
+ fixture.handle.mockImplementation((route, method, body) => route === `/conversations/${roomId}/messages` && method === 'POST'
+ ? { status: 409, body: { error: { code: 'OPERATION_CONFLICT' } } } : threadResponse(route, method, body));
+ expect(await service.chatServer!.shareToMain({ groupId: roomId, messageId: aliceReply })).toEqual({ ok: true, messageId: null, alreadyShared: true });
+ });
+
+ it('re-reads a cached share source only after the server reports it edited', async () => {
+ const outside = '70000000-0000-4000-8000-000000000009';
+ const share = msg('90000000-0000-4000-8000-000000000009', 9, aliceId, { content: shareCard(outside) });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [share], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [share] };
+ if (route.endsWith(`/messages/${outside}`)) return { body: msg(outside, 1, aliceId, { threadRootId: rootId }) };
+ return threadResponse(route, method, body);
+ });
+ const reads = () => fixture.handle.mock.calls.filter(([route]) => route.endsWith(`/messages/${outside}`)).length;
+ await service.getGroup(roomId);
+ await service.getGroup(roomId);
+ expect(reads()).toBe(1);
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets.at(-1)!;
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '10',
+ changes: [{ type: 'message.updated', entityId: outside }] }));
+ await service.getGroup(roomId);
+ expect(reads()).toBe(2);
+ // A cursor reset skips the pushes in between, so nothing cached may survive it.
+ Object.assign(socket, { readyState: 1 });
+ socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'RESET_REQUIRED' } }));
+ await vi.advanceTimersByTimeAsync(0);
+ await service.getGroup(roomId);
+ expect(reads()).toBe(3);
+ });
+
+ it('does not reuse a cached share source after losing the room subscription', async () => {
+ const outside = '70000000-0000-4000-8000-00000000000a';
+ const share = msg('90000000-0000-4000-8000-00000000000a', 9, aliceId, { content: shareCard(outside) });
+ let visible = true;
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [share], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [share] };
+ if (route.endsWith(`/messages/${outside}`)) return visible
+ ? { body: msg(outside, 1, aliceId, { threadRootId: rootId, content: [{ type: 'text', text: 'before you left' }] }) }
+ : { status: 404, body: { error: { code: 'MESSAGE_NOT_FOUND' } } };
+ return threadResponse(route, method, body);
+ });
+ const shareView = async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.messages.find(m => m.id === share.id)!.threadShare!;
+ };
+ expect(await shareView()).toMatchObject({ status: 'loading', content: '' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await shareView()).toMatchObject({ status: 'available', content: 'before you left' });
+ await vi.advanceTimersByTimeAsync(2000);
+ // Removed from the room; on rejoin the history window no longer covers that reply.
+ fixture.sockets.at(-1)!.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
+ visible = false;
+ expect(await shareView()).not.toMatchObject({ content: 'before you left' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await shareView()).toMatchObject({ status: 'unavailable', content: '' });
+ });
+
+ it.each([
+ ['a server error', { status: 503, body: { error: { code: 'UNAVAILABLE' } } }, 'loading'],
+ ['a timeout-like failure', null, 'loading'],
+ ['forbidden', { status: 403, body: { error: { code: 'FORBIDDEN' } } }, 'unavailable'],
+ ['gone', { status: 410, body: { error: { code: 'GONE' } } }, 'unavailable'],
+ ] as const)('never shows the card text when reading the reply hits %s', async (_label, reply, status) => {
+ const outside = '70000000-0000-4000-8000-00000000000b';
+ const share = msg('90000000-0000-4000-8000-00000000000b', 9, aliceId, { content: shareCard(outside) });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [share], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [share] };
+ if (route.endsWith(`/messages/${outside}`)) { if (!reply) throw new Error('socket hang up'); return reply; }
+ return threadResponse(route, method, body);
+ });
+ const read = async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.messages.find(m => m.id === share.id)!.threadShare!;
+ };
+ await read();
+ await vi.advanceTimersByTimeAsync(0);
+ const view = await read();
+ expect(view).toMatchObject({ status, content: '', authorName: '' });
+ expect(JSON.stringify(view)).not.toContain('forged words');
+ });
+
+ it('names the sharer in the sidebar and never quotes or resolves the card', async () => {
+ const forged = msg('90000000-0000-4000-8000-00000000000c', 20, aliceId, { content: shareCard(botReply) });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route === '/conversations?limit=100') return { body: [room(roomId)] };
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [forged, ...replies, root], cursor: '20' } };
+ return threadResponse(route, method, body);
+ });
+ const result = await service.listGroups();
+ if (!result.ok) throw new Error('Expected groups');
+ expect(result.groups[0]!.lastMessage).toMatchObject({ preview: '', threadShare: true, authorName: 'Alice' });
+ expect(JSON.stringify(result.groups)).not.toContain('forged words');
+ // The sidebar costs no per-group share or thread reads.
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fixture.handle.mock.calls.filter(([route]) => route.includes('threadRootId=') || /\/messages\/[0-9a-f-]{36}$/.test(route))).toHaveLength(0);
+ });
+
+ it('updates shares shown on older pages after an edit, a deletion or lost access, without a reload', async () => {
+ const outside = '70000000-0000-4000-8000-00000000000d';
+ const ref = { id: '90000000-0000-4000-8000-00000000000d', messageId: outside, threadRootId: rootId, sharerId: aliceId };
+ let source: Record<string, unknown> | null = msg(outside, 1, aliceId, { threadRootId: rootId, content: [{ type: 'text', text: 'v1' }] });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [root], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?limit=`)) return { body: [root] };
+ if (route.endsWith(`/messages/${outside}`)) return source ? { body: source } : { status: 404, body: { error: { code: 'MESSAGE_NOT_FOUND' } } };
+ return threadResponse(route, method, body);
+ });
+ const read = async () => {
+ const result = await service.getGroup(roomId, { shownShares: [ref] });
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.threadShareUpdates![ref.id]!;
+ };
+ const settle = async () => { await read(); await vi.advanceTimersByTimeAsync(0); return read(); };
+ expect(await read()).toMatchObject({ status: 'loading', content: '' });
+ vi.mocked(deps.onChanged!).mockClear();
- await vi.advanceTimersByTimeAsync(0);
++ await vi.advanceTimersByTimeAsync(150);
+ // The background read asks the open page to refresh: no click or reopen needed.
+ expect(deps.onChanged).toHaveBeenCalledWith({ groupId: roomId, change: 'messages' }, undefined);
+ expect(await read()).toMatchObject({ status: 'available', content: 'v1', sharedByAuthor: true, edited: false });
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets.at(-1)!;
+ source = { ...source, revision: 2, content: [{ type: 'text', text: 'v2' }] };
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '10', changes: [{ type: 'message.updated', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'available', content: 'v2', edited: true });
+ source = { ...source, deleted: true, content: [] };
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '11', changes: [{ type: 'message.deleted', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'unavailable', content: '' });
+ // Back to visible, then the reader loses access: the old text must not come back.
+ source = msg(outside, 1, aliceId, { threadRootId: rootId, content: [{ type: 'text', text: 'v3' }] });
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '12', changes: [{ type: 'message.updated', entityId: outside }] }));
+ expect(await settle()).toMatchObject({ status: 'available', content: 'v3' });
+ socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
+ source = null;
+ expect(await read()).not.toMatchObject({ content: 'v3' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(await read()).toMatchObject({ status: 'unavailable', content: '' });
+ });
+
+ it('raises the share version on edits and lost access so unchecked older shares are not trusted', async () => {
+ const version = async () => {
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ return result.group.threadShareVersion!;
+ };
+ const start = await version();
+ await vi.advanceTimersByTimeAsync(2000);
+ const socket = fixture.sockets.at(-1)!;
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '10', changes: [{ type: 'message.deleted', entityId: botReply }] }));
+ const afterDelete = await version();
+ expect(afterDelete).toBeGreaterThan(start);
+ socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'FORBIDDEN' } }));
+ expect(await version()).toBeGreaterThan(afterDelete);
+ // Share views carry the version they were checked at.
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ expect(result.group.messages.find(m => m.id === shares[0]!.id)!.threadShare!.version).toBe(result.group.threadShareVersion);
+ });
+
+ it('does not let 「继续讨论」 restart a re-posted reply', async () => {
+ const ask = msg('90000000-0000-4000-8000-0000000000aa', 1, selfId);
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route === `/conversations/${roomId}/messages?limit=100`) return { body: [shares[0], ask] };
+ if (route.endsWith('/executions')) return { body: [] };
+ return threadResponse(route, method, body);
+ });
+ expect(await service.continueRound(roomId)).toEqual({ ok: true });
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/messages/${ask.id}/continue`, 'POST', expect.anything());
+ expect(fixture.handle.mock.calls.some(([route]) => route.includes(`/messages/${shares[0].id}/continue`))).toBe(false);
+ });
+
+ it('keeps mixed-card text visible and eligible for discussion without marking it as a shared reply', async () => {
+ const mixed = msg(execution.source_message_id, 9, selfId, {
+ content: [...shareCard(botReply), { type: 'text', text: 'Bot, summarize this extra text' }],
+ });
+ fixture.handle.mockImplementation((route, method, body) => {
+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members, messages: [mixed], cursor: '9' } };
+ if (route.startsWith(`/conversations/${roomId}/messages?`)) return { body: [mixed] };
+ if (route.endsWith('/executions')) return { body: [] };
+ return threadResponse(route, method, body);
+ });
+ const result = await service.getGroup(roomId);
+ if (!result.ok) throw new Error('Expected group');
+ expect(result.group.messages[0].threadShare).toBeUndefined();
+ expect(result.group.messages[0].content).toContain('Bot, summarize this extra text');
+ expect(await service.continueRound(roomId)).toEqual({ ok: true });
+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/messages/${mixed.id}/continue`, 'POST', expect.anything());
+
+ claimed = false;
+ fixture.handle.mockImplementation((route, method, body) => route.includes('all=true') ? { body: [mixed] }
+ : route.endsWith('/snapshot') || route.endsWith('/members') ? threadResponse(route, method, body) : response(route));
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ const prompt = vi.mocked(deps.dispatch).mock.calls[0][0].message;
+ const history = [...prompt.matchAll(/<untrusted-data>\n(.*?)\n<\/untrusted-data>/g)].map(match => JSON.parse(match[1])).find(block => block.messages)!.messages;
+ expect(history.find((m: { id: string }) => m.id === mixed.id)).toMatchObject({ text: result.group.messages[0].content });
+ expect(history.find((m: { id: string }) => m.id === mixed.id)).not.toHaveProperty('sharedReplyId');
+ });
+
+ it('tells companions a share is a reference whose quoted @names address no one', async () => {
+ claimed = false;
+ fixture.handle.mockImplementation((route, method, body) => route.includes('all=true')
+ ? { body: [...shares, { ...msg(execution.source_message_id, 1, selfId), content: [{ type: 'text', text: 'Bot, summarize' }] }] }
+ : route.endsWith('/snapshot') || route.endsWith('/members') ? threadResponse(route, method, body) : response(route));
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ const prompt = vi.mocked(deps.dispatch).mock.calls[0][0].message;
+ expect(prompt).toContain('A message with sharedReplyId re-posts an existing thread reply');
+ const history = [...prompt.matchAll(/<untrusted-data>\n(.*?)\n<\/untrusted-data>/g)].map(match => JSON.parse(match[1])).find(block => block.messages)!.messages;
+ for (const share of shares) expect(history.find((m: { id: string }) => m.id === share.id))
+ .toMatchObject({ sharedReplyId: expect.any(String), text: '' });
+ expect(prompt).not.toContain('forged words');
+ expect(history.find((m: { id: string }) => m.id === execution.source_message_id)).not.toHaveProperty('sharedReplyId');
+ });
+
+ it('omits share fallback from arrangement context while retaining ordinary text', async () => {
+ deps.decidePlan = vi.fn(async () => null);
+ fixture.handle.mockImplementation((route, method, body) => route.endsWith('/messages') && method === 'POST'
+ ? { body: { id: execution.source_message_id } } : threadResponse(route, method, body));
+ expect(await service.sendMessage({ groupId: roomId, text: 'Plan our trip', clientId: 'share-context-plan',
+ division: true, mentions: { all: false, botIds: [] } })).toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(deps.decidePlan).toHaveBeenCalledOnce();
+ const context = vi.mocked(deps.decidePlan).mock.calls[0][0];
+ expect(context.recent.filter(m => m.sharedReplyId)).toHaveLength(shares.length);
+ expect(context.recent.filter(m => m.sharedReplyId).every(m => m.text === '')).toBe(true);
+ expect(JSON.stringify(context)).not.toContain('forged words');
+ expect(context.recent).toContainEqual(expect.objectContaining({ text: '@Alice 去爬山\n[附件: map.png]' }));
+ });
+
+ it('marks a share in the main-group background of a Thread request as a reference too', async () => {
+ claimed = false;
+ const rootId = '90000000-0000-4000-8000-0000000000bb';
+ const source = { ...msg(execution.source_message_id, 2, selfId), threadRootId: rootId, content: [{ type: 'text', text: 'Bot, summarize' }] };
+ fixture.handle.mockImplementation((route, method, body) => route.includes('all=true') || route.includes('threadRootId=') ? { body: [source] }
+ : route.startsWith(`/conversations/${roomId}/messages?limit=`) ? { body: [shares[0]] }
+ : route === `/conversations/${roomId}/messages/${rootId}` ? { body: msg(rootId, 1, selfId) }
+ : route.endsWith('/snapshot') || route.endsWith('/members') ? threadResponse(route, method, body) : response(route));
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ const prompt = vi.mocked(deps.dispatch).mock.calls[0][0].message;
+ expect(prompt).toContain('A message with sharedReplyId re-posts an existing thread reply');
+ const background = [...prompt.matchAll(/<untrusted-data>\n(.*?)\n<\/untrusted-data>/g)].map(match => JSON.parse(match[1])).find(block => block.mainGroupBackground)!.mainGroupBackground;
+ expect(background).toEqual([expect.objectContaining({ id: shares[0].id, sharedReplyId: botReply, text: '' })]);
+ expect(prompt).not.toContain('forged words');
+ });
+ });
});
diff --cc apps/desktop/src/main/maker-ipc/chatServer.ts
index bdafe28643,f2ed02d716..0cce5ec156
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@@ -33,7 -34,9 +34,9 @@@ import
isBotGroupRuntimeFailureCode, type BotGroupRuntimeFailureCode,
readImportedBotGroupRuntimeFailureCode,
readBotGroupExecutionFailure, type BotGroupExecutionFailureView,
+ buildBotGroupThreadShareCard, botGroupThreadShareOperationId, readBotGroupThreadShareCard,
+ type BotGroupThreadShareView,
- type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
+ type BotGroupDetail, type BotGroupSpeaker, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,
botGroupQuoteAttachmentName, botGroupQuoteExcerpt, botGroupQuoteFromMessage, buildBotGroupQuoteCard, readBotGroupQuote, readBotGroupQuoteCard, type BotGroupQuoteView,
readBotGroupTaskCard, botGroupMessageSummaryText,
} from '../../shared/botGroupChat.js';
@@@ -804,17 -686,12 +819,18 @@@ function createChatServer(local: BotGro
const roomId = event.scope.slice(13);
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 === 'reaction.changed' && typeof change.entityId === 'string') {
- bumpMessageReactions(roomId, change.entityId);
+ for (const change of event.changes ?? []) {
+ 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);
}
changed(roomId);
- for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
+ const changes: unknown[] = Array.isArray(event.changes) ? event.changes : [];
+ const types = changes.map(change => (change as { type?: unknown } | null)?.type);
+ // Lease renewals append no change; ordinary chatter cannot revoke a lease, so it does
+ // not renew one either. Any other or unknown change re-checks the room's running work.
+ if (!types.length || types.some(type => typeof type !== 'string' || !CHATTER_CHANGES.has(type)))
+ for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
+ if (changes.some(queuedForThisDevice)) triggerClaim();
}
else {
for (const change of event.changes ?? []) {
@@@ -947,9 -796,10 +967,10 @@@
/**
* The quoted message as this member reads it from the server: the room scopes the read,
* so another group's or an invisible message is a 404. Only a live main-timeline chat
- * message can be quoted; the snapshot never comes from the controller's input.
+ * message can be quoted; the snapshot never comes from the controller's input. A thread
+ * share's own text is only its card's fallback, so a share is not quotable either.
*/
- async function quoteSnapshot(roomId: string, messageId: string, members: Member[]): Promise<BotGroupQuoteView> {
+ async function quoteSnapshot(roomId: string, messageId: string, members: Promise<Member[]>): Promise<BotGroupQuoteView> {
let quoted: Message;
try {
quoted = await api<Message>(`/conversations/${roomId}/messages/${messageId}`);
@@@ -957,9 -807,9 +978,9 @@@
if (error instanceof ChatResponseError && [403, 404].includes(error.status)) throw new Error('QUOTE_UNAVAILABLE');
throw error;
}
- const view = messageView(quoted, members);
+ const view = messageView(quoted, await members);
if (quoted.id !== messageId || quoted.deleted || quoted.threadRootId !== null || quoted.origin === 'system'
- || view.kind !== 'message' || view.authorKind === 'system') throw new Error('QUOTE_UNAVAILABLE');
+ || view.kind !== 'message' || view.authorKind === 'system' || readBotGroupThreadShareCard(quoted)) throw new Error('QUOTE_UNAVAILABLE');
return botGroupQuoteFromMessage({ ...view, content: quotedText(quoted),
attachments: quotedAttachments(quoted) });
}
@@@ -1030,17 -923,18 +1094,22 @@@
const workspace = workspaces().read(roomId);
const plans = serverPlans.map(plan => planView(plan, s.members, workspace));
const open = plans.find(p => ['proposed', 'running', 'waiting'].includes(p.status));
- const speakers = executions.filter(e => e.status === 'running').map(e => ({
+ const speakers: BotGroupSpeaker[] = executions.filter(e => e.status === 'running').map(e => ({
botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: running.get(e.bot_id)?.sessionId ?? null, activity: e.plan_id ? 'step' as const : 'reply' as const,
}));
+ // The organizer is visibly 「正在看」 while this device decides whether to arrange (§7.2),
+ // as the local service showed it. It works on the auxiliary model, not in a lane session.
+ const deciding = planning.get(roomId);
+ if (deciding) speakers.push({ botId: deciding.botId, sessionId: null, activity: 'planning' });
// Sidebar refresh must not download every attachment in every group's history.
- const messages = summaryOnly ? [] : (await messageViews(roomId, page, s.members)).sort((a, b) => a.sequence - b.sequence);
+ 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;
+ messages.sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
const lastView = last ? messageView(last, s.members) : null;
+ // The sidebar never resolves shares: it names the sharer and never quotes the card's text.
+ const lastIsShare = !!last && !!readBotGroupThreadShareCard(last);
return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? runtimeReactionRevision, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, supportsGroupLeave: true, supportsDissolve, supportsListRemoval, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), 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);
@@@ -1058,10 -952,10 +1127,11 @@@
} : 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.origin !== 'system' && m.authorId !== selfId
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
+ incomingMessageTimes: incomingMessageTimes(s.messages, s.members),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
- messages, executionFailures, hasMoreBefore: page.length === (o.limit ?? 100), plans,
- round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || 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'].includes(e.status)) } };
+ messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),
+ ...(shares ? { threadShareVersion: shares.version } : {}), 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 && ordinaryExecution(e)) || s.messages.some(discussionSource)) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };
++ round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id && ordinaryExecution(e)) || s.messages.some(discussionSource)) && !executions.some(e => ['queued','running','stopping'].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,
@@@ -1294,166 -1174,136 +1367,170 @@@
if (ownDirectRoom) { await runDirectExecution(run, bot.id, s.room.id); return; }
// Any other 1:1 room is never answered as a group.
if (s.room.kind === 'direct') throw new Error('INVALID_EXECUTION_TRIGGER');
- // Metadata only: the server remains the sole message store and scheduler.
- if (!metadata.has(s.room.id)) metadata.set(s.room.id, (async () => {
- const client = getDbClient();
- const [localRow] = await client.drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, s.room.id)).limit(1);
- const botIds = s.members.filter(m => m.state === 'joined').map(m => localBot(m.id)?.id).filter((v): v is string => !!v);
- if (!current()) throw new Error('OWNER_CHANGED');
- if (!localRow) await client.tx('botGroups.create', { groupId: s.room.id, name: s.room.name, botIds, now: Date.now() });
- })().catch(error => { metadata.delete(s.room.id); throw error; }));
- await metadata.get(s.room.id);
- // A member may bring another owned companion after this room was first cached.
- await getDbClient().drizzle.insert(botGroupMembers).values({ groupId: s.room.id, botId: bot.id, position: 0, lastSeenSequence: 0, joinedAt: Date.now() }).onConflictDoNothing();
- if (execution.plan_id) {
- run.plan = (await api<ServerPlan[]>(`/conversations/${s.room.id}/plans?ids=${execution.plan_id}`)).find(p => p.id === execution.plan_id);
- if (!run.plan) throw new Error('PLAN_CLOSED');
- if (execution.access_mode !== 'chat') {
- const settings = workspaces().read(s.room.id) ?? { projectDir: null, plans: {} };
- // Each grant has its own workspace. Revoked grants cannot reuse private context.
- const key = `${run.plan.id}:${execution.access_mode}:${execution.access_revision}`;
- run.workspace = settings.plans[key] ?? (execution.access_mode === 'owner' ? settings.plans[run.plan.id] : undefined);
- if (!run.workspace) {
- const prepared = await deps.workDir?.prepare({ groupId: s.room.id, projectDir: settings.projectDir });
- if (!prepared?.ok) throw new Error('WORKDIR_UNAVAILABLE');
- run.workspace = prepared;
- settings.plans[key] = prepared; settings.plans[run.plan.id] = prepared;
- if (!current()) throw new Error('OWNER_CHANGED');
- workspaces().save(s.room.id, settings);
+ // Lane setup and context metadata reads run together; attachment bytes wait for setup
+ // to succeed so a failed setup cannot leave downloads running after settlement.
+ const laneSetup = (async () => {
+ // Metadata only: the server remains the sole message store and scheduler.
+ if (!metadata.has(s.room.id)) metadata.set(s.room.id, (async () => {
+ const client = getDbClient();
+ const [localRow] = await client.drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, s.room.id)).limit(1);
+ const botIds = s.members.filter(m => m.state === 'joined').map(m => localBot(m.id)?.id).filter((v): v is string => !!v);
+ if (!current()) throw new Error('OWNER_CHANGED');
+ if (!localRow) await client.tx('botGroups.create', { groupId: s.room.id, name: s.room.name, botIds, now: Date.now() });
+ })().catch(error => { metadata.delete(s.room.id); throw error; }));
+ await metadata.get(s.room.id);
+ // A member may bring another owned companion after this room was first cached.
+ await getDbClient().drizzle.insert(botGroupMembers).values({ groupId: s.room.id, botId: bot.id, position: 0, lastSeenSequence: 0, joinedAt: Date.now() }).onConflictDoNothing();
+ if (execution.plan_id && planRead) {
+ run.plan = (await planRead).find(p => p.id === execution.plan_id);
+ if (!run.plan) throw new Error('PLAN_CLOSED');
+ if (execution.access_mode !== 'chat') {
+ const settings = workspaces().read(s.room.id) ?? { projectDir: null, plans: {} };
+ // Each grant has its own workspace. Revoked grants cannot reuse private context.
+ const key = `${run.plan.id}:${execution.access_mode}:${execution.access_revision}`;
+ run.workspace = settings.plans[key] ?? (execution.access_mode === 'owner' ? settings.plans[run.plan.id] : undefined);
+ if (!run.workspace) {
+ const prepared = await deps.workDir?.prepare({ groupId: s.room.id, projectDir: settings.projectDir });
+ if (!prepared?.ok) throw new Error('WORKDIR_UNAVAILABLE');
+ run.workspace = prepared;
+ settings.plans[key] = prepared; settings.plans[run.plan.id] = prepared;
+ if (!current()) throw new Error('OWNER_CHANGED');
+ workspaces().save(s.room.id, settings);
+ }
+ run.beforeFiles = await deps.workDir?.snapshot(run.workspace.workDir);
}
- run.beforeFiles = await deps.workDir?.snapshot(run.workspace.workDir);
}
- }
- const lane = await deps.ensureLane({ botId: bot.id, groupId: s.room.id, title: s.room.name,
- chatAccess: { mode: execution.access_mode, revision: execution.access_revision },
- ...(run.plan ? { plan: { planId: run.plan.id, workDir: run.workspace?.workDir ?? '', sessionId: run.workspace?.ownerSessionId ?? undefined } } : {}) });
- if (!lane.ok) throw new Error(lane.errorCode);
- run.sessionId = lane.sessionId;
- run.releaseToolAuthority = registerGroupToolAuthority(lane.sessionId, {
- botId: bot.id, mode: execution.access_mode,
- sourceGroup: { groupId: s.room.id, name: s.room.name },
- isCurrent: () => current() && running.get(execution.bot_id) === run && !run.settlement,
- validate: async () => {
- // Recheck metadata and the execution lease at the actual tool boundary.
- // Group administrators cannot grant access to someone else's companion.
- try {
- const members = await api<Member[]>(`/conversations/${s.room.id}/members`);
- const companion = members.find(m => m.id === execution.bot_id && m.kind === 'bot' && m.state === 'joined');
- const requester = members.find(m => m.id === execution.requester_id && m.state === 'joined');
- if (!companion || companion.ownerActorId !== selfId || !requester
- || companion.accessRevision !== execution.access_revision
- || (execution.access_mode === 'owner' ? requester.ownerActorId !== selfId : companion.guestAccess !== 'tools'))
- throw new GroupToolAuthorizationError();
- await updateExecution(run, 'heartbeat');
- } catch (error) {
- if (error instanceof ChatResponseError && [401, 403, 404, 409, 410].includes(error.status))
- throw new GroupToolAuthorizationError();
- throw error;
- }
- },
- });
- if (run.plan && run.workspace?.ownerSessionId) {
- const settings = workspaces().read(s.room.id)!;
- const key = `${run.plan.id}:${execution.access_mode}:${execution.access_revision}`;
- run.workspace = { ...run.workspace, ownerSessionId: null };
- settings.plans[key] = run.workspace; settings.plans[run.plan.id] = run.workspace;
- workspaces().save(s.room.id, settings);
- }
- await deps.syncLanePermission?.(lane.sessionId, bot.id);
- // A lease may have been superseded during lane setup; revalidate before Agent work.
- await updateExecution(run, 'heartbeat');
+ const lane = await deps.ensureLane({ botId: bot.id, groupId: s.room.id, title: s.room.name,
+ chatAccess: { mode: execution.access_mode, revision: execution.access_revision },
+ ...(run.plan ? { plan: { planId: run.plan.id, workDir: run.workspace?.workDir ?? '', sessionId: run.workspace?.ownerSessionId ?? undefined } } : {}) });
+ if (!lane.ok) throw new Error(lane.errorCode);
+ run.sessionId = lane.sessionId;
+ run.releaseToolAuthority = registerGroupToolAuthority(lane.sessionId, {
+ botId: bot.id, mode: execution.access_mode,
+ sourceGroup: { groupId: s.room.id, name: s.room.name },
+ isCurrent: () => current() && running.get(execution.bot_id) === run && !run.settlement,
+ validate: async () => {
+ // Recheck metadata and the execution lease at the actual tool boundary.
+ // Group administrators cannot grant access to someone else's companion.
+ try {
+ const members = await api<Member[]>(`/conversations/${s.room.id}/members`);
+ const companion = members.find(m => m.id === execution.bot_id && m.kind === 'bot' && m.state === 'joined');
+ const requester = members.find(m => m.id === execution.requester_id && m.state === 'joined');
+ if (!companion || companion.ownerActorId !== selfId || !requester
+ || companion.accessRevision !== execution.access_revision
+ || (execution.access_mode === 'owner' ? requester.ownerActorId !== selfId : companion.guestAccess !== 'tools'))
+ throw new GroupToolAuthorizationError();
+ await updateExecution(run, 'heartbeat');
+ } catch (error) {
+ if (error instanceof ChatResponseError && [401, 403, 404, 409, 410].includes(error.status))
+ throw new GroupToolAuthorizationError();
+ throw error;
+ }
+ },
+ });
+ if (run.plan && run.workspace?.ownerSessionId) {
+ const settings = workspaces().read(s.room.id)!;
+ const key = `${run.plan.id}:${execution.access_mode}:${execution.access_revision}`;
+ run.workspace = { ...run.workspace, ownerSessionId: null };
+ settings.plans[key] = run.workspace; settings.plans[run.plan.id] = run.workspace;
+ workspaces().save(s.room.id, settings);
+ }
+ await deps.syncLanePermission?.(lane.sessionId, bot.id);
+ return lane;
+ })();
+ const contextRead = (async () => {
+ const history = await historyRead;
+ let page = [...history];
+ if (eventSource && !history.some(message => message.id === eventSource.id)) history.push(eventSource);
+ const plan = planRead ? (await planRead).find(p => p.id === execution.plan_id) : undefined;
+ if (plan) {
+ const missing = [...new Set([plan.source_message_id, ...plan.steps.flatMap(step => step.resultMessageId ? [step.resultMessageId] : []), ...(plan.note_message_ids ?? [])])]
+ .filter(messageId => !history.some(message => message.id === messageId));
+ history.push(...settledValues(await settleBounded(missing, TURN_DOWNLOAD_CONCURRENCY,
+ messageId => api<Message>(`/conversations/${s.room.id}/messages/${id.parse(messageId)}`))));
+ }
+ // The request is identified by the execution, not by recency. The mixed
+ // room page carries no Thread structure, so a Thread request also reads its
+ // root and replies explicitly, even when they predate the bounded page.
+ const source = run.context!.kind === 'message'
+ ? history.find(message => message.id === execution.source_message_id) ?? await readMessage(s.room.id, execution.source_message_id)
+ : undefined;
+ if (source?.origin === 'system') throw new Error('INVALID_EXECUTION_TRIGGER');
+ const threadRootId = source?.threadRootId ?? null;
+ let thread: { root?: Message; replies: Message[]; earlierRepliesOmitted: boolean; background: Message[] } | undefined;
+ if (threadRootId) {
+ const repliesRead = api<Message[]>(`/conversations/${s.room.id}/messages?threadRootId=${id.parse(threadRootId)}&limit=100&before=${contextBefore}`);
+ // Read the main timeline on its own: busy Threads can fill the mixed page.
+ const backgroundRead = api<Message[]>(`/conversations/${s.room.id}/messages?limit=${THREAD_BACKGROUND_LIMIT + 1}&before=${contextBefore}`);
+ const rootRead = readMessage(s.room.id, threadRootId);
+ for (const read of [backgroundRead, rootRead]) read.catch(() => undefined);
+ const replies = await repliesRead;
+ const background = await backgroundRead;
+ thread = { root: await rootRead, replies, earlierRepliesOmitted: replies.length >= 100,
+ background: background.filter(message => message.id !== threadRootId).slice(0, THREAD_BACKGROUND_LIMIT) };
+ if (source && !replies.some(message => message.id === source.id)) replies.push(source);
+ }
+ const focusMessages = [source, thread?.root, ...(thread?.replies ?? [])].flatMap(message => message ? [message] : []);
+ const focus = new Set(focusMessages.map(message => message.id));
+ // Text stays bounded, but unseen attachments may precede the latest text page.
+ // The server watermark is scoped to this bot/grant/plan step and advances only on success.
+ const attachmentHistory = [...history, ...[...focusMessages, ...(thread?.background ?? [])].filter(message => !history.some(known => known.id === message.id))];
+ const after = BigInt(execution.attachment_after_seq ?? '0');
+ while (execution.attachment_after_seq !== undefined && page.length === 100) {
+ const before = page.reduce((min, m) => BigInt(m.seq) < min ? BigInt(m.seq) : min, contextBefore);
+ if (before <= after + 1n) break;
+ page = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${before}`);
+ attachmentHistory.push(...page);
+ }
+ // Downloads share the media cache with other consumers. Start them only after the
+ // lane is ready, rather than cancelling a shared download on setup failure.
+ await laneSetup;
+ const attachments: BotGroupAttachment[] = [];
+ const missingAttachments: string[] = [];
+ // Attach a bounded newest set, and retain the names of older files in context.
+ // The request and its Thread come first so the cap cannot drop the files under discussion.
+ // A Thread request never carries other Threads' files, and its own Thread's files are
+ // offered again regardless of the watermark, which only records a successful turn.
+ const mediaDelivery = new Map<string, 'included' | 'not-included'>();
+ const order = (message: Message) => focus.has(message.id) ? 1 : 0;
+ const candidates: Array<{ mediaId: string; name: string }> = [];
+ for (const message of attachmentHistory.sort((a, b) => order(b) - order(a) || (BigInt(a.seq) < BigInt(b.seq) ? 1 : -1))) for (const block of message.content) {
+ if (thread && message.threadRootId && !focus.has(message.id)) continue;
+ if (message.deleted || block.type !== 'media' || !block.mediaId || mediaDelivery.has(block.mediaId)) continue;
+ if (BigInt(message.seq) <= after && !(thread && focus.has(message.id))) continue;
+ mediaDelivery.set(block.mediaId, 'not-included');
+ candidates.push({ mediaId: block.mediaId, name: block.caption ?? block.mediaId });
+ }
+ // The first 40 files in that order that download are attached, as when they were read
+ // one by one; a few download at once. A failed file frees its place for the next one.
+ let next = 0;
+ while (next < candidates.length && attachments.length < 40) {
+ const batch = candidates.slice(next, next + 40 - attachments.length);
+ next += batch.length;
+ const results = await settleBounded(batch, TURN_DOWNLOAD_CONCURRENCY, async candidate => {
+ return media.download(s.room.id, id.parse(candidate.mediaId));
+ });
+ results.forEach((result, index) => {
+ if (result.status === 'fulfilled') { attachments.push(result.value); mediaDelivery.set(batch[index]!.mediaId, 'included'); }
+ else missingAttachments.push(batch[index]!.name);
+ });
+ }
+ for (const candidate of candidates.slice(next)) missingAttachments.push(candidate.name);
+ return { history, source, threadRootId, thread, focusMessages, attachments, missingAttachments, mediaDelivery };
+ })();
+ // Observed here so a read that fails after a failed setup is not an unhandled rejection.
+ contextRead.catch(() => undefined);
+ const lane = await laneSetup;
+ const { history, source, threadRootId, thread, focusMessages, attachments, missingAttachments, mediaDelivery } = await contextRead;
if (!current()) throw new Error('OWNER_CHANGED');
- const history = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${BigInt(execution.context_seq) + 1n}`);
- let page = [...history];
- if (eventSource && !history.some(message => message.id === eventSource.id)) history.push(eventSource);
- if (run.plan) for (const messageId of new Set([run.plan.source_message_id, ...run.plan.steps.flatMap(step => step.resultMessageId ? [step.resultMessageId] : []), ...(run.plan.note_message_ids ?? [])])) {
- if (!history.some(message => message.id === messageId)) history.push(await api<Message>(`/conversations/${s.room.id}/messages/${id.parse(messageId)}`));
- }
- // The request is identified by the execution, not by recency. The mixed
- // room page carries no Thread structure, so a Thread request also reads its
- // root and replies explicitly, even when they predate the bounded page.
- const source = run.context.kind === 'message'
- ? history.find(message => message.id === execution.source_message_id) ?? await readMessage(s.room.id, execution.source_message_id)
- : undefined;
- if (source?.origin === 'system') throw new Error('INVALID_EXECUTION_TRIGGER');
- const threadRootId = source?.threadRootId ?? null;
- let thread: { root?: Message; replies: Message[]; earlierRepliesOmitted: boolean; background: Message[] } | undefined;
- if (threadRootId) {
- const before = BigInt(execution.context_seq) + 1n;
- const replies = await api<Message[]>(`/conversations/${s.room.id}/messages?threadRootId=${id.parse(threadRootId)}&limit=100&before=${before}`);
- // Read the main timeline on its own: busy Threads can fill the mixed page.
- const background = await api<Message[]>(`/conversations/${s.room.id}/messages?limit=${THREAD_BACKGROUND_LIMIT + 1}&before=${before}`);
- thread = { root: await readMessage(s.room.id, threadRootId), replies, earlierRepliesOmitted: replies.length >= 100,
- background: background.filter(message => message.id !== threadRootId).slice(0, THREAD_BACKGROUND_LIMIT) };
- if (source && !replies.some(message => message.id === source.id)) replies.push(source);
- }
- const focusMessages = [source, thread?.root, ...(thread?.replies ?? [])].flatMap(message => message ? [message] : []);
- const focus = new Set(focusMessages.map(message => message.id));
- // Text stays bounded, but unseen attachments may precede the latest text page.
- // The server watermark is scoped to this bot/grant/plan step and advances only on success.
- const attachmentHistory = [...history, ...[...focusMessages, ...(thread?.background ?? [])].filter(message => !history.some(known => known.id === message.id))];
- const after = BigInt(execution.attachment_after_seq ?? '0');
- while (execution.attachment_after_seq !== undefined && page.length === 100) {
- const before = page.reduce((min, m) => BigInt(m.seq) < min ? BigInt(m.seq) : min, BigInt(execution.context_seq) + 1n);
- if (before <= after + 1n) break;
- page = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${before}`);
- attachmentHistory.push(...page);
- }
- const attachments: BotGroupAttachment[] = [];
- const missingAttachments: string[] = [];
- // Attach a bounded newest set, and retain the names of older files in context.
- // The request and its Thread come first so the cap cannot drop the files under discussion.
- // A Thread request never carries other Threads' files, and its own Thread's files are
- // offered again regardless of the watermark, which only records a successful turn.
- const mediaDelivery = new Map<string, 'included' | 'not-included'>();
- const order = (message: Message) => focus.has(message.id) ? 1 : 0;
- for (const message of attachmentHistory.sort((a, b) => order(b) - order(a) || (BigInt(a.seq) < BigInt(b.seq) ? 1 : -1))) for (const block of message.content) {
- if (thread && message.threadRootId && !focus.has(message.id)) continue;
- if (message.deleted || block.type !== 'media' || !block.mediaId || mediaDelivery.has(block.mediaId)) continue;
- if (BigInt(message.seq) <= after && !(thread && focus.has(message.id))) continue;
- mediaDelivery.set(block.mediaId, 'not-included');
- if (attachments.length >= 40) { missingAttachments.push(block.caption ?? block.mediaId); continue; }
- try { attachments.push(await media.download(s.room.id, id.parse(block.mediaId))); mediaDelivery.set(block.mediaId, 'included'); }
- catch { missingAttachments.push(block.caption ?? block.mediaId); }
- }
// A quote resolves against every message this run read; otherwise its card snapshot stands.
const readMessages = [...history, ...focusMessages, ...(thread?.background ?? [])];
- const promptMessage = (m: Message) => ({ id: m.id, from: m.author.name, kind: m.origin === 'system' ? 'system' : m.author.kind, text: bodyText(m),
- ...(m.threadRootId ? { threadRootId: m.threadRootId } : {}), ...quoteContext(m, readMessages) });
+ const promptMessage = (m: Message) => {
+ const shared = readBotGroupThreadShareCard(m);
+ return { id: m.id, from: m.author.name, kind: m.origin === 'system' ? 'system' : m.author.kind, text: bodyText(m),
+ ...(m.threadRootId ? { threadRootId: m.threadRootId } : {}), ...(shared ? { sharedReplyId: shared.messageId } : {}),
+ ...quoteContext(m, readMessages) };
+ };
// Files of the request and its Thread keep their identity and actual delivery state.
const focusMessage = (m: Message) => {
const files = m.deleted ? [] : m.content.flatMap(block => block.type === 'media' && block.mediaId
@@@ -1768,18 -1573,40 +1846,45 @@@
thread: input => result(async () => {
const i = z.object({ groupId: id, rootId: id, before: z.number().int().positive().optional(), sourceMessageIds: z.array(id).optional() }).parse(input);
i.groupId = await resolveGroup(i.groupId); subscribe(i.groupId);
- const members = await api<Member[]>(`/conversations/${i.groupId}/members`);
- const root = await api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);
- const page = await api<Message[]>(`/conversations/${i.groupId}/messages?threadRootId=${i.rootId}&limit=50${i.before ? `&before=${i.before}` : ''}`);
+ // One round trip; awaited in the former order so the same failure is reported first.
+ const membersRead = api<Member[]>(`/conversations/${i.groupId}/members`);
+ const rootRead = api<Message>(`/conversations/${i.groupId}/messages/${i.rootId}`);
+ const pageRead = api<Message[]>(`/conversations/${i.groupId}/messages?threadRootId=${i.rootId}&limit=50${i.before ? `&before=${i.before}` : ''}`);
+ for (const read of [rootRead, pageRead]) read.catch(() => undefined);
+ const members = await membersRead;
+ const root = await rootRead;
+ const page = await pageRead;
const executionFailures = await failureSnapshot(i.groupId, members, [...(i.sourceMessageIds ?? []), root.id, ...page.map(m => m.id)]);
- return { root: (await messageViews(i.groupId, [root], members))[0], executionFailures,
+ // A share in the main chat can itself be a thread root.
+ const rootViews = await messageViews(i.groupId, [root], members);
+ await decorateThreads(i.groupId, rootViews, [root], page, members, false);
+ return { root: rootViews[0], executionFailures,
replies: await messageViews(i.groupId, page.reverse(), members), hasMore: page.length === 50 };
}),
+ shareToMain: input => result(async () => {
+ const i = z.object({ groupId: id, messageId: id }).strict().parse(input);
+ const room = await resolveGroup(i.groupId);
+ const source = await readMessage(room, i.messageId);
+ if (!source || !isShareableThreadReply(source)) throw new Error('SHARE_UNAVAILABLE');
+ const members = await api<Member[]>(`/conversations/${room}/members`);
+ const author = members.find(member => member.id === source.authorId);
+ const card = buildBotGroupThreadShareCard({ messageId: source.id, threadRootId: source.threadRootId!,
+ authorName: author ? memberName(author) : source.author.name,
+ text: threadPreviewText(source) || threadPreviewAttachments(source, attachmentName).map(file => file.name).join(', ') });
+ try {
+ const posted = await api<{ id: string }>(`/conversations/${room}/messages`, 'POST', {
+ operationId: botGroupThreadShareOperationId(source.id), content: [card],
+ // Addressed to the sharer alone: the server never widens a directed message, so
+ // re-posting starts no companion round and the quoted @names stay inert.
+ mentions: [selfId],
+ });
+ changed(room); return { messageId: posted.id, alreadyShared: false };
+ } catch (error) {
+ // The same person shared this reply before and its text has changed since.
+ if (error instanceof ChatResponseError && error.message === 'OPERATION_CONFLICT') { changed(room); return { messageId: null, alreadyShared: true }; }
+ throw error;
+ }
+ }),
reply: input => result(async () => {
const i = z.object({ groupId: id, rootId: id, text: z.string().trim().min(1).max(8000), clientId: operationId,
mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()).max(100) }) }).parse(input);
@@@ -2147,7 -1941,7 +2259,7 @@@
continuePlan: input => safe(() => actPlan(input, 'continue')), retryPlan: input => safe(() => actPlan(input, 'retry')),
editPlanStep: input => safe(() => actPlan(input, 'reassign')),
dispose: () => {
- disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); clearTimeout(claimTrigger); socket?.close();
- disposed = true; threads.dispose(); clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();
++ 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);
attachmentRefreshes.clear();
diff --cc apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index 51be6d6f9c,ae083fecee..b7b2c30e9f
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@@ -51,7 -54,10 +51,8 @@@ import { toast } from '@/lib/toast'
import { ControlledBanner, useControlledBy, useComposerCollapsed } from '@/features/remote-device/ControlledBanner';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import type {
- BotGroupAttachment,
- BotGroupDetail,
BotGroupMemberView,
++ BotGroupDetail,
BotGroupMessageView,
BotGroupPlanAction,
BotGroupPlanStepView,
@@@ -60,21 -67,26 +61,22 @@@
} from '../../../shared/botGroupChat';
import { botGroupQuoteFromMessage, isBotGroupMessageQuotable, resolveBotGroupQuote } from '../../../shared/botGroupChat';
import { useRegisterContentHeader } from '../feature-context';
-import { BotAvatar } from './BotAvatar';
-import { BotGenerationLabel } from './BotGenerationLabel';
import { BotGroupAvatarStack } from './BotGroupAvatars';
import { botGroupAttachmentScope, refreshPendingBotGroupAttachments } from './botGroupAttachments';
-import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
import { BotGroupComposer } from './BotGroupComposer';
-import { BotGroupQuoteBlock } from './BotGroupQuote';
-import { ChatInviteButton, ChatMessageActions, messageReactionRevision } from './ChatServerControls';
++import { findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
+import {
+ BotGroupHeaderStatusText,
+ BotGroupProgressStrip,
+ BotGroupSpeakerInteraction,
+ BotGroupSpeakingLine,
+ botGroupHeaderStatus,
+ type BotGroupLiveSpeaker,
+} from './BotGroupLiveStatus';
+import { ChatInviteButton, messageReactionRevision } from './ChatServerControls';
import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';
-import { BotGroupThreadPreview, BotGroupThreadShareQuote, botGroupThreadShareLabel, findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
-import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';
-import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { BotGroupTaskCard } from './BotGroupTaskCard';
-import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
import {
- BotGroupHandoffFiles,
BotGroupOrganizerTag,
- BotGroupPlanCard,
- BotGroupPlanEndDivider,
BotGroupPlanFollowUpRow,
type BotGroupFollowUpAction,
type BotGroupPlanCardAction,
@@@ -235,49 -242,46 +237,55 @@@ function BotGroupChatContent({ groupId
discardBotGroupOutbox(groupId);
if (shown.kind === 'ready' && shown.group.id !== groupId) discardBotGroupOutbox(shown.group.id);
};
- const load = async (additionalSources: string[] = []) => {
- const version = ++requestVersion;
+ /** Bumped when a read starts (and on delete): re-checks spawned by older reads stop. */
+ let version = 0;
+ let inFlight = false;
+ let queued: { sources: string[]; changed: string[] } | null = null;
+ const run = async (additionalSources: string[], changedIds: string[]) => {
+ inFlight = true;
+ const current = ++version;
+ const readToken = beginBotGroupTimelineRead();
const owner = getDataOwnerGeneration();
const api = botGroupApi();
- const isCurrent = () =>
- !cancelled && version === requestVersion && isDataOwnerGenerationCurrent(owner);
- if (!api || !groupId) {
- if (isCurrent()) setState({ kind: groupId ? 'error' : 'missing' });
- return;
- }
- const readToken = beginBotGroupTimelineRead();
+ const isCurrent = () => !cancelled && current === version && isDataOwnerGenerationCurrent(owner);
+ // Reads run one at a time, so a result is never older than what is on screen; only the
+ // account (data owner) or a delete can make it stale.
+ const isApplicable = () => !cancelled && isDataOwnerGenerationCurrent(owner) && current <= version;
try {
+ if (!api || !groupId) {
+ if (isApplicable()) setState({ kind: groupId ? 'error' : 'missing' });
+ return;
+ }
const displayed = stateRef.current;
- const sourceMessageIds = [...new Set([...(displayed.kind === 'ready' && displayed.group.id === groupId
+ const shown = displayed.kind === 'ready' && displayed.group.id === groupId;
+ const sourceMessageIds = [...new Set([...(shown
? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
- const result = sourceMessageIds.length ? await api.getBotGroup(groupId, { sourceMessageIds }) : await api.getBotGroup(groupId);
+ // Older pages are not re-read, so their shares ask for the reply's current state.
+ const shownShares = shown ? botGroupShownShares(displayed.older) : [];
+ const result = sourceMessageIds.length || shownShares.length
+ ? await api.getBotGroup(groupId, { sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })
+ : await api.getBotGroup(groupId);
- if (!isCurrent()) return;
+ if (!isApplicable()) return;
if (result.ok) {
readOwner.current = owner;
- setState((previous) =>
- previous.kind === 'ready'
- ? { ...previous, group: result.group, older: applyBotGroupThreadShareUpdates(previous.older, result.group), readToken }
- : {
- kind: 'ready',
- group: result.group,
- older: [],
- olderPlans: [],
- olderHasMore: result.group.hasMoreBefore,
- readToken,
- },
- );
const shown = stateRef.current;
+ setState((previous) => {
+ if (previous.kind !== 'ready') {
+ return { kind: 'ready', group: result.group, older: [], olderPlans: [], olderHasMore: result.group.hasMoreBefore, readToken };
+ }
+ const merged = mergeBotGroupLatestPage(previous, result.group);
++ merged.older = applyBotGroupThreadShareUpdates(merged.older, result.group);
+ return { kind: 'ready', ...merged, readToken };
+ });
if (shown.kind === 'ready') {
- const targets = quotedOlderOriginals(shown.older, result.group.messages);
- if (targets.length > 0) void recheckQuotedOriginals(api, targets, isCurrent);
+ const quoted = quotedOlderOriginals([...shown.older, ...shown.group.messages], result.group.messages);
+ // A message changed here (a reaction) that sits only on an opened older page: the
+ // latest page cannot refresh its copy, so its page is re-read like a quoted original's.
+ const latestIds = new Set(result.group.messages.map((message) => message.id));
+ const changed = shown.older.filter((message) => changedIds.includes(message.id)
+ && !latestIds.has(message.id) && !quoted.some((target) => target.id === message.id));
+ const targets = [...quoted, ...changed].sort((a, b) => b.sequence - a.sequence);
+ if (targets.length > 0) void recheckOlderCopies(api, targets, isCurrent);
}
if (displayed.kind === 'ready' && displayed.group.id === groupId && result.group.messages.length > 0) {
const latestFrom = Math.min(...result.group.messages.map((message) => message.sequence));
@@@ -409,8 -390,26 +426,22 @@@
() => (state.kind === 'ready' ? projectBotGroupExecutionFailures(mergeBotGroupMessages(state.older, state.group.messages), state.group.executionFailures) : []),
[state],
);
+ /** Thread replies already in the loaded main chat, with the share to reveal. */
+ const sharedReplies = useMemo(() => {
+ const shares = new Map<string, { messageId: string; bySelf: boolean }>();
- for (const message of messages) {
++ for (const message of realMessages) {
+ const share = message.threadShare;
+ // Only a share the server resolved inside its claimed thread stands for that reply.
+ if (share?.status !== 'available') continue;
+ const bySelf = message.authorKind === 'user' && message.isSelf !== false;
+ // Prefer the reader's own share: it is the one a repeat would return.
+ if (!shares.has(share.messageId) || bySelf) shares.set(share.messageId, { messageId: message.id, bySelf });
+ }
+ return shares;
- }, [messages]);
++ }, [realMessages]);
+ // The composer sends under the group's own id; an older local route can still lead here.
const outboxGroupId = group?.id ?? groupId;
const outbox = useBotGroupOutbox(outboxGroupId);
- // Settle receipts only once the read that shows them is on screen, so a pending bubble
- // never disappears a frame before its real message appears. Older pages count too: a
- // message pushed off the latest page settles its previews once 查看更早的消息 shows it.
- // A receipt for a message the timeline already shows settles when it comes back.
useLayoutEffect(() => {
if (state.kind === 'ready') noteBotGroupTimeline(outboxGroupId, mergeBotGroupMessages(state.older, state.group.messages), state.readToken);
}, [outboxGroupId, state, outbox]);
@@@ -519,8 -454,8 +550,10 @@@
const separator = t('bots.groupChat.memberSeparator');
const [threadRootId, setThreadRootId] = useState<string | null>(null);
+ const threadRootIdRef = useRef(threadRootId);
+ threadRootIdRef.current = threadRootId;
+ /** A reply to bring into view when a main-chat share opens its thread. */
+ const [threadFocus, setThreadFocus] = useState<{ messageId: string; nonce: number } | null>(null);
const threadOpenerRef = useRef<HTMLElement | null>(null);
const threadLayoutRef = useRef<HTMLDivElement>(null);
const threadHeaderRef = useRef<HTMLDivElement>(null);
@@@ -554,6 -489,28 +587,14 @@@
threadCloseAnimationRef.current?.cancel();
threadCloseAnimationRef.current = null;
}, [threadRootId]);
- const openThread = useCallback((rootId: string, focusMessageId?: string) => {
- threadOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
- if (threadCloseAnimationRef.current) {
- threadCloseAnimationRef.current.cancel();
- threadCloseAnimationRef.current = null;
- const panel = threadLayoutRef.current?.querySelector('aside');
- if (panel) panel.inert = false;
- if (rootId === threadRootId) {
- (panel?.querySelector<HTMLTextAreaElement>('textarea:not(:disabled)') ?? panel?.querySelector<HTMLButtonElement>('header button'))?.focus();
- }
- }
- setThreadFocus(focusMessageId ? { messageId: focusMessageId, nonce: Date.now() } : null);
- setThreadRootId(rootId);
- }, [threadRootId]);
+ /** From a thread reply back to where it was shared in the main chat. */
+ const revealMainMessage = useCallback((messageId: string) => {
+ const target = findThreadMessageElement(contentRef.current, messageId);
+ if (!target) return false;
+ stickToBottomRef.current = false;
+ flashThreadTarget(target);
+ return true;
+ }, []);
useEffect(() => {
if (!group?.serverBacked || !threadRootId) return;
const onKeyDown = (event: KeyboardEvent) => {
@@@ -862,72 -778,6 +903,73 @@@
}
};
+ // Stable handlers for the memoized rows; each reads the latest page state through refs.
+ const actionsRef = useRef({ locateQuoted, continueRound, runPlanAction, editPlanStep });
+ actionsRef.current = { locateQuoted, continueRound, runPlanAction, editPlanStep };
+ const onLocateQuote = useCallback((quote: BotGroupQuoteView) => void actionsRef.current.locateQuoted(quote), []);
+ const onContinue = useCallback(() => void actionsRef.current.continueRound(), []);
+ const onPlanAction = useCallback((action: 'start' | 'dismiss', planId: string) => void actionsRef.current.runPlanAction(action, planId), []);
+ const onEditStep = useCallback((planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) =>
+ void actionsRef.current.editPlanStep(planId, step, action, botId), []);
+ const onChanged = useCallback((messageId: string) => loadRef.current([], [messageId]), []);
+ const onQuote = useCallback((messageId: string) => {
+ const message = messageByIdRef.current.get(messageId);
+ if (message) setQuoteDraft(botGroupQuoteFromMessage(message));
+ }, []);
- const onOpenThread = useCallback((messageId: string) => {
++ const onOpenThread = useCallback((messageId: string, focusMessageId?: string) => {
+ threadOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ if (threadCloseAnimationRef.current) {
+ threadCloseAnimationRef.current.cancel();
+ threadCloseAnimationRef.current = null;
+ const panel = threadLayoutRef.current?.querySelector('aside');
+ if (panel) panel.inert = false;
+ if (messageId === threadRootIdRef.current) {
+ (panel?.querySelector<HTMLTextAreaElement>('textarea:not(:disabled)') ?? panel?.querySelector<HTMLButtonElement>('header button'))?.focus();
+ }
+ }
+ setThreadRootId(messageId);
++ setThreadFocus(focusMessageId ? { messageId: focusMessageId, nonce: Date.now() } : null);
+ }, []);
+ const onSending = useCallback(() => { stickToBottomRef.current = true; }, []);
+
+ const planById = useMemo(() => new Map(plans.map((plan) => [plan.id, plan])), [plans]);
+ const layout = useMemo(() => layoutBotGroupTimeline(rows), [rows]);
+ const stepNumbers = useMemo(() => botGroupHandoffStepNumbers(realMessages, planById), [realMessages, planById]);
+ /** Finish time of each done step (1-based) per plan, from the hand-off messages; stable per content. */
+ const doneAtCache = useRef(new Map<string, { key: string; value: ReadonlyMap<number, number> }>());
+ const planDoneAt = useMemo(() => {
+ const byPlan = new Map<string, Map<number, number>>();
+ for (const message of realMessages) {
+ const number = stepNumbers.get(message.id);
+ if (number === undefined || !message.planId) continue;
+ const entry = byPlan.get(message.planId) ?? new Map<number, number>();
+ entry.set(number, message.createdAt);
+ byPlan.set(message.planId, entry);
+ }
+ const next = new Map<string, { key: string; value: ReadonlyMap<number, number> }>();
+ for (const [planId, value] of byPlan) {
+ const key = JSON.stringify([...value]);
+ const cached = doneAtCache.current.get(planId);
+ next.set(planId, cached && cached.key === key ? cached : { key, value });
+ }
+ doneAtCache.current = next;
+ return next;
+ }, [realMessages, stepNumbers]);
+
+ const openPlan = group ? openBotGroupPlan({ openPlan: group.openPlan, plans }) : null;
+ const runningStep = runningBotGroupPlanStep(openPlan);
+ const speakers = useMemo<BotGroupLiveSpeaker[]>(() => (running && group
+ ? group.round.speakers.flatMap((speaker) => {
+ const member = memberById.get(speaker.botId);
+ return member ? [{ member, displayName: botGroupMemberDisplayName(member), sessionId: speaker.sessionId, activity: speaker.activity }] : [];
+ })
+ : []), [running, group, memberById]);
+ const stepSpeaker = runningStep
+ ? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === runningStep.step.botId)
+ : undefined;
+ const stepLive = useAgentIslandActivity(stepSpeaker?.sessionId ?? '');
+ const planRunningSince = runningStep ? stepLive?.startedAtMs ?? runningStep.plan.updatedAt : null;
+
const resetDrag = () => {
dragCounterRef.current = 0;
setDragOver(false);
diff --cc apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
index f5ff0237b9,303606862a..aaeadaaab2
--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
@@@ -36,6 -31,6 +36,7 @@@ import
useMemo,
useRef,
useState,
++ type ReactNode,
type ClipboardEvent,
type KeyboardEvent,
} from 'react';
@@@ -173,54 -117,29 +174,56 @@@ export function BotGroupComposer(
dragOver = false,
quote = null,
onQuoteChange,
+ sendReply,
+ onSendStart,
+ onSendSettled,
+ onSent,
onSending,
++ footerStart,
}: {
groupId: string;
+ /** `thread`: a 话题's reply box (no 「+」 menu, attachments or quotes). */
+ mode?: 'group' | 'thread';
+ /** Where the unsent text is kept (the group's attachment scope, or the 话题's own key). */
+ draftKey: string;
members: readonly BotGroupMemberView[];
running: boolean;
+ /** Archived group: nothing can be sent. */
+ disabled?: boolean;
/** The group's open plan, for placeholders and the 「安排分工」 gate. */
planState?: BotGroupComposerPlanState | null;
- attachments: BotGroupComposerAttachments;
+ attachments?: BotGroupComposerAttachments;
/** Scope for writing annotated images before send (see botGroupAttachmentScope). */
- attachmentScope: string;
+ attachmentScope?: string;
/** Files are being dragged over the page: the card shows the same drop hint as a task's. */
dragOver?: boolean;
/** 引用回复 waiting to go with the next message, and how its original reads right now. */
quote?: { view: BotGroupQuoteView; display: BotGroupQuoteDisplay } | null;
onQuoteChange?: (quote: BotGroupQuoteView | null) => void;
- /** Called when a message enters the outbox, so the view can follow it to the bottom. */
- onSending: () => void;
+ /** Thread mode: posts the reply. */
+ sendReply?: (input: { text: string; clientId: string; mentions: BotGroupMention }) => Promise<ChatServerResult<{ messageId: string }>>;
+ /** The message is on its way: show its local copy now. */
+ onSendStart?: (message: BotGroupOutgoingMessage) => void;
+ /** Main answered (or the send failed before reaching it). */
+ onSendSettled?: (clientId: string, outcome: BotGroupSendOutcome) => void;
+ /** Called after main accepted the message, so the view can re-read at once. */
+ onSent?: () => void;
+ /** Main-group send was queued; keep the timeline at the bottom. */
+ onSending?: () => void;
++ footerStart?: (sending: boolean) => ReactNode;
}) {
const { t } = useTranslation();
- const [text, setText] = useState('');
+ const thread = mode === 'thread';
+ const [text, setText] = useState(() => botGroupDraftText(getDraft(draftKey)?.text));
+ const [error, setError] = useState('');
const [stopping, setStopping] = useState(false);
+ /** Thread send in flight; group sends are owned by the outbox. */
+ const [sending, setSending] = useState(false);
/** 「分工」 tag from 「+」→「安排分工」: this message goes to the organizer for a plan. */
const [division, setDivision] = useState(false);
+ const divisionRef = useRef(division);
+ divisionRef.current = division;
+ const groupAttemptRef = useRef<{ clientId: string; signature: string } | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@@@ -609,7 -430,6 +612,8 @@@
/>
<div className={BOT_GROUP_COMPOSER_FOOTER}>
<div className={BOT_GROUP_COMPOSER_FOOTER_START}>
++ {footerStart?.(sending)}
+ {thread ? null : (<>
<input
ref={fileInputRef}
type="file"
diff --cc apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
index 4ddf4d6db5,0000000000..d551bbff18
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
@@@ -1,485 -1,0 +1,510 @@@
+/**
+ * 群聊时间线的一行(主时间线与话题面板共用),Telegram / Slack 式的紧凑排版:
+ *
+ * - 自己的消息靠右、浅色气泡;其他人(伙伴与别的人)一律靠左平铺:28px 头像 + 名字
+ * (text-13)+ 时刻(text-11),正文在下。同一作者五分钟内的连续消息合并:后续行不再带
+ * 头像和名字,时刻只在悬停时出现在左侧槽位。
+ * - 引用块在正文上方,表情回应在正文下方;消息操作栏(复制、分享、引用回复、话题、表情、
+ * 时间)悬停时浮在右上角,键盘聚焦与触屏时常显。
+ * - @ 点名在所有消息里都高亮:正文仍交给 MarkdownRenderer,高亮走 CSS Custom Highlight
+ * (不改 Markdown 的 DOM,也就不会和 React 抢节点)。
+ * - 轮次结束、分工结束与系统提示是居中的一行小字。
+ *
+ * 行用 `memo` 包住:父组件只在这条消息(或它的引用、安排快照、高亮状态)真的变了时才会
+ * 让它重绘;回调一律是父组件的稳定引用,按消息 id 调用。
+ */
+import { memo, useEffect, useState, useLayoutEffect, useRef, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
- import { CircleAlert, RefreshCcw } from 'lucide-react';
++import { CircleAlert, CornerDownRight, RefreshCcw } from 'lucide-react';
++import { BotGroupThreadPreview, BotGroupThreadShareQuote, botGroupThreadShareLabel } from './BotGroupThreadViews';
+import { toast } from '@/lib/toast';
+import { editBotGroupSend, retryBotGroupSend, type BotGroupOutboxEntry } from './botGroupOutbox';
+
+import { formatBotTimelineClock, formatBotTimelineDate } from '@cindy/maker-shared/botTimeline';
+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
+import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';
+import { Button } from '@/components/ui/button';
+import { SHARE_MESSAGE_ATTR, SHARE_SESSION_ATTR } from '@/lib/shareConversationImage';
+import { cn } from '@/lib/utils';
+import type {
+ BotGroupMemberView,
+ BotGroupPlanStepView,
+ BotGroupPlanView,
+ BotGroupQuoteDisplay,
+ BotGroupQuoteView,
+} from '../../../shared/botGroupChat';
+import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';
+import { BotAvatar } from './BotAvatar';
+import { splitBotGroupMentionSegments } from './botGroupMentions';
+import { botGroupNoticeKey } from './botGroupPresentation';
+import {
+ BotGroupHandoffFiles,
+ BotGroupOrganizerTag,
+ BotGroupPlanCard,
+ BotGroupPlanEndDivider,
+ type BotGroupPlanCardAction,
+} from './BotGroupPlan';
+import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
+import { BotGroupQuoteBlock } from './BotGroupQuote';
+import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
+import { BotGroupTaskCard } from './BotGroupTaskCard';
+import type { BotGroupTimelineMessage } from './BotGroupTimelineModel';
+import { ChatMessageHoverActions, ChatMessageReactions } from './ChatServerControls';
+
+/** Group chat body: one step smaller than a task's reading text, Slack-dense. */
+export const BOT_GROUP_BODY_CLASS = 'text-14 font-normal leading-relaxed';
+
+// ---- @ mention highlight ----------------------------------------------------------------
+
+const MENTION_HIGHLIGHT = 'bot-group-mention';
+const mentionRanges = new Map<object, Range[]>();
+let highlightSyncQueued = false;
+let highlightStyleInstalled = false;
+
+type HighlightRegistry = { set: (name: string, value: unknown) => void; delete: (name: string) => void };
+function highlightApi(): { registry: HighlightRegistry; Highlight: new (...ranges: Range[]) => unknown } | null {
+ const registry = (globalThis as { CSS?: { highlights?: HighlightRegistry } }).CSS?.highlights;
+ const Highlight = (globalThis as { Highlight?: new (...ranges: Range[]) => unknown }).Highlight;
+ return registry && typeof Highlight === 'function' ? { registry, Highlight } : null;
+}
+
+function installHighlightStyle(): void {
+ if (highlightStyleInstalled || typeof document === 'undefined') return;
+ highlightStyleInstalled = true;
+ const style = document.createElement('style');
+ style.dataset.botGroupMention = '';
+ // Same chip colors as the composer's mention chip; both modes follow the tokens.
+ style.textContent = `::highlight(${MENTION_HIGHLIGHT}) { background-color: var(--surface-chip); color: var(--text-primary); }`;
+ document.head.append(style);
+}
+
+function syncMentionHighlight(): void {
+ if (highlightSyncQueued) return;
+ highlightSyncQueued = true;
+ queueMicrotask(() => {
+ highlightSyncQueued = false;
+ const api = highlightApi();
+ if (!api) return;
+ const ranges = [...mentionRanges.values()].flat();
+ if (ranges.length === 0) api.registry.delete(MENTION_HIGHLIGHT);
+ else api.registry.set(MENTION_HIGHLIGHT, new api.Highlight(...ranges));
+ });
+}
+
+function collectMentionRanges(root: HTMLElement, labels: readonly string[]): Range[] {
+ const ranges: Range[] = [];
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) {
+ if (!node.data.includes('@') || node.parentElement?.closest('pre, code')) continue;
+ let offset = 0;
+ for (const segment of splitBotGroupMentionSegments(node.data, labels)) {
+ if (segment.mention) {
+ const range = document.createRange();
+ range.setStart(node, offset);
+ range.setEnd(node, offset + segment.text.length);
+ ranges.push(range);
+ }
+ offset += segment.text.length;
+ }
+ }
+ return ranges;
+}
+
+/** Message text as Markdown, with `@名字` of known members highlighted like a chip. */
+function BotGroupMessageText({ content, mentionLabels }: { content: string; mentionLabels: readonly string[] }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const labelsKey = mentionLabels.join('\u0000');
+ useLayoutEffect(() => {
+ const root = ref.current;
+ if (!root || !content.includes('@') || !highlightApi()) return;
+ installHighlightStyle();
+ const owner = {};
+ const refresh = () => {
+ mentionRanges.set(owner, collectMentionRanges(root, mentionLabels));
+ syncMentionHighlight();
+ };
+ refresh();
+ // Markdown may finish later (code highlighting, lazy blocks); follow its DOM.
+ const observer = typeof MutationObserver === 'undefined' ? null : new MutationObserver(refresh);
+ observer?.observe(root, { childList: true, subtree: true, characterData: true });
+ return () => {
+ observer?.disconnect();
+ mentionRanges.delete(owner);
+ syncMentionHighlight();
+ };
+ // labelsKey stands in for the label array.
+ }, [content, labelsKey]);
+ return (
+ <div ref={ref} className="min-w-0 break-words">
+ <MarkdownRenderer workingDir="" content={content} allowPrivilegedLinks={false} />
+ </div>
+ );
+}
+
+// ---- Pieces ----------------------------------------------------------------------------
+
+/** Quiet pill after an author name (负责人, 第 k 步, 某某的主人). */
+export function BotGroupNameTag({ children }: { children: ReactNode }) {
+ return (
+ <span className="inline-flex min-h-[18px] max-w-[12rem] shrink-0 select-none items-center truncate rounded-full bg-[var(--surface-chip)] px-1.5 py-px text-11 font-medium leading-tight text-[var(--text-secondary)]">
+ {children}
+ </span>
+ );
+}
+
+/** One line per local day; it sticks to the top while that day scrolls by. */
+export function BotGroupDateDivider({ timestamp, locale }: { timestamp: number; locale: string }) {
+ return (
+ <div data-testid="bot-group-date-divider" className="sticky top-1 z-[5] mt-4 flex select-none justify-center first:mt-0">
+ <span className="rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-2.5 py-0.5 text-11 leading-4 text-[var(--text-tertiary)]">
+ {formatBotTimelineDate(timestamp, locale)}
+ </span>
+ </div>
+ );
+}
+
+// ---- The row ---------------------------------------------------------------------------
+
+export interface BotGroupTimelineItemProps {
+ message: BotGroupTimelineMessage;
+ /** Same author as the row above within five minutes: no avatar or name. */
+ continued: boolean;
+ /** Author name as this reader sees it (`伙伴名 (主人昵称)` where it applies). */
+ authorName: string;
+ /** Avatar identity of the author (the organizer on a 安排卡). */
+ avatar?: { name: string; avatar: string | null; avatarUrl?: string | null; avatarColor: string | null };
+ /** Bots a human author brought into the group: 「某某的主人」. */
+ ownerOf?: string;
+ /** 「第 k 步」 on a step hand-off. */
+ stepNumber?: number;
+ members: readonly BotGroupMemberView[];
+ mentionLabels: readonly string[];
+ locale: string;
+ shareScope: string;
+ sharing: boolean;
+ /** Server group id: reactions and the toolbar's reaction picker. */
+ reactionGroupId?: string;
+ /** The message's reaction version (`messageReactionRevision`): who reacted is re-read when it moves. */
+ reactionRevision?: string;
+ quoteDisplay?: BotGroupQuoteDisplay;
+ onLocateQuote?: (quote: BotGroupQuoteView) => void;
+ onQuote?: (messageId: string) => void;
- onOpenThread?: (messageId: string) => void;
++ onOpenThread?: (messageId: string, focusMessageId?: string) => void;
++ menuActions?: Parameters<typeof ChatMessageHoverActions>[0]['menuActions'];
++ footer?: ReactNode;
+ /** This client changed the message (a reaction): the timeline refreshes its copy. */
+ onChanged: (messageId: string) => void;
+ highlighted?: boolean;
+ /** Focusable only as a jump target, so a click elsewhere keeps its usual focus. */
+ focusable?: boolean;
+ /** Arrived while the reader was watching: fade in (opacity only). */
+ entering?: boolean;
+ // Round and plan pieces; the Thread panel leaves them out.
+ canContinue?: boolean;
+ continuing?: boolean;
+ onContinue?: () => void;
+ plan?: BotGroupPlanView;
+ planActionable?: boolean;
+ planReassignable?: boolean;
+ planPending?: BotGroupPlanCardAction | null;
+ /** Live start of the plan's running step (its Session's turn), for the elapsed time. */
+ planRunningSince?: number | null;
+ /** Finish time of each done step (1-based), read off its hand-off message. */
+ planDoneAt?: ReadonlyMap<number, number>;
+ onPlanAction?: (action: 'start' | 'dismiss', planId: string) => void;
+ readOnly?: boolean;
+ onEditStep?: (planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
+}
+
+function Row({ message, highlighted, focusable, entering, block, children }: {
+ message: BotGroupTimelineMessage; highlighted?: boolean; focusable?: boolean; entering?: boolean;
+ /** Space above: a new author block, a merged line, or a compact system line. */
+ block: 'author' | 'continued' | 'system';
+ children: ReactNode;
+}) {
+ return (
+ <div
+ data-bot-group-message-id={message.id}
+ tabIndex={focusable ? -1 : undefined}
+ className={cn(
+ 'rounded-lg outline-none transition-colors first:mt-0',
+ block === 'continued' ? 'mt-0.5' : block === 'author' ? 'mt-3.5' : 'mt-3',
+ entering && 'animate-fade-in motion-reduce:animate-none',
+ highlighted && 'bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+function SystemLine({ children, testId }: { children: ReactNode; testId?: string }) {
+ return (
+ <div data-testid={testId} className="flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">
+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />
+ {children}
+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />
+ </div>
+ );
+}
+
+/** A task card is live only for a member of this group whose teammate is mine; unknown authors are snapshots. */
+export function botGroupTaskOwned(authorBotId: string | null, members: readonly BotGroupMemberView[]): boolean {
+ const author = authorBotId ? members.find((member) => member.botId === authorBotId) : undefined;
+ return author !== undefined && author.isOwned !== false;
+}
+
+function BotGroupTimelineItemImpl(props: BotGroupTimelineItemProps) {
+ const { t } = useTranslation();
+ const { message, continued, authorName, members, mentionLabels, locale, shareScope, sharing } = props;
+ const rowProps = { message, highlighted: props.highlighted, focusable: props.focusable, entering: props.entering };
+
+ if (message.kind === 'round-end') {
+ return (
+ <Row {...rowProps} block="system">
+ <SystemLine>
+ <span>{t('bots.groupChat.timeline.roundEnded')}</span>
+ {props.canContinue && props.onContinue ? (
+ <Button variant="secondary" tone="quiet" size="sm" compact type="button" loading={props.continuing} onClick={props.onContinue}>
+ {t('bots.groupChat.timeline.continue')}
+ </Button>
+ ) : null}
+ </SystemLine>
+ </Row>
+ );
+ }
+ if (message.kind === 'plan-end') {
+ return (
+ <Row {...rowProps} block="system">
+ <BotGroupPlanEndDivider stepCount={props.plan ? props.plan.steps.length : null} />
+ </Row>
+ );
+ }
+ if (message.kind === 'notice' || message.authorKind === 'system') {
+ const name = message.authorName.trim() || authorName;
+ if (isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) {
+ return (
+ <Row {...rowProps} block="system">
+ <BotGroupRuntimeFailureNotice name={name} code={message.runtimeFailureCode} />
+ </Row>
+ );
+ }
+ const key = botGroupNoticeKey(message.noticeCode, message.planId !== null);
+ return (
+ <Row {...rowProps} block="system">
+ <p className="select-none text-center text-12 leading-5 text-[var(--text-tertiary)]">{key ? t(key, { name }) : message.content}</p>
+ </Row>
+ );
+ }
+
+ const shareable = message.kind === 'message' && !message.pending;
+ const shareAttrs = shareable ? { [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id } : {};
+ const hasText = message.content.trim().length > 0;
+ const quote = props.quoteDisplay ? (
+ <BotGroupQuoteBlock
+ display={props.quoteDisplay}
+ onLocate={props.onLocateQuote && message.quote ? () => props.onLocateQuote!(message.quote!) : undefined}
+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
+ />
+ ) : null;
++ const share = message.threadShare;
++ const threadPreview = props.onOpenThread && (message.replyCount ?? 0) > 0 ? (
++ <BotGroupThreadPreview message={message} members={members}
++ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
++ onOpen={() => props.onOpenThread!(message.id)} />
++ ) : null;
++ const shareBody = share ? <>
++ <p className="flex select-none items-center gap-1 text-12 text-[var(--text-tertiary)]">
++ <CornerDownRight size={12} aria-hidden />{botGroupThreadShareLabel(share, t)}</p>
++ <BotGroupThreadShareQuote share={share} members={members}
++ attachments={<BotGroupMessageAttachments attachments={share.attachments} align="start" />}
++ onOpenThread={props.onOpenThread ? () => props.onOpenThread!(share.threadRootId, share.messageId) : undefined} />
++ </> : null;
+ const actions = shareable ? (
+ <ChatMessageHoverActions
+ groupId={props.reactionGroupId}
+ shareScope={shareScope}
+ message={message}
+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
+ onQuote={props.onQuote ? () => props.onQuote!(message.id) : undefined}
+ onReply={props.onOpenThread ? () => props.onOpenThread!(message.id) : undefined}
+ onChanged={props.onChanged}
++ copyText={share ? share.status === 'available' ? share.content : '' : undefined}
++ replyCountShown={Boolean(threadPreview)}
++ menuActions={props.menuActions}
+ />
+ ) : null;
+
+ if (message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false) {
+ return (
+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>
+ <article
+ {...shareAttrs}
+ data-testid={message.outbox ? "bot-group-outbox" : undefined}
+ data-status={message.outbox?.status}
+ aria-busy={message.pending && message.outbox?.status !== 'failed' ? true : undefined}
+ className={cn('group/message relative flex min-w-0 justify-end rounded-lg py-0.5', sharing && 'ml-10')}
+ >
+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}
+ <div className={cn('flex min-w-0 max-w-[78%] flex-col items-end gap-1.5 transition-opacity', message.pending && message.outbox?.status !== 'failed' && 'opacity-60')}>
+ {quote}
- <BotGroupMessageAttachments attachments={message.attachments ?? []} align="end" />
- {hasText ? (
++ {shareBody}
++ {!share && <BotGroupMessageAttachments attachments={message.attachments ?? []} align="end" />}
++ {!share && hasText ? (
+ <div
+ data-testid="bot-group-self-bubble"
+ className={`max-w-full rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3 py-1.5 text-[var(--msg-user-text)] ${BOT_GROUP_BODY_CLASS}`}
+ >
+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />
+ </div>
+ ) : null}
++ {threadPreview}
++ {props.footer}
+ {message.outbox ? <BotGroupOutboxStatus entry={message.outbox} readOnly={props.readOnly} /> : null}
+ {message.pending && !message.outbox ? <span className="sr-only">{t('bots.groupChat.timeline.sending')}</span> : null}
+ {!message.pending ? <ChatMessageReactions groupId={props.reactionGroupId} message={message} members={members} reactionRevision={props.reactionRevision} align="right" onChanged={props.onChanged} /> : null}
+ </div>
+ {actions}
+ </article>
+ </Row>
+ );
+ }
+
+ // A server plan is signed by its human creator; present the organizer without changing authorship.
+ const isPlanCard = message.kind === 'plan';
+ const timed = Number.isFinite(message.createdAt) && message.createdAt > 0;
+ const clock = timed ? formatBotTimelineClock(message.createdAt, locale) : '';
+ const dateTime = timed ? new Date(message.createdAt).toISOString() : undefined;
+ return (
+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>
+ <article
+ {...shareAttrs}
+ className={cn(
+ 'group/message relative -mx-2 flex min-w-0 items-start gap-2.5 rounded-lg px-2 py-0.5 transition-colors hover:bg-[var(--surface-hover-soft)]',
+ sharing && 'ml-8',
+ )}
+ >
+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}
+ <div className="flex w-7 shrink-0 justify-end">
+ {continued ? (
+ <time
+ dateTime={dateTime}
+ className="select-none pt-0.5 text-11 leading-5 tabular-nums text-[var(--text-tertiary)] opacity-0 group-hover/message:opacity-100"
+ >
+ {clock}
+ </time>
+ ) : (
+ <BotAvatar bot={props.avatar ?? { name: authorName, avatar: null, avatarColor: null }} size="sm" />
+ )}
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ {!continued ? (
+ <span className="flex min-w-0 select-none items-baseline gap-1.5">
+ <span className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{authorName}</span>
+ {isPlanCard ? <BotGroupOrganizerTag /> : null}
+ {props.stepNumber ? <BotGroupNameTag>{t('bots.groupChat.timeline.stepTag', { count: props.stepNumber })}</BotGroupNameTag> : null}
+ {props.ownerOf ? <BotGroupNameTag>{t('bots.groupChat.ownerOf', { name: props.ownerOf })}</BotGroupNameTag> : null}
+ {timed ? (
+ <time dateTime={dateTime} className="shrink-0 text-11 tabular-nums text-[var(--text-tertiary)]">
+ {clock}
+ </time>
+ ) : null}
+ </span>
+ ) : null}
+ {isPlanCard ? (
+ <div className="mt-1">
+ <BotGroupPlanCard
+ plan={props.plan}
+ members={members}
+ actionable={props.planActionable ?? false}
+ reassignable={props.planReassignable ?? false}
+ pending={props.planPending ?? null}
+ runningSince={props.planRunningSince ?? null}
+ doneAt={props.planDoneAt}
+ locale={locale}
+ onStart={() => { if (message.planId) props.onPlanAction?.('start', message.planId); }}
+ onDismiss={() => { if (message.planId) props.onPlanAction?.('dismiss', message.planId); }}
+ onEditStep={(step, action, botId) => { if (message.planId) props.onEditStep?.(message.planId, step, action, botId); }}
+ />
+ </div>
+ ) : (
+ <div className="flex min-w-0 flex-col gap-1">
+ {quote}
+ {/* A task this teammate started from the group; mine is live where it runs, 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. */}
- {message.task ? (
++ {shareBody}
++ {!share && message.task ? (
+ <BotGroupTaskCard task={message.task} owned={botGroupTaskOwned(message.authorBotId, members)}
+ botId={message.authorBotId} />
+ ) : null}
- {hasText ? (
++ {!share && hasText ? (
+ <div className={`min-w-0 text-[var(--msg-assistant-text)] ${BOT_GROUP_BODY_CLASS}`}>
+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />
+ </div>
+ ) : null}
- <BotGroupMessageAttachments attachments={message.attachments ?? []} align="start" />
++ {!share && <BotGroupMessageAttachments attachments={message.attachments ?? []} align="start" />}
++ {threadPreview}
++ {props.footer}
+ <BotGroupHandoffFiles files={message.files ?? []} workDir={props.plan?.workDir ?? null} />
+ <ChatMessageReactions groupId={props.reactionGroupId} message={message} members={members} reactionRevision={props.reactionRevision} onChanged={props.onChanged} />
+ </div>
+ )}
+ </div>
+ {actions}
+ </article>
+ </Row>
+ );
+}
+
+export const BotGroupTimelineItem = memo(BotGroupTimelineItemImpl);
+
+/** Queue feedback shares the same message row, so receipts do not remount its content. */
+function BotGroupOutboxStatus({ entry, readOnly }: { entry: BotGroupOutboxEntry; readOnly?: boolean }) {
+ const { t } = useTranslation();
+ const sending = entry.status === 'sending';
+ const [slow, setSlow] = useState(false);
+ useEffect(() => {
+ if (!sending) {
+ setSlow(false);
+ return;
+ }
+ const timer = window.setTimeout(() => setSlow(true), 600);
+ return () => window.clearTimeout(timer);
+ }, [sending]);
+ return (
+ <>
+ {sending && slow ? (
+ <p role="status" className="select-none text-12 leading-[1.33] text-[var(--text-tertiary)]">
+ {t('bots.groupChat.outbox.sending')}
+ </p>
+ ) : null}
+ {entry.status === 'failed' ? (
+ <div role="alert" className="flex flex-wrap items-center justify-end gap-2">
+ <span className="flex select-none items-center gap-1 text-12 leading-[1.33] text-[var(--text-danger)]">
+ <CircleAlert size={13} aria-hidden className="shrink-0" />
+ {t('bots.groupChat.outbox.failed')}
+ </span>
+ <Button
+ variant="secondary"
+ size="sm"
+ compact
+ type="button"
+ disabled={readOnly}
+ onClick={() => {
+ if (!editBotGroupSend(entry.input.groupId, entry.input.clientId)) toast.warning(t('bots.groupChat.outbox.editBlocked'));
+ }}
+ >
+ {t('bots.groupChat.outbox.edit')}
+ </Button>
+ {entry.retryable !== false ? (
+ <Button variant="secondary" size="sm" compact type="button" disabled={readOnly} onClick={() => retryBotGroupSend(entry.input.groupId, entry.input.clientId)}>
+ <RefreshCcw size={13} />
+ {t('bots.retry')}
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ </>
+ );
+}
diff --cc apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
index 674631339f,cf4a464192..deb50a879c
--- a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
@@@ -40,78 -51,25 +40,81 @@@ function useChatReaction(groupId: strin
} catch { if (isDataOwnerGenerationCurrent(owner)) toast.error(t(key('requestFailed'))); }
finally { busyRef.current = false; setBusy(false); }
}
+ return { busy, react };
+}
+
+interface ChatMessageActionProps {
+ groupId?: string; shareScope: string; message: BotGroupMessageView; align?: 'left' | 'right';
+ /** Who can be named on a reaction badge, and the message's reaction version (see `messageReactionRevision`). */
+ members?: readonly BotGroupMemberView[]; reactionRevision?: string | number;
+ /** 引用回复: a new main-timeline message that quotes this one. */
+ onQuote?: () => void;
+ /** Opens the message's Thread (话题) — 创建话题 before anyone answered, 查看话题 after. */
+ onReply?: () => void;
++ replyCountShown?: boolean;
++ copyText?: string;
++ menuActions?: Parameters<typeof MessageActionBar>[0]['menuActions'];
+ /** The current actor's reaction on `messageId` changed: re-read that message's copy. */
+ onChanged: (messageId: string) => void;
+}
+
+/** The reactions under a message's text; each chip toggles the current actor's reaction. */
+export function ChatMessageReactions({ groupId, message, members, reactionRevision, align = 'left', onChanged }: Pick<ChatMessageActionProps, 'groupId' | 'message' | 'members' | 'reactionRevision' | 'align' | 'onChanged'>) {
+ const { busy, react } = useChatReaction(groupId, message.id, onChanged);
+ if (!message.reactions?.length) return null;
+ return (
+ <div {...{ [SHARE_EXCLUDE_ATTR]: '' }} className={`mt-1 flex flex-wrap items-center gap-1 ${align === 'right' ? 'justify-end' : ''}`}>
+ {message.reactions.map(reaction => (
+ <ChatReactionButton key={reaction.emoji} groupId={groupId} messageId={message.id} reaction={reaction} revision={reactionRevision} members={members}
+ disabled={busy || !groupId} onToggle={() => void react(reaction.emoji, !reaction.me)} />
+ ))}
+ </div>
+ );
+}
+
- function ChatMessageToolbar({ groupId, shareScope, message, align = 'left', onQuote, onReply, onChanged, picker, onPickerChange }: ChatMessageActionProps & {
++function ChatMessageToolbar({ groupId, shareScope, message, align = 'left', onQuote, onReply, replyCountShown, copyText, menuActions, onChanged, picker, onPickerChange }: ChatMessageActionProps & {
+ picker: boolean; onPickerChange: (open: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const { busy, react } = useChatReaction(groupId, message.id, onChanged);
+ return (
- <MessageActionBar copyText={message.content} createdAt={message.createdAt ? new Date(message.createdAt).toISOString() : undefined}
++ <MessageActionBar copyText={copyText ?? message.content} menuActions={menuActions} createdAt={message.createdAt ? new Date(message.createdAt).toISOString() : undefined}
+ align={align} hovered simplifiedBotConversation
+ onShareAsImage={() => shareSelectionStore.enter(shareScope, message.id)}
+ quoteAction={onQuote ? { onClick: onQuote, label: t(key('quoteReply')) } : undefined}
- replyAction={onReply ? { onClick: onReply, count: message.replyCount,
++ replyAction={onReply ? { onClick: onReply, count: replyCountShown ? undefined : message.replyCount,
+ label: message.replyCount ? t(key('openTopic'), { count: message.replyCount }) : t(key('startTopic')) } : undefined}
+ reactionAction={groupId ? { label: t(key('addReaction')), open: picker, onOpenChange: onPickerChange, disabled: busy,
+ content: <div className="grid grid-cols-6 gap-1">{emojiChoices.map(emoji =>
+ <button type="button" key={emoji} className={iconClass} aria-label={emoji}
+ onClick={() => { onPickerChange(false); void react(emoji, !message.reactions?.some(r => r.emoji === emoji && r.me)); }}>{emoji}</button>)}</div>,
+ } : undefined} />
+ );
+}
+
+/**
+ * The message toolbar (copy, share, 引用回复, 话题, reaction, time) floating at the top right of
+ * its message, Slack-style. It shows while the message (`group/message`) is hovered, while
+ * keyboard focus is inside, while its reaction picker is open, and always on touch screens.
+ */
+export function ChatMessageHoverActions(props: ChatMessageActionProps) {
+ const [picker, setPicker] = useState(false);
+ return (
+ <div {...{ [SHARE_EXCLUDE_ATTR]: '' }} data-bot-group-message-actions="" data-open={picker ? '' : undefined}
+ className="pointer-events-none absolute -top-3.5 right-1 z-10 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-1 py-0.5 opacity-0 transition-opacity duration-[var(--motion-fast)] ease-[var(--motion-ease-out)] focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100 data-[open]:pointer-events-auto data-[open]:opacity-100 motion-reduce:transition-none [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
+ <ChatMessageToolbar {...props} picker={picker} onPickerChange={setPicker} />
+ </div>
+ );
+}
+
+/** Reactions and the toolbar stacked under the text, always visible. */
+export function ChatMessageActions(props: ChatMessageActionProps) {
+ const [picker, setPicker] = useState(false);
+ const align = props.align ?? (props.message.isSelf ? 'right' : 'left');
return (
<div {...{ [SHARE_EXCLUDE_ATTR]: '' }} className="mt-1 flex flex-col gap-1">
- {!!message.reactions?.length && <div className={`flex flex-wrap items-center gap-1 ${align === 'right' ? 'justify-end' : ''}`}>
- {message.reactions.map(reaction => (
- <ChatReactionButton key={reaction.emoji} groupId={groupId} messageId={message.id} reaction={reaction} revision={reactionRevision} members={members}
- disabled={busy || !groupId} onToggle={() => void react(reaction.emoji, !reaction.me)} />
- ))}
- </div>}
- <MessageActionBar copyText={copyText ?? message.content} menuActions={menuActions} createdAt={message.createdAt ? new Date(message.createdAt).toISOString() : undefined}
- align={align} hovered simplifiedBotConversation
- onShareAsImage={() => shareSelectionStore.enter(shareScope, message.id)}
- quoteAction={onQuote ? { onClick: onQuote, label: t(key('quoteReply')) } : undefined}
- replyAction={onReply ? { onClick: onReply, count: replyCountShown ? undefined : message.replyCount,
- label: message.replyCount ? t(key('openTopic'), { count: message.replyCount }) : t(key('startTopic')) } : undefined}
- reactionAction={groupId ? { label: t(key('addReaction')), open: picker, onOpenChange: setPicker, disabled: busy,
- content: <div className="grid grid-cols-6 gap-1">{emojiChoices.map(emoji =>
- <button type="button" key={emoji} className={iconClass} aria-label={emoji}
- onClick={() => void react(emoji, !message.reactions?.some(r => r.emoji === emoji && r.me))}>{emoji}</button>)}</div>,
- } : undefined} />
+ <ChatMessageReactions {...props} align={align} />
+ <ChatMessageToolbar {...props} align={align} picker={picker} onPickerChange={setPicker} />
</div>
);
}
diff --cc apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index 6679f9569d,0448307401..58c0b1d81f
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@@ -1,41 -1,68 +1,75 @@@
-import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+/**
+ * 话题(Thread)面板:与主时间线同一套消息行(BotGroupTimelineItem)与密度规则——根消息、
+ * 「N 条回复」分隔、回复按作者五分钟合并;有新回复且读者在底部时跟到底。
+ *
+ * 读取:进入读一次,之后本群每条推送重读;同一时刻只有一个读取在飞,期间的推送合并成一次
+ * 补读。回复用群聊同一个输入框的话题模式(BotGroupComposer `mode="thread"`),发出即乐观插入,
+ * 服务器的回复到了原地替换;失败撤掉、文字放回,原因写在输入框上方。
+ */
- import { Fragment, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
- import { X } from 'lucide-react';
++import { Fragment, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+ import { Check, CornerDownRight, MessageSquareShare, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { SendButton } from '@/components/new-chat/SendButton';
++import { toast } from '@/lib/toast';
++import { cn } from '@/lib/utils';
++import { findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
import { Button } from '@/components/ui/button';
import { Tip } from '@/components/ui/tooltip';
-import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';
-import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';
import { shareSelectionStore, useShareSelectionActive } from '@/components/chat/shareSelectionStore';
-import { SHARE_SESSION_ATTR, SHARE_MESSAGE_ATTR } from '@/lib/shareConversationImage';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
-import { toast } from '@/lib/toast';
-import { cn } from '@/lib/utils';
-import type { BotGroupDetail, BotGroupExecutionFailureView, BotGroupMention, BotGroupMessageView } from '../../../shared/botGroupChat';
-import { isBotGroupRuntimeFailureCode, resolveBotGroupQuote } from '../../../shared/botGroupChat';
+import type { BotGroupDetail, BotGroupExecutionFailureView, BotGroupMessageView } from '../../../shared/botGroupChat';
+import { resolveBotGroupQuote } from '../../../shared/botGroupChat';
+import { botGroupThreadDraftKey, refreshPendingBotGroupAttachments } from './botGroupAttachments';
import { refreshBotGroups } from './botGroupStore';
import { mergeBotGroupMessages, projectBotGroupExecutionFailures } from './botGroupPresentation';
-import { BotAvatar } from './BotAvatar';
-import { BotGroupQuoteBlock } from './BotGroupQuote';
+import { BotGroupComposer, type BotGroupOutgoingMessage, type BotGroupSendOutcome } from './BotGroupComposer';
+import { BotGroupTimelineItem } from './BotGroupTimelineItem';
import {
- BOT_GROUP_COMPOSER_CARD, BOT_GROUP_COMPOSER_COLUMN, BOT_GROUP_COMPOSER_DOCK, BOT_GROUP_COMPOSER_FOOTER, BOT_GROUP_COMPOSER_FOOTER_START, BOT_GROUP_COMPOSER_INPUT,
- fitBotGroupComposerInput, keepBotGroupComposerInputFocus, useRefitBotGroupComposerInputOnResize,
-} from './botGroupComposerChrome';
-import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
-import { refreshPendingBotGroupAttachments } from './botGroupAttachments';
-import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { BotGroupThreadShareQuote, botGroupThreadShareLabel, findThreadMessageElement, flashThreadTarget } from './BotGroupThreadViews';
-import { ChatMessageActions, chatErrorKey, messageReactionRevision } from './ChatServerControls';
-import { useBotGroupMentionPicker } from './useBotGroupMentionPicker';
+ botGroupMemberDisplayName,
+ botGroupOwnedBotNames,
+ layoutBotGroupTimeline,
+ matchBotGroupPendingSends,
+ pendingBotGroupMessage,
+ pendingBotGroupMessageId,
+ stabilizeById,
+ type BotGroupPendingSend,
+ type BotGroupTimelineMessage,
+} from './BotGroupTimelineModel';
+import { chatErrorKey, messageReactionRevision } from './ChatServerControls';
const key = (name: string) => `bots.groupChat.server.${name}`;
-const sameBotGroupMentions = (a: BotGroupMention, b: BotGroupMention) =>
- a.all === b.all && a.botIds.length === b.botIds.length && a.botIds.every((botId, index) => botId === b.botIds[index]);
const api = () => window.electronAPI.maker.chatServer;
+const STICK_TO_BOTTOM_PX = 48;
+ /** Earlier pages read while looking for a reply opened from the main chat. */
+ const FOCUS_PAGE_LIMIT = 5;
+
+ /** Shares of this thread's replies that the main chat has loaded. */
+ export type BotGroupSharedReplies = ReadonlyMap<string, { messageId: string; bySelf: boolean }>;
+
+ /**
+ * Replies that reached a thread while their main-chat copy did not, per group and thread.
+ * Kept outside the panel, and the only copy: a copy may fail after its panel closed, or
+ * while the same thread is open again, and either way that panel shows the retry.
+ * Server groups keep their IDs across accounts, so the queue belongs to one data owner.
+ */
+ const unpostedStore = { owner: getDataOwnerGeneration().dataOwnerId, replies: new Map<string, ReadonlySet<string>>(), listeners: new Set<() => void>() };
+ const NONE_UNPOSTED: ReadonlySet<string> = new Set();
+ function unpostedReplies() {
+ // Same-account runtime repairs advance generation without changing this queue's owner.
+ const owner = getDataOwnerGeneration().dataOwnerId;
+ if (unpostedStore.owner !== owner) { unpostedStore.owner = owner; unpostedStore.replies.clear(); }
+ return unpostedStore.replies;
+ }
+ function updateUnposted(key: string, update: (previous: ReadonlySet<string>) => ReadonlySet<string>) {
+ const queue = unpostedReplies();
+ const next = update(queue.get(key) ?? NONE_UNPOSTED);
+ if (next.size) queue.set(key, next); else queue.delete(key);
+ for (const listener of unpostedStore.listeners) listener();
+ }
+ function useUnposted(key: string): ReadonlySet<string> {
+ return useSyncExternalStore(
+ useCallback(listener => { unpostedStore.listeners.add(listener); return () => { unpostedStore.listeners.delete(listener); }; }, []),
+ () => unpostedReplies().get(key) ?? NONE_UNPOSTED);
+ }
export function animateThreadPanelWidth(panel: HTMLElement, from: string, to: string): Animation | null {
const style = getComputedStyle(panel);
@@@ -51,9 -119,16 +85,17 @@@
* `quoteSources` are the main timeline's verified messages (older pages included), so a
* 话题 root's quote reads the same as it does in the timeline; without them, the latest page.
*/
- export function ChatThreadPanel({ group, rootId, quoteSources = group.messages, onClose }: { group: BotGroupDetail; rootId: string; quoteSources?: readonly BotGroupMessageView[]; onClose: () => void }) {
+ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages, focus, sharedReplies, onRevealShare, onClose }: {
+ group: BotGroupDetail; rootId: string; quoteSources?: readonly BotGroupMessageView[];
+ /** A reply to bring into view; a new nonce repeats the jump. */
+ focus?: { messageId: string; nonce: number } | null;
+ sharedReplies?: BotGroupSharedReplies;
+ /** Scroll the main chat to a share; false when it is not loaded there. */
+ onRevealShare?: (messageId: string) => boolean;
+ onClose: () => void;
+ }) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
+ const locale = i18n.language;
const titleId = useId();
const shareScope = `bot-group:${group.id}:thread:${rootId}`;
const sharing = useShareSelectionActive(shareScope);
@@@ -74,51 -147,47 +116,61 @@@
const [executionFailures, setExecutionFailures] = useState<BotGroupExecutionFailureView[]>([]);
const [replies, setReplies] = useState<BotGroupMessageView[]>([]);
const [hasMore, setHasMore] = useState(false);
- const [text, setText] = useState('');
- const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
+ // Off by default: a reply stays in the thread unless the user asks for both.
+ const [alsoSend, setAlsoSend] = useState(false);
+ const unpostedKey = `${group.id}:${rootId}`;
+ const unposted = useUnposted(unpostedKey);
+ const setUnposted = (update: (previous: ReadonlySet<string>) => ReadonlySet<string>) => updateUnposted(unpostedKey, update);
+ const [posting, setPosting] = useState<ReadonlySet<string>>(new Set());
+ const postingRef = useRef(new Set<string>());
+ /** Shares confirmed in this panel (reply → main-chat message, null when unknown). */
+ const [posted, setPosted] = useState<ReadonlyMap<string, string | null>>(new Map());
- const request = useRef(0);
- const attempt = useRef<{ text: string; roster: BotGroupDetail['members']; id: string; mentions: BotGroupMention } | null>(null);
- const sending = useRef(false);
- const inputRef = useRef<HTMLTextAreaElement>(null);
- const allLabel = t('bots.groupChat.mention.all');
- const allLabels = useMemo(() => [allLabel, '所有人', 'all', 'everyone'], [allLabel]);
- // Same @ picker as the main composer.
- const mention = useBotGroupMentionPicker({ text, members: group.members, textareaRef: inputRef, allLabels, onTextChange: value => {
- setText(value);
- if (attempt.current?.text !== value) attempt.current = null;
- } });
- useLayoutEffect(() => { if (inputRef.current) fitBotGroupComposerInput(inputRef.current); }, [text, sharing]);
- useRefitBotGroupComposerInputOnResize(inputRef, !sharing);
- /** `onAccepted` runs only when this read's result is the one shown. */
- const load = useCallback(async (before?: number, onAccepted?: () => void) => {
- const version = ++request.current, owner = getDataOwnerGeneration();
- const current = () => version === request.current && isDataOwnerGenerationCurrent(owner);
+ const [pendingSends, setPendingSends] = useState<BotGroupPendingSend[]>([]);
+ const repliesRef = useRef(replies);
+ repliesRef.current = replies;
+ const aliveRef = useRef(true);
+ const inFlightRef = useRef(false);
+ const queuedRef = useRef(false);
+
+ /** Lowest sequence of the last latest-page read; replies below it live only on opened older pages. */
+ const latestFloorRef = useRef(Number.POSITIVE_INFINITY);
+
+ /**
+ * Reads the latest page, or the page before `before`. `rereadOnly` re-reads an opened page for a
+ * changed copy: it is not the oldest page, so its `hasMore` says nothing about what is loaded.
+ */
- const read = useCallback(async (before?: number, rereadOnly = false) => {
++ const read = useCallback(async (before?: number, rereadOnly = false, onAccepted?: () => void) => {
+ const owner = getDataOwnerGeneration();
+ const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner);
+ const shown = repliesRef.current;
+ // An older page belongs below the reply it was read from; a latest page that started over
+ // meanwhile dropped that reply, and the page would sit under the new one with the gap still in it.
+ const anchorId = before ? shown[0]?.id : undefined;
+ const anchored = (replies: BotGroupMessageView[]) => !anchorId || replies.some(reply => reply.id === anchorId);
try {
- const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: replies.map(message => message.id) });
+ const result = await api().thread({ groupId: group.id, rootId, before, sourceMessageIds: shown.map(message => message.id) });
if (!current()) return;
if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
- onAccepted?.();
- setRoot(result.root); setError('');
+ setRoot(previous => (previous && JSON.stringify(previous) === JSON.stringify(result.root) ? previous : result.root));
+ setError('');
setExecutionFailures(result.executionFailures ?? []);
- setReplies(previous => mergeBotGroupMessages(previous, result.replies));
- if (before || replies.length === 0) setHasMore(result.hasMore);
- if (before === undefined && result.replies.length > 0) {
- const latestFrom = Math.min(...result.replies.map(message => message.sequence));
- const refreshed = await refreshPendingBotGroupAttachments(replies, latestFrom, async page => {
+ const floor = result.replies.reduce((min, reply) => Math.min(min, reply.sequence), Number.POSITIVE_INFINITY);
+ // A latest page that neither overlaps nor directly adjoins the shown replies may leave a gap:
+ // start over from it, as on first load, so 「查看更早」 reads on from right below it.
+ const gap = !before && result.hasMore && result.replies.length > 0 && shown.length > 0
+ && floor > shown.reduce((max, reply) => Math.max(max, reply.sequence), Number.NEGATIVE_INFINITY) + 1;
+ if (!anchored(repliesRef.current)) return;
++ onAccepted?.();
+ setReplies(previous => (anchored(previous)
+ ? stabilizeById(previous, gap ? result.replies : mergeBotGroupMessages(previous, result.replies))
+ : previous));
+ if (!before) latestFloorRef.current = floor;
+ if (!rereadOnly && (before || shown.length === 0 || gap)) setHasMore(result.hasMore);
+ // A refresh reads only the latest page: replies on opened older pages keep the attachments they
+ // arrived with, so re-read the pages whose attachments were not here yet.
+ if (!before && !gap && result.replies.length > 0) {
+ const refreshed = await refreshPendingBotGroupAttachments(shown, floor, async page => {
const earlier = await api().thread({ groupId: group.id, rootId, before: page });
return earlier.ok && current() ? earlier.replies : null;
});
@@@ -128,126 -197,98 +180,201 @@@
}
}
} catch { if (current()) setError(t(key('requestFailed'))); }
- }, [group.id, rootId, t, replies]);
- const loadRef = useRef(load); loadRef.current = load;
+ }, [group.id, rootId, t]);
+ const readRef = useRef(read);
+ readRef.current = read;
+ /** One refresh in flight; pushes meanwhile collapse into one follow-up read. */
+ const refresh = useCallback(() => {
+ if (inFlightRef.current) { queuedRef.current = true; return; }
+ inFlightRef.current = true;
+ void read().finally(() => {
+ inFlightRef.current = false;
+ if (queuedRef.current && aliveRef.current) {
+ queuedRef.current = false;
+ refresh();
+ }
+ });
+ }, [read]);
+ const refreshRef = useRef(refresh);
+ refreshRef.current = refresh;
useEffect(() => {
- void loadRef.current();
+ aliveRef.current = true;
+ refreshRef.current();
const stop = window.electronAPI.maker.onBotGroupChanged((event, stamp) => {
- if (isDataOwnerPushCurrent(stamp) && event.groupId === group.id) void loadRef.current();
+ if (isDataOwnerPushCurrent(stamp) && event.groupId === group.id) refreshRef.current();
});
- return () => { request.current++; stop(); };
+ return () => { aliveRef.current = false; stop(); };
}, [group.id, rootId]);
+
+ const members = group.members;
+ const mentionLabels = useMemo(
+ () => [t('bots.groupChat.mention.all'), ...members.flatMap((member) => [member.name, botGroupMemberDisplayName(member), member.nickname || member.displayName || member.name])],
+ [members, t],
+ );
+ const memberById = useMemo(() => new Map(members.map((member) => [member.botId, member])), [members]);
+ const separator = t('bots.groupChat.memberSeparator');
+
+ const realReplies = useMemo(() => projectBotGroupExecutionFailures(replies, executionFailures), [replies, executionFailures]);
+ const adoptedKeysRef = useRef(new Map<string, string>());
+ const pendingMatches = useMemo(() => matchBotGroupPendingSends(pendingSends, realReplies, adoptedKeysRef.current), [pendingSends, realReplies]);
+ for (const [clientId, messageId] of pendingMatches) adoptedKeysRef.current.set(messageId, pendingBotGroupMessageId(clientId));
+ useEffect(() => {
+ if (pendingMatches.size === 0) return;
+ setPendingSends((previous) => previous.filter((send) => !pendingMatches.has(send.clientId)));
+ }, [pendingMatches]);
+ const replyRows = useMemo<BotGroupTimelineMessage[]>(
+ () => [...realReplies, ...pendingSends.filter((send) => !pendingMatches.has(send.clientId)).map(pendingBotGroupMessage)],
+ [realReplies, pendingSends, pendingMatches],
+ );
+ const rootRows = useMemo(() => projectBotGroupExecutionFailures(root ? [root] : [], executionFailures), [root, executionFailures]);
+ const layout = useMemo(() => layoutBotGroupTimeline(replyRows), [replyRows]);
+ const lastRealSequenceRef = useRef(0);
+ lastRealSequenceRef.current = realReplies[realReplies.length - 1]?.sequence ?? 0;
+
+ // The root and the latest page come with every refresh; a reply opened through 「加载更早」 sits
+ // below that page, so the page holding it is re-read for its new reaction state.
+ const onChanged = useCallback((messageId: string) => {
+ refreshRef.current();
+ const reply = repliesRef.current.find(candidate => candidate.id === messageId);
+ if (reply && reply.sequence < latestFloorRef.current) void readRef.current(reply.sequence + 1, true);
+ }, []);
+ const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {
+ stickToBottomRef.current = true;
+ setPendingSends((previous) => [
+ ...previous.filter((send) => send.clientId !== message.clientId),
+ { ...message, createdAt: Date.now(), afterSequence: lastRealSequenceRef.current },
+ ]);
+ }, []);
+ const onSendSettled = useCallback((clientId: string, outcome: BotGroupSendOutcome) => {
+ setPendingSends((previous) => outcome.ok
+ ? previous.map((send) => (send.clientId === clientId ? { ...send, messageId: outcome.messageId } : send))
+ : previous.filter((send) => send.clientId !== clientId));
+ }, []);
- const sendReply = useCallback(
- (input: { text: string; clientId: string; mentions: BotGroupMessageView['mentions'] }) => api().reply({ groupId: group.id, rootId, ...input }),
- [group.id, rootId],
- );
+ // A share opened this thread: find its reply, reading back a few pages if needed.
+ const focusSearch = useRef<{ nonce: number; pages: number } | null>(null);
+ useEffect(() => {
+ if (!focus || !replies.length) return;
+ if (focusSearch.current?.nonce !== focus.nonce) focusSearch.current = { nonce: focus.nonce, pages: 0 };
+ const search = focusSearch.current;
+ if (search.pages < 0) return;
+ const target = findThreadMessageElement(contentRef.current, focus.messageId);
- if (target) { search.pages = -1; flashThreadTarget(target); return; }
++ if (target) { stickToBottomRef.current = false; search.pages = -1; flashThreadTarget(target); return; }
+ if (!hasMore || search.pages >= FOCUS_PAGE_LIMIT) { search.pages = -1; return; }
+ // A push refresh may overtake this page; then its replies trigger the next attempt, and
+ // only a page that was merged counts against the limit.
- void loadRef.current(replies[0]?.sequence, () => { search.pages += 1; });
++ void readRef.current(replies[0]?.sequence, false, () => { search.pages += 1; });
+ }, [focus, replies, hasMore]);
+
+ /** One server operation per reply and person, so a retry never posts twice. */
+ async function postToMain(messageId: string, fromComposer: boolean) {
+ if (readOnly || postingRef.current.has(messageId)) return false;
+ postingRef.current.add(messageId); setPosting(new Set(postingRef.current));
+ const owner = getDataOwnerGeneration();
+ const failed = (code?: string) => {
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ if (code === 'SHARE_UNAVAILABLE') {
+ setUnposted(previous => { const next = new Set(previous); next.delete(messageId); return next; });
+ toast.error(t(chatErrorKey(code)));
+ } else if (fromComposer) setUnposted(previous => new Set(previous).add(messageId));
+ else toast.error(t(code ? chatErrorKey(code) : key('requestFailed')));
+ };
+ try {
+ const result = await api().shareToMain({ groupId: group.id, messageId });
+ if (!isDataOwnerGenerationCurrent(owner)) return false;
+ if (!result.ok) { failed(result.errorCode); return false; }
+ setPosted(previous => new Map(previous).set(messageId, result.messageId));
+ setUnposted(previous => { const next = new Set(previous); next.delete(messageId); return next; });
+ if (result.alreadyShared && !fromComposer) toast.info(t(key('thread.alreadyPosted')));
+ refreshBotGroups();
+ return true;
+ } catch { failed(); return false; }
+ finally { postingRef.current.delete(messageId); setPosting(new Set(postingRef.current)); }
+ }
+ async function retryUnposted() {
+ // The queue belongs to the account that started the retry; stop once it is switched.
+ const owner = getDataOwnerGeneration();
+ for (const messageId of unposted) {
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ await postToMain(messageId, true);
+ }
+ }
- async function send() {
- if (readOnly || sending.current || !text.trim()) return;
- sending.current = true; setBusy(true); setError('');
- const owner = getDataOwnerGeneration();
- const toMain = alsoSend;
- // A retry reuses the attempt only for the same text and the same targets (bot-group-chat.md).
- // Targets are re-resolved against the attempt's own roster: a roster refresh alone changes nothing
- // and the host still rejects a departed target; re-picking someone else gets a new clientId.
- const previous = attempt.current;
- const current = previous && previous.text === text && sameBotGroupMentions(mention.resolve(text, previous.roster), previous.mentions)
- ? previous : { text, roster: group.members, id: crypto.randomUUID(), mentions: mention.resolve(text) };
- attempt.current = current;
- try {
- const result = await api().reply({ groupId: group.id, rootId, text: current.text, clientId: current.id,
- mentions: current.mentions });
- if (!isDataOwnerGenerationCurrent(owner)) return;
- if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }
- // The reply exists now; only its main-chat copy may still need a retry.
- setText(''); mention.reset(); attempt.current = null; setAlsoSend(false);
- if (toMain) await postToMain(result.messageId, true);
- void loadRef.current(); refreshBotGroups();
- } catch { if (isDataOwnerGenerationCurrent(owner)) setError(t(key('requestFailed'))); }
- finally { sending.current = false; setBusy(false); }
- }
+ /** The reader's own share wins over another member's, even when only this panel knows it. */
+ const sharedState = (messageId: string) => {
+ const known = sharedReplies?.get(messageId);
+ if (known?.bySelf) return { bySelf: true, shareId: known.messageId };
+ if (posted.has(messageId)) return { bySelf: true, shareId: posted.get(messageId) ?? null };
+ return known ? { bySelf: false, shareId: known.messageId } : null;
+ };
+ /** The share may sit on an older page the main chat has not loaded. */
+ const revealShare = (shareId: string) => {
+ if (!onRevealShare?.(shareId)) toast.info(t(key('thread.shareNotLoaded')));
+ };
++ const sendReply = async (input: { text: string; clientId: string; mentions: BotGroupMessageView['mentions'] }) => {
++ const owner = getDataOwnerGeneration();
++ const toMain = alsoSend;
++ const result = await api().reply({ groupId: group.id, rootId, ...input });
++ if (result.ok && isDataOwnerGenerationCurrent(owner)) {
++ setAlsoSend(false);
++ if (toMain) await postToMain(result.messageId, true);
++ }
++ return result;
++ };
+ const onSent = useCallback(() => { refreshRef.current(); refreshBotGroups(); }, []);
+
+ // Follow new replies while the reader is at the bottom, including content that grows later.
+ const lastKey = replyRows[replyRows.length - 1]?.id ?? '';
+ useLayoutEffect(() => {
+ const element = scrollRef.current;
+ if (element && stickToBottomRef.current) element.scrollTop = element.scrollHeight;
+ }, [lastKey, replyRows.length, root]);
+ useEffect(() => {
+ const scroller = scrollRef.current;
+ const content = contentRef.current;
+ if (!scroller || !content || typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(() => {
+ if (stickToBottomRef.current) scroller.scrollTop = scroller.scrollHeight;
+ });
+ observer.observe(content);
+ observer.observe(scroller);
+ return () => observer.disconnect();
+ }, []);
+
+ const renderRow = (message: BotGroupTimelineMessage, continued: boolean) => {
+ const member = message.authorBotId ? memberById.get(message.authorBotId) : undefined;
+ const authorName = (member && message.authorKind !== 'system' ? botGroupMemberDisplayName(member) : '') || message.authorName || member?.name || '';
+ const owned = message.authorKind === 'user' && message.isSelf === false ? botGroupOwnedBotNames(member, members).join(separator) : '';
++ const shared = message.id !== root?.id && !message.pending ? sharedState(message.id) : null;
++ const onReveal = shared?.shareId ? () => revealShare(shared.shareId!) : undefined;
++ const postAction = readOnly || message.pending || message.id === root?.id || message.deleted || message.kind !== 'message' ? undefined
++ : shared?.bySelf ? onReveal && { key: 'reveal-in-main', label: t(key('thread.viewInMain')), icon: <CornerDownRight size={14} strokeWidth={2} className="shrink-0" />, onSelect: onReveal }
++ : { key: 'post-to-main', label: t(key('thread.postToMain')), disabled: posting.has(message.id), icon: <MessageSquareShare size={14} strokeWidth={2} className="shrink-0" />, onSelect: () => void postToMain(message.id, false) };
+ return (
+ <BotGroupTimelineItem
+ message={message}
+ continued={continued}
+ authorName={authorName}
+ avatar={{ name: authorName, avatar: member?.avatar ?? null, avatarUrl: member?.avatarUrl, avatarColor: member?.avatarColor ?? null }}
+ ownerOf={owned || undefined}
+ members={members}
+ mentionLabels={mentionLabels}
+ locale={locale}
+ shareScope={shareScope}
+ sharing={sharing}
+ reactionGroupId={group.id}
+ reactionRevision={messageReactionRevision(group, message.id)}
+ // A 话题 root may itself be a 引用回复; its original lives in the main timeline.
+ quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, quoteSources) : undefined}
+ onChanged={onChanged}
++ menuActions={postAction ? [postAction] : undefined}
++ footer={shared ? <button type="button" onClick={onReveal} disabled={!onReveal}
++ className="-ml-1.5 inline-flex min-h-6 select-none items-center gap-1 self-start rounded-full px-1.5 text-12 text-[var(--text-tertiary)] outline-none transition-colors duration-[var(--motion-fast)] enabled:hover:bg-[var(--surface-hover)] enabled:hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
++ <CornerDownRight size={12} aria-hidden />{t(key(shared.bySelf ? 'thread.postedBySelf' : 'thread.postedToMain'))}
++ </button> : null}
+ />
+ );
+ };
+ const replyCount = Math.max(root?.replyCount ?? 0, realReplies.filter(reply => reply.kind === 'message').length);
+
return <aside ref={panelRef} aria-labelledby={titleId}
className="flex h-full min-w-0 w-1/2 max-w-[min(50%,28rem)] shrink-0 flex-col overflow-hidden border-l border-[var(--border-default)] bg-[var(--surface)]">
<header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--border-default)] px-5">
@@@ -258,42 -299,58 +385,59 @@@
aria-label={t('bots.close')} onClick={onClose}><X size={17} aria-hidden /></Button>
</Tip>
</header>
- <div ref={contentRef} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4">
- {projectBotGroupExecutionFailures(root ? [root] : [], executionFailures).map(message => <ThreadMessage key={message.id} quoteSources={quoteSources} shareScope={shareScope} sharing={sharing} group={group} message={message}
- onChanged={() => void loadRef.current()} />)}
- <div className="border-t border-[var(--border-default)] pt-3 text-12 text-[var(--text-tertiary)]">{t(key('replies'))}</div>
- {hasMore && <Button variant="secondary" size="sm" onClick={() => void loadRef.current(replies[0]?.sequence)}>{t('bots.groupChat.timeline.loadEarlier')}</Button>}
- {projectBotGroupExecutionFailures(replies, executionFailures).map(message => {
- const shared = sharedState(message.id);
- return <ThreadMessage key={message.id} quoteSources={quoteSources} shareScope={shareScope} sharing={sharing} group={group} message={message}
- shared={shared} posting={posting.has(message.id)}
- onPost={readOnly ? undefined : () => void postToMain(message.id, false)}
- onReveal={shared?.shareId ? () => revealShare(shared.shareId!) : undefined}
- onChanged={() => void loadRef.current()} />;
- })}
+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 pt-3"
+ onScroll={(event) => {
+ const element = event.currentTarget;
+ stickToBottomRef.current = element.scrollHeight - element.scrollTop - element.clientHeight < STICK_TO_BOTTOM_PX;
+ }}>
+ <div ref={contentRef} className="flex min-w-0 flex-col">
+ {rootRows.map(message => <Fragment key={message.id}>{renderRow(message, false)}</Fragment>)}
+ <div data-testid="bot-group-thread-replies" className="mt-3 flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">
+ <span className="shrink-0">{replyCount > 0 ? t(key('replyCount'), { count: replyCount }) : t(key('replies'))}</span>
+ <span aria-hidden className="h-px flex-1 bg-[var(--border-default)]" />
+ </div>
+ {hasMore && <div className="mt-2"><Button variant="secondary" size="sm" onClick={() => void read(replies[0]?.sequence)}>{t('bots.groupChat.timeline.loadEarlier')}</Button></div>}
+ {replyRows.map(message => (
+ <Fragment key={adoptedKeysRef.current.get(message.id) ?? message.id}>
+ {renderRow(message, layout.get(message.id)?.continued ?? false)}
+ </Fragment>
+ ))}
+ </div>
</div>
{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"
- getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <div className={BOT_GROUP_COMPOSER_DOCK}><div className={BOT_GROUP_COMPOSER_COLUMN}>
- {error && <p role="alert" className="mb-2 px-1 text-13 leading-5 text-[var(--error-fg)]">{error}</p>}
+ getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <>
+ {error && <p role="alert" className="px-4 pt-3 text-13 text-[var(--error-fg)]">{error}</p>}
+ {/* Kept apart from read errors: a thread refresh must not hide the retry. */}
+ {unposted.size > 0 && <div role="alert" className="mb-2 px-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-13 text-[var(--error-fg)]">
+ <span className="min-w-0">{t(key('thread.alsoSendFailed'), { count: unposted.size })}</span>
+ <Button variant="secondary" size="sm" compact disabled={readOnly} loading={[...unposted].some(id => posting.has(id))} onClick={() => void retryUnposted()}>
+ {t(key('thread.retryPost'))}</Button>
+ </div>}
- {/* Read-only also means no @ picks while sending. */}
- {busy || readOnly ? null : mention.list}
- {/* Same card as the main group's composer; a sending reply stays read-only (and focused) until main answers. */}
- <div className={BOT_GROUP_COMPOSER_CARD} aria-busy={busy || undefined}>
- <textarea ref={inputRef} rows={1} aria-label={t(key('replyPlaceholder'))} placeholder={t(key('replyPlaceholder'))} value={text}
- {...mention.textareaProps} onChange={e => mention.onChange(e.target.value)}
- maxLength={8000} readOnly={busy} disabled={readOnly} className={BOT_GROUP_COMPOSER_INPUT} onKeyDown={e => {
- if (e.nativeEvent.isComposing || e.keyCode === 229 || (!busy && mention.onKeyDown(e))) return;
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(); }
- }} />
- <div className={BOT_GROUP_COMPOSER_FOOTER}>
- <div className={BOT_GROUP_COMPOSER_FOOTER_START}>
- <button type="button" role="checkbox" aria-checked={alsoSend} disabled={busy || readOnly}
+ <div className="border-t border-[var(--border-default)]">
+ <BotGroupComposer
+ mode="thread"
+ groupId={group.id}
+ draftKey={botGroupThreadDraftKey(group.id, rootId)}
+ members={members}
+ running={false}
+ disabled={readOnly}
++ footerStart={sending => (
++ <button type="button" role="checkbox" aria-checked={alsoSend} disabled={sending || readOnly}
+ onClick={() => setAlsoSend(value => !value)}
+ className="-ml-1.5 inline-flex min-h-7 min-w-0 select-none items-center gap-2 rounded-full px-1.5 text-13 text-[var(--text-secondary)] outline-none transition-colors duration-[var(--motion-fast)] enabled:hover:bg-[var(--surface-hover)] enabled:hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50">
+ <span aria-hidden className={cn('flex h-4 w-4 shrink-0 items-center justify-center rounded-full transition-colors duration-[var(--motion-fast)]',
+ alsoSend ? 'bg-[var(--accent-cta-bg-pure)] text-[var(--accent-pure-cta-fg)]' : 'border border-[var(--border-default)]')}>
+ {alsoSend ? <Check size={10} strokeWidth={3} /> : null}
+ </span>
+ <span className="min-w-0 truncate">{t(key('thread.alsoSend'))}</span>
+ </button>
- </div>
- <span className="inline-flex rounded-full" onMouseDown={keepBotGroupComposerInputFocus(inputRef)}>
- <Tip text={t(key('sendReply'))}>
- <SendButton ariaLabel={t(key('sendReply'))} disabled={readOnly || busy || !text.trim()} onClick={() => void send()} />
- </Tip>
- </span>
- </div>
++ )}
+ sendReply={sendReply}
+ onSendStart={onSendStart}
+ onSendSettled={onSendSettled}
+ onSent={onSent}
+ />
</div>
- </div></div>}
+ </>}
</aside>;
}
diff --cc apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index 0b6ef982c5,b5640ed8af..e871990f88
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@@ -48,8 -51,9 +51,11 @@@ const mocks = vi.hoisted(() => (
getControlledState: vi.fn(),
revoke: vi.fn(),
thread: vi.fn(),
+ /** Live activity of the speaking Session (null = not running on this machine). */
+ activity: null as null | { compactDetail: string; startedAtMs: number | null; phase: string },
+ ownerGeneration: { dataOwnerId: 'account-a', generation: 1 },
+ reply: vi.fn(),
+ shareToMain: vi.fn(),
}));
// Partial: the shared attachment pieces pull in the app i18n instance, which needs initReactI18next.
@@@ -2758,264 -2712,610 +2768,875 @@@ it('keeps copy/share in each author ro
} finally { focus.mockRestore(); resetBotReadStateForTests(); }
});
+it('acknowledges a Bot’s plan card at the tail, the same range the unread badge counts', async () => {
+ resetBotReadStateForTests();
+ const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true);
+ markBotRead(botGroupReadKey('g1'), 100);
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(plan(), [], { messages: [
+ msg({ id: 'b', authorKind: 'bot', content: 'First reply', createdAt: 200 }),
+ { ...planCard, createdAt: 300 },
+ ] }) });
+ const view = renderView();
+ try {
+ await screen.findByTestId('bot-group-plan');
+ act(() => window.dispatchEvent(new Event('focus')));
+ expect(getBotLastReadAt(botGroupReadKey('g1'))).toBe(300);
+ } finally { focus.mockRestore(); resetBotReadStateForTests(); view.unmount(); }
+});
+
+describe('Telegram / Slack-grade timeline', () => {
+ function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+ }
+ const push = (change: BotGroupChangedPayload['change'] = 'messages') =>
+ act(async () => { mocks.pushes.forEach((listener) => listener({ groupId: 'g1', change })); });
+ const own = (id: string, sequence: number, content: string, createdAt = 1_700_000_000_000) =>
+ msg({ id, sequence, content, createdAt, isSelf: true });
+
+ it('shows a sent message at once and swaps in main’s copy in place', async () => {
+ const sent = deferred<{ ok: true; messageId: string }>();
+ mocks.sendBotGroupMessage.mockReturnValue(sent.promise);
+ renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '在吗' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(input.value).toBe('');
+ const bubble = await screen.findByText('在吗');
+ const row = bubble.closest('[data-bot-group-message-id]') as HTMLElement;
+ expect(row.dataset.botGroupMessageId).toMatch(/^pending:/);
+ expect(row.querySelector('article')?.getAttribute('aria-busy')).toBe('true');
+ // The pending copy has no toolbar: it cannot be quoted, shared or answered yet.
+ expect(within(row).queryByRole('button', { name: 'chat.messageActionBar.copy' })).toBeNull();
+ const base = detail();
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: { ...base, messages: [...base.messages, own('u9', 5, '在吗')] } });
+ await act(async () => sent.resolve({ ok: true, messageId: 'u9' }));
+ await waitFor(() => expect(row.dataset.botGroupMessageId).toBe('u9'));
+ // Same row element: no remount, no flash.
+ expect(document.contains(row)).toBe(true);
+ expect(screen.getAllByText('在吗')).toHaveLength(1);
+ });
+
+ it('takes the pending copy back and restores the draft when the send fails', async () => {
+ mocks.sendBotGroupMessage.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });
+ renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '没发出去' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(input.value).toBe('没发出去'));
+ expect(document.querySelector('[data-bot-group-message-id^="pending:"]')).toBeNull();
+ });
+
+ it('collapses pushes during a read into one follow-up read and shows every result', async () => {
+ renderView();
+ await screen.findByText('周六 8:10 有票');
+ const first = deferred<{ ok: true; group: BotGroupDetail }>();
+ const second = deferred<{ ok: true; group: BotGroupDetail }>();
+ mocks.getBotGroup.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ await push();
+ await push();
+ await push();
+ // One read in flight; the later pushes wait for it instead of discarding it.
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(2);
+ const base = detail();
+ await act(async () => first.resolve({ ok: true, group: { ...base, messages: [...base.messages, msg({ id: 'x1', sequence: 5, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '第一条回复' })] } }));
+ expect(screen.getByText('第一条回复')).toBeTruthy();
+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(3));
+ await act(async () => second.resolve({ ok: true, group: { ...base, messages: [...base.messages,
+ msg({ id: 'x1', sequence: 5, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '第一条回复' }),
+ msg({ id: 'x2', sequence: 6, authorKind: 'bot', authorBotId: 'mimi', authorName: '咪咪', content: '第二条回复' })] } }));
+ expect(screen.getByText('第一条回复')).toBeTruthy();
+ expect(screen.getByText('第二条回复')).toBeTruthy();
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);
+ });
+
+ it('keeps messages pushed out of the newest page on screen', async () => {
+ const rows = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, index) =>
+ msg({ id: `r${from + index}`, sequence: from + index, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: `第${from + index}条` }));
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: rows(1, 3), hasMoreBefore: true }) });
+ renderView();
+ await screen.findByText('第1条');
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: rows(3, 5), hasMoreBefore: true }) });
+ await push();
+ await screen.findByText('第5条');
+ expect(screen.getByText('第1条')).toBeTruthy();
+ expect(screen.getByText('第2条')).toBeTruthy();
+ // Older history is still offered above them.
+ expect(screen.getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })).toBeTruthy();
+ });
+
+ it('merges consecutive messages by one author and divides days', async () => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ yesterday.setHours(12, 0, 0, 0);
+ const today = new Date();
+ today.setHours(0, 30, 0, 0);
+ const bot = (id: string, sequence: number, createdAt: number, content: string) =>
+ msg({ id, sequence, createdAt, content, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满' });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [
+ bot('a', 1, yesterday.getTime(), '昨天第一条'),
+ bot('b', 2, yesterday.getTime() + 60_000, '昨天第二条'),
+ bot('c', 3, today.getTime(), '今天第一条'),
+ ] }) });
+ renderView();
+ await screen.findByText('今天第一条');
+ const article = (text: string) => screen.getByText(text).closest('article')!;
+ expect(article('昨天第一条').querySelector('[data-avatar]')).toBeTruthy();
+ expect(within(article('昨天第一条')).getByText('小满')).toBeTruthy();
+ // The merged line has no avatar or name, only a time in its gutter.
+ expect(article('昨天第二条').querySelector('[data-avatar]')).toBeNull();
+ expect(within(article('昨天第二条')).queryByText('小满')).toBeNull();
+ expect(article('昨天第二条').querySelector('time')).toBeTruthy();
+ // A new day starts a new block under its own date line.
+ expect(article('今天第一条').querySelector('[data-avatar]')).toBeTruthy();
+ expect(screen.getAllByTestId('bot-group-date-divider')).toHaveLength(2);
+ });
+
+ it('keeps the unsent text with the group across a remount', async () => {
+ let view = renderView();
+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: '写了一半的话\n第二行' } });
+ view.unmount();
+ view = renderView();
+ expect(((await screen.findByRole('textbox')) as HTMLTextAreaElement).value).toBe('写了一半的话\n第二行');
+ view.unmount();
+ // Another group starts empty.
+ mocks.groupId = 'g2';
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'g2' }) });
+ renderView();
+ expect(((await screen.findByRole('textbox')) as HTMLTextAreaElement).value).toBe('');
+ });
+
+ it('shows the organizer deciding about a split in the header and as a speaking line', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({
+ speakingBotIds: ['mimi'],
+ planningBotId: 'mimi',
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: null, activity: 'planning' }], canContinue: false },
+ }) });
+ renderView();
+ const row = await screen.findByTestId('bot-group-speaking');
+ expect(row.getAttribute('data-activity')).toBe('planning');
+ expect(row.textContent).toContain('咪咪');
+ expect(row.textContent).toContain('bots.groupChat.speaking.planning');
+ expect(screen.getByTestId('content-header').textContent).toContain('bots.groupChat.header.planning:咪咪');
+ });
+
+ it('does not pin the progress strip for an organizer still deciding about a split', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({
+ speakingBotIds: ['mimi'],
+ planningBotId: 'mimi',
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: null, activity: 'planning' }], canContinue: false },
+ }) });
+ // Well past the few seconds after which a speaking teammate would pin the strip.
+ mocks.activity = { compactDetail: '', startedAtMs: Date.now() - 5_000, phase: 'running' };
+ try {
+ renderView();
+ const row = await screen.findByTestId('bot-group-speaking');
+ expect(row.getAttribute('data-activity')).toBe('planning');
+ expect(screen.queryByTestId('bot-group-progress')).toBeNull();
+ } finally {
+ mocks.activity = null;
+ }
+ });
+
+ it('pins a progress strip above the composer while a plan step runs', async () => {
+ const running = plan({
+ status: 'running',
+ currentStep: 0,
+ updatedAt: Date.now() - 125_000,
+ steps: [{ ...plan().steps[0]!, status: 'running' }, plan().steps[1]!],
+ });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(running, [], {
+ speakingBotIds: ['mimi'],
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: 'plan-mimi', activity: 'step' }], canContinue: false },
+ }) });
+ renderView();
+ const strip = await screen.findByTestId('bot-group-progress');
+ expect(strip.textContent).toContain('bots.groupChat.progress.step');
+ expect(strip.textContent).toContain('想清楚这页讲什么');
+ expect(strip.textContent).toContain('bots.groupChat.progress.elapsed');
+ // The strip stands in for the step's speaking line; its confirmations stay in the timeline.
+ expect(screen.queryByTestId('bot-group-speaking')).toBeNull();
+ expect(screen.getByTestId('pending-interaction').textContent).toBe('plan-mimi');
+ // It sits between the timeline and the composer.
+ expect(strip.compareDocumentPosition(screen.getByRole('textbox')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByTestId('content-header').textContent).toContain('bots.groupChat.header.stepRunning:咪咪');
+ // The running step shows how long it has been going.
+ expect(screen.getByTestId('bot-group-plan').textContent).toContain('bots.groupChat.elapsed.minutes');
+ fireEvent.click(within(strip).getByRole('button', { name: 'bots.groupChat.progress.stop' }));
+ await waitFor(() => expect(mocks.stopBotGroupRound).toHaveBeenCalledWith('g1'));
+ });
+
+ it('does not show the silence marker as the running step’s current action', async () => {
+ const running = plan({
+ status: 'running',
+ currentStep: 0,
+ steps: [{ ...plan().steps[0]!, status: 'running' }, plan().steps[1]!],
+ });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(running, [], {
+ speakingBotIds: ['mimi'],
+ round: { status: 'running', speakers: [{ botId: 'mimi', sessionId: 'plan-mimi', activity: 'step' }], canContinue: false },
+ }) });
+ mocks.activity = { compactDetail: 'NO_REPLY', startedAtMs: Date.now() - 5_000, phase: 'running' };
+ try {
+ renderView();
+ const strip = await screen.findByTestId('bot-group-progress');
+ expect(strip.textContent).toContain('想清楚这页讲什么');
+ expect(strip.textContent).not.toContain('NO_REPLY');
+ mocks.activity = { compactDetail: '正在读 README.md', startedAtMs: Date.now() - 5_000, phase: 'running' };
+ fireEvent.click(within(strip).getByRole('button', { name: 'bots.groupChat.progress.viewProcess' }));
+ await waitFor(() => expect(screen.getByTestId('bot-group-progress').textContent).toContain('正在读 README.md'));
+ } finally {
+ mocks.activity = null;
+ }
+ });
+
+ it('highlights @mentions of members in teammates’ messages too', async () => {
+ const registry = new Map<string, { ranges: Range[] }>();
+ vi.stubGlobal('Highlight', class { ranges: Range[]; constructor(...ranges: Range[]) { this.ranges = ranges; } });
+ const originalCss = globalThis.CSS;
+ vi.stubGlobal('CSS', { ...(originalCss ?? {}), highlights: registry });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [
+ msg({ id: 'u1', sequence: 1, content: '@小满 帮我查余票' }),
+ msg({ id: 'b1', sequence: 2, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '@咪咪 你来订 `@nobody`' }),
+ ] }) });
+ renderView();
+ await screen.findByText('@小满 帮我查余票');
+ await waitFor(() => expect(registry.get('bot-group-mention')?.ranges.map((range) => range.toString()).sort()).toEqual(['@咪咪', '@小满']));
+ });
+
+ it('shows a 话题 reply at once and keeps one copy when the server’s reply arrives', async () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ const sent = deferred<{ ok: true; messageId: string }>();
+ const reply = vi.fn(() => sent.promise);
+ Object.assign((window.electronAPI as unknown as { maker: { chatServer: Record<string, unknown> } }).maker.chatServer, { reply });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true }) });
+ const user = userEvent.setup();
+ renderView();
+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);
+ const panel = screen.getByRole('complementary');
+ await within(panel).findByText('Reply to u1');
+ const input = within(panel).getByRole('textbox') as HTMLTextAreaElement;
+ await user.type(input, '我也去{Enter}');
+ expect(input.value).toBe('');
+ expect(within(panel).getByText('我也去')).toBeTruthy();
+ expect(reply).toHaveBeenCalledWith(expect.objectContaining({ groupId: 'g1', rootId: 'u1', text: '我也去' }));
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: 'Thread root u1' }),
+ replies: [msg({ id: 'reply-u1', content: 'Reply to u1' }), msg({ id: 'r9', sequence: 2, content: '我也去', isSelf: true })], hasMore: false });
+ await act(async () => sent.resolve({ ok: true, messageId: 'r9' }));
+ await waitFor(() => expect(panel.querySelector('[data-bot-group-message-id="r9"]')).toBeTruthy());
+ expect(within(panel).getAllByText('我也去')).toHaveLength(1);
+ });
+});
++
+ describe('thread previews and posting to the main chat', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ const preview = (id: string, authorName: string, text: string, extra: Record<string, unknown> = {}) => ({
+ id, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName, text, attachments: [], createdAt: 1_700_000_000_000, ...extra });
+ const share = (overrides: Partial<NonNullable<BotGroupMessageView['threadShare']>> = {}): NonNullable<BotGroupMessageView['threadShare']> => ({
+ messageId: 'reply-u1', threadRootId: 'u1', status: 'available', authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '原话:@咪咪 周六见', attachments: [], createdAt: 1_700_000_000_000, edited: false, ...overrides });
+ function group(messages: BotGroupMessageView[]) {
+ return detail({ serverBacked: true, messages });
+ }
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('shows the newest replies under the root and opens the thread from the preview', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([
+ msg({ id: 'u1', content: '去哪玩', replyCount: 3, threadPreview: { replies: [
+ preview('r2', '小满', '爬山吧,带上相机'),
+ preview('r3', '咪咪', '', { attachments: [{ name: 'map.png', category: 'image' }, { name: 'list.pdf', category: 'file' }] }),
+ ] } }),
+ ]) });
+ const user = userEvent.setup();
+ renderView();
+ const card = await screen.findByRole('button', { name: t('open') });
+ expect(card.textContent).toContain('小满');
+ expect(card.textContent).toContain('爬山吧,带上相机');
+ // An attachment-only reply still says what it carried.
+ expect(card.textContent).toContain(t('attachmentsSummary'));
+ expect(card.textContent).toContain('bots.groupChat.server.replyCount');
+ // Export the selected root, without its independently selectable thread replies.
+ const exported = prepareShareMessageClone(card.closest('article')!)!;
+ expect(exported.textContent).toContain('去哪玩');
+ expect(exported.textContent).not.toContain('爬山吧,带上相机');
+ expect(exported.textContent).not.toContain('map.png');
+ expect(exported.querySelector('[data-thread-preview]')).toBeNull();
+ // The count lives in the preview; the toolbar keeps a plain reply icon.
+ const toolbarReply = screen.getByRole('button', { name: 'bots.groupChat.server.openTopic' });
+ expect(toolbarReply.textContent).toBe('');
+ await user.click(card);
+ expect(await screen.findByRole('complementary')).toBeTruthy();
+ expect(mocks.thread).toHaveBeenCalledWith(expect.objectContaining({ rootId: 'u1' }));
+ await user.keyboard('{Escape}');
+ expect(document.activeElement).toBe(card);
+ });
+
+ it('keeps the original author and the sharer apart, and jumps from a share to its reply', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([
+ msg({ id: 'u1', content: '去哪玩' }),
+ msg({ id: 's-other', sequence: 2, authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ 小满: fallback', threadShare: share() }),
+ msg({ id: 's-own', sequence: 3, content: '↪ 我: fallback', threadShare: share({ messageId: 'reply-u1', authorKind: 'user', authorBotId: null, authorName: '我', sharedByAuthor: true, content: '我自己的回复' }) }),
+ msg({ id: 's-gone', sequence: 4, authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ x: fallback', threadShare: share({ status: 'unavailable', authorName: '', content: '' }) }),
+ ]) });
+ const user = userEvent.setup();
+ renderView();
+ const other = (await screen.findByText(`${t('sharedReplyFrom')}:小满`)).closest('article')!;
+ expect(within(other).getByText('Alice')).toBeTruthy();
+ expect(within(other).getByText('原话:@咪咪 周六见')).toBeTruthy();
+ expect(within(other).queryByText('↪ 小满: fallback')).toBeNull();
+ // A selected share keeps the quoted reply and authors, but not navigation controls.
+ const exported = prepareShareMessageClone(other)!;
+ expect(exported.textContent).toContain('Alice');
+ expect(exported.textContent).toContain('小满');
+ expect(exported.textContent).toContain('原话:@咪咪 周六见');
+ expect(exported.textContent).not.toContain(t('viewThread'));
+ const own = screen.getByText(t('alsoSent')).closest('article')!;
+ expect(within(own).getByText('我自己的回复')).toBeTruthy();
+ expect(screen.getByText(t('sourceUnavailable'))).toBeTruthy();
+ // An unverified card's own thread ID leads nowhere.
+ const gone = screen.getByText(t('sourceUnavailable')).closest('article')!;
+ expect(within(gone).queryByRole('button', { name: t('viewThread') })).toBeNull();
+ await user.click(within(other).getByRole('button', { name: t('viewThread') }));
+ const panel = await screen.findByRole('complementary');
+ await waitFor(() => expect(within(panel).getByText('Reply to u1').closest('article')!.className).toContain('ring-2'));
+ // The reply is already in the main chat: say so and lead back to it.
+ expect(within(panel).getByRole('button', { name: t('postedBySelf') })).toBeTruthy();
+ await user.click(within(panel).getByRole('button', { name: t('postedBySelf') }));
+ expect(own.className).toContain('ring-2');
+ });
+
+ it('sends to the thread only by default, and to both places when asked', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩' })]) });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const panel = await screen.findByRole('complementary');
+ const toggle = within(panel).getByRole('checkbox', { name: t('alsoSend') });
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ await user.type(within(panel).getByRole('textbox'), 'thread only{Enter}');
+ await waitFor(() => expect(mocks.reply).toHaveBeenCalledTimes(1));
+ expect(mocks.shareToMain).not.toHaveBeenCalled();
+ await user.click(toggle);
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ mocks.reply.mockResolvedValueOnce({ ok: true, messageId: 'reply-2' });
+ await user.type(within(panel).getByRole('textbox'), '@咪咪 both{Enter}');
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledWith({ groupId: 'g1', messageId: 'reply-2' }));
+ expect(mocks.reply).toHaveBeenCalledTimes(2);
+ expect(mocks.reply.mock.calls[1][0]).toMatchObject({ rootId: 'u1', text: '@咪咪 both' });
+ // Each send starts from the default again.
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'));
+ });
+
+ it('retries only the main-chat copy after the reply already reached the thread', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩' })]) });
+ mocks.shareToMain.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR' });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'both{Enter}');
+ const retry = await within(panel).findByRole('button', { name: t('retryPost') });
+ // A thread refresh must not hide the retry.
+ act(() => { for (const push of mocks.pushes) push({ groupId: 'g1', change: 'messages' }); });
+ await waitFor(() => expect(mocks.thread.mock.calls.length).toBeGreaterThan(1));
+ expect(within(panel).getByText(t('alsoSendFailed'))).toBeTruthy();
+ await user.click(retry);
+ await waitFor(() => expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull());
+ expect(mocks.shareToMain.mock.calls).toEqual([[{ groupId: 'g1', messageId: 'new-reply' }], [{ groupId: 'g1', messageId: 'new-reply' }]]);
+ expect(mocks.reply).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([false, true])('drops an unavailable main-chat copy and reports why (after transient failure: %s)', async retrying => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩' })]) });
+ if (retrying) mocks.shareToMain.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR' });
+ mocks.shareToMain.mockResolvedValueOnce({ ok: false, errorCode: 'SHARE_UNAVAILABLE' });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'both{Enter}');
+ if (retrying) await user.click(await within(panel).findByRole('button', { name: t('retryPost') }));
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith(t('shareUnavailable')));
+ expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull();
+ expect(mocks.reply).toHaveBeenCalledTimes(1);
+ expect(mocks.shareToMain).toHaveBeenCalledTimes(retrying ? 2 : 1);
+ });
+
+ it('keeps one send identity across a failed reply and never posts to the main chat before it lands', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩' })]) });
+ mocks.reply.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR' });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'both{Enter}');
+ await waitFor(() => expect(mocks.reply).toHaveBeenCalledTimes(1));
+ expect(mocks.shareToMain).not.toHaveBeenCalled();
+ expect(within(panel).getByRole('checkbox', { name: t('alsoSend') }).getAttribute('aria-checked')).toBe('true');
+ await user.click(within(panel).getByRole('button', { name: 'bots.groupChat.server.sendReply' }));
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledTimes(1));
+ expect(mocks.reply.mock.calls[1][0].clientId).toBe(mocks.reply.mock.calls[0][0].clientId);
+ });
+
+ it('does not carry the choice into another thread', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: 'A' }), msg({ id: 'u2', sequence: 2, content: 'B' })]) });
+ const user = userEvent.setup();
+ renderView();
+ const [first, second] = await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' });
+ await user.click(first!);
+ await user.click(within(await screen.findByRole('complementary')).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.click(second!);
+ await screen.findByText('Reply to u2');
+ expect(within(screen.getByRole('complementary')).getByRole('checkbox', { name: t('alsoSend') }).getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('posts an existing reply, including someone else’s, from its menu', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: group([msg({ id: 'u1', content: '去哪玩' })]) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ expect(mocks.shareToMain).toHaveBeenCalledWith({ groupId: 'g1', messageId: 'alice-reply' });
+ expect(await within(reply).findByRole('button', { name: t('postedBySelf') })).toBeTruthy();
+ expect(mocks.reply).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('thread share follow-ups', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ const share = (overrides: Partial<NonNullable<BotGroupMessageView['threadShare']>> = {}): NonNullable<BotGroupMessageView['threadShare']> => ({
+ messageId: 'reply-x', threadRootId: 'u1', status: 'available', authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '服务器上的原文', attachments: [], createdAt: 1_700_000_000_000, edited: false, ...overrides });
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('shows a loading placeholder, never the card text, while the reply is read', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [
+ msg({ id: 's1', authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ 冒充: 卡片文字', threadShare: share({ status: 'loading', authorName: '', content: '' }) }),
+ ] }) });
+ renderView();
+ expect(await screen.findByText(t('loadingSource'))).toBeTruthy();
+ expect(screen.queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ });
+
+ it.each(['unavailable', 'available'] as const)('keeps a %s share as a quote when it is the thread root', async status => {
+ const root = msg({ id: 's1', authorKind: 'user', isSelf: false, authorName: 'Alice', content: '↪ 冒充: 卡片文字', replyCount: 1,
+ threadShare: share(status === 'available'
+ ? { attachments: [{ id: 'f1', name: '路线.pdf', category: 'file', mimeType: 'application/pdf', size: 1, url: null, path: '/tmp/路线.pdf' }] }
+ : { status: 'unavailable', authorName: '', content: '' }) });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [root] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root, replies: [], hasMore: false });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.openTopic' }));
+ const panel = await screen.findByRole('complementary');
+ await waitFor(() => expect(within(panel).getAllByRole('figure').length).toBe(1));
+ expect(within(panel).queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ if (status === 'available') {
+ expect(within(panel).getByText('服务器上的原文')).toBeTruthy();
+ expect(within(panel).getByText('路线.pdf')).toBeTruthy();
+ } else expect(within(panel).getByText(t('sourceUnavailable'))).toBeTruthy();
+ });
+
+ it('keeps the share it got back and says when that share is on an older page', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' })] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ mocks.shareToMain.mockResolvedValue({ ok: true, messageId: 'old-share', alreadyShared: false });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ const badge = await within(reply).findByRole('button', { name: t('postedBySelf') });
+ expect((badge as HTMLButtonElement).disabled).toBe(false);
+ await user.click(badge);
+ expect(mocks.toastInfo).toHaveBeenCalledWith(t('shareNotLoaded'));
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ expect(await screen.findByRole('menuitem', { name: t('viewInMain') })).toBeTruthy();
+ });
+
+ it('stops offering to post a reply whose existing share cannot be located', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' })] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ // The server already has this person's share but could not say which message it is.
+ mocks.shareToMain.mockResolvedValue({ ok: true, messageId: null, alreadyShared: true });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ const badge = await within(reply).findByRole('button', { name: t('postedBySelf') });
+ expect((badge as HTMLButtonElement).disabled).toBe(true);
+ // With nothing else to offer for this reply, the menu itself may be gone.
+ const more = within(reply).queryByRole('button', { name: 'chat.messageActionBar.moreActions' });
+ if (more) {
+ fireEvent.pointerDown(more, { button: 0, ctrlKey: false });
+ await screen.findAllByRole('menuitem');
+ }
+ expect(screen.queryByRole('menuitem', { name: t('postToMain') })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: t('viewInMain') })).toBeNull();
+ expect(mocks.shareToMain).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows the reader's own share over another member's that the main chat has loaded", async () => {
+ const bobShare = msg({ id: 'bob-share', sequence: 2, authorKind: 'user', isSelf: false, authorBotId: 'bob', authorName: 'Bob', content: '↪ 卡片',
+ threadShare: { messageId: 'alice-reply', threadRootId: 'u1', status: 'available', authorKind: 'user', authorBotId: null, authorName: 'Alice',
+ sharedByAuthor: false, content: 'Alice says hi', attachments: [], createdAt: 1, edited: false } });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' }), bobShare] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ // The reader's earlier share of the same reply sits on a page the main chat has not loaded.
+ mocks.shareToMain.mockResolvedValue({ ok: true, messageId: 'my-old-share', alreadyShared: true });
+ const user = userEvent.setup();
+ renderView();
+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);
+ const panel = await screen.findByRole('complementary');
+ const reply = (await within(panel).findByText('Alice says hi')).closest('article')!;
+ expect(await within(reply).findByRole('button', { name: t('postedToMain') })).toBeTruthy();
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ expect(await within(reply).findByRole('button', { name: t('postedBySelf') })).toBeTruthy();
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ expect(await screen.findByRole('menuitem', { name: t('viewInMain') })).toBeTruthy();
+ expect(screen.queryByRole('menuitem', { name: t('postToMain') })).toBeNull();
+ });
+
+ it('does not count a share the server could not resolve in its claimed thread as posted', async () => {
+ // The reader's own card names the right reply but the wrong thread, so it resolved as unavailable.
+ const misplaced = msg({ id: 'my-bad-share', sequence: 2, content: '↪ 卡片',
+ threadShare: share({ messageId: 'alice-reply', threadRootId: 'elsewhere', status: 'unavailable', authorName: '', content: '' }) });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' }), misplaced] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ const user = userEvent.setup();
+ renderView();
+ await user.click((await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' }))[0]!);
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ expect(within(reply).queryByRole('button', { name: t('postedBySelf') })).toBeNull();
+ expect(within(reply).queryByRole('button', { name: t('postedToMain') })).toBeNull();
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ expect(await screen.findByRole('menuitem', { name: t('postToMain') })).toBeTruthy();
+ expect(screen.queryByRole('menuitem', { name: t('viewInMain') })).toBeNull();
+ });
+
+ it('keeps every failed main-chat copy retryable, across switching threads', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: 'A' }), msg({ id: 'u2', sequence: 2, content: 'B' })] }) });
+ mocks.reply.mockResolvedValueOnce({ ok: true, messageId: 'first' }).mockResolvedValueOnce({ ok: true, messageId: 'second' });
+ mocks.shareToMain.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR' });
+ const user = userEvent.setup();
+ renderView();
+ const [first, second] = await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' });
+ await user.click(first!);
+ let panel = await screen.findByRole('complementary');
+ for (const text of ['one', 'two']) {
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), `${text}{Enter}`);
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledWith({ groupId: 'g1', messageId: text === 'one' ? 'first' : 'second' }));
+ }
+ await within(panel).findByRole('button', { name: t('retryPost') });
+ await user.click(second!);
+ await screen.findByText('Reply to u2');
+ expect(within(screen.getByRole('complementary')).queryByRole('button', { name: t('retryPost') })).toBeNull();
+ await user.click(first!);
+ panel = await screen.findByRole('complementary');
+ const retry = await within(panel).findByRole('button', { name: t('retryPost') });
+ mocks.shareToMain.mockClear().mockResolvedValue({ ok: true, messageId: 'share', alreadyShared: false });
+ await user.click(retry);
+ await waitFor(() => expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull());
+ expect(mocks.shareToMain.mock.calls.map(([input]) => input.messageId)).toEqual(['first', 'second']);
+ expect(mocks.reply).toHaveBeenCalledTimes(2);
+ });
+
+ // The copy fails while the reader is in another thread, or after they came back to this one.
+ it.each(['away', 'back'] as const)('keeps a main-chat copy retryable when it fails after leaving the thread (reader %s)', async (where) => {
+ // The queue outlives a panel by design, so each case uses threads of its own.
+ const [rootA, rootB] = [`${where}-a`, `${where}-b`];
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: rootA, content: 'A' }), msg({ id: rootB, sequence: 2, content: 'B' })] }) });
+ mocks.reply.mockResolvedValue({ ok: true, messageId: 'first' });
+ let fail!: () => void;
+ mocks.shareToMain.mockReturnValueOnce(new Promise(resolve => { fail = () => resolve({ ok: false, errorCode: 'SERVICE_ERROR' }); }));
+ const user = userEvent.setup();
+ renderView();
+ const [first, second] = await screen.findAllByRole('button', { name: 'bots.groupChat.server.startTopic' });
+ await user.click(first!);
+ const panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'one{Enter}');
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledTimes(1));
+ // The copy is still on its way when the reader moves to another thread.
+ await user.click(second!);
+ await screen.findByText(`Reply to ${rootB}`);
+ if (where === 'away') await act(async () => fail());
+ await user.click(first!);
+ const reopened = await screen.findByRole('complementary');
+ await within(reopened).findByText(`Reply to ${rootA}`);
+ if (where === 'back') {
+ expect(within(reopened).queryByRole('button', { name: t('retryPost') })).toBeNull();
+ await act(async () => fail());
+ }
+ expect(await within(reopened).findByRole('button', { name: t('retryPost') })).toBeTruthy();
+ });
+ });
+
+ describe('shares on older pages', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it('follows the reply after an edit or deletion without a click or reopen', async () => {
+ const oldShare = msg({ id: 'old-share', sequence: 1, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 冒充: 卡片文字',
+ threadShare: { messageId: 'old-reply', threadRootId: 'old-root', status: 'available', authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '加载时的原文', attachments: [], createdAt: 1, edited: false } });
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] });
+ mocks.getBotGroup
+ .mockResolvedValueOnce({ ok: true, group: latest })
+ .mockResolvedValueOnce({ ok: true, group: { ...latest, hasMoreBefore: false, messages: [oldShare] } })
+ .mockResolvedValue({ ok: true, group: { ...latest, threadShareUpdates: { 'old-share': { ...oldShare.threadShare!, status: 'unavailable', authorName: '', content: '' } } } });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ expect(await screen.findByText('加载时的原文')).toBeTruthy();
+ act(() => { for (const push of mocks.pushes) push({ groupId: 'g1', change: 'messages' }); });
+ expect(await screen.findByText(t('sourceUnavailable'))).toBeTruthy();
+ expect(screen.queryByText('加载时的原文')).toBeNull();
+ expect(screen.queryByText('↪ 冒充: 卡片文字')).toBeNull();
+ expect(mocks.getBotGroup).toHaveBeenLastCalledWith('g1', expect.objectContaining({
+ shownShares: [{ id: 'old-share', messageId: 'old-reply', threadRootId: 'old-root', sharerId: 'alice-actor' }] }));
+ });
+
+ // The reply is edited while an older page is on its way; either read may land first.
+ it.each(['refresh', 'page'] as const)('checks the shares of an older page that races an edit refresh (%s lands first)', async (first) => {
+ const share = { messageId: 'old-reply', threadRootId: 'old-root', status: 'available' as const, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '编辑前的原文', attachments: [], createdAt: 1, edited: false, version: 1 };
+ const oldShare = msg({ id: 'old-share', sequence: 1, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 卡片文字', threadShare: share });
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 1, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] });
+ let finishPage!: (result: { ok: true; group: BotGroupDetail }) => void;
+ let finishRefresh!: (result: { ok: true; group: BotGroupDetail }) => void;
+ mocks.getBotGroup
+ .mockResolvedValueOnce({ ok: true, group: latest })
+ .mockReturnValueOnce(new Promise(resolve => { finishPage = resolve; }))
+ .mockReturnValueOnce(new Promise(resolve => { finishRefresh = resolve; }))
+ .mockImplementation(async (_groupId: string, options?: { shownShares?: Array<{ id: string }> }) => ({ ok: true, group: { ...latest, threadShareVersion: 2,
+ ...(options?.shownShares?.some(item => item.id === 'old-share')
+ ? { threadShareUpdates: { 'old-share': { ...share, content: '编辑后的原文', edited: true, version: 2 } } } : {}) } }));
+ renderView();
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(3));
+ const page = () => finishPage({ ok: true, group: { ...latest, hasMoreBefore: false, messages: [oldShare] } });
+ const refresh = () => finishRefresh({ ok: true, group: { ...latest, threadShareVersion: 2 } });
+ for (const land of first === 'refresh' ? [refresh, page] : [page, refresh]) await act(async () => land());
+ expect(await screen.findByText('编辑后的原文')).toBeTruthy();
+ expect(screen.queryByText('编辑前的原文')).toBeNull();
+ });
+
+ it('checks each new version once without looping when a source cannot be confirmed', async () => {
+ const share = { messageId: 'old-reply', threadRootId: 'old-root', status: 'available' as const, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '原文', attachments: [], createdAt: 1, edited: false, version: 1 };
+ const oldShare = msg({ id: 'old-share', sequence: 1, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 卡片文字', threadShare: share });
+ let version = 1;
+ // The server cannot confirm this share for now, so every refresh leaves it stale.
+ mocks.getBotGroup.mockImplementation(async (_groupId: string, options?: { beforeSequence?: number }) => ({ ok: true, group: detail({ serverBacked: true,
+ threadShareVersion: version, ...(options?.beforeSequence ? { hasMoreBefore: false, messages: [oldShare] } : { hasMoreBefore: true, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] }) }) }));
+ renderView();
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ await screen.findByText('原文');
+ const settle = async () => { for (let i = 0; i < 6; i += 1) await act(async () => { await Promise.resolve(); }); };
+ version = 2;
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
+ await settle();
+ const afterFirstEdit = mocks.getBotGroup.mock.calls.length;
+ // A later edit is checked again; unchanged stale data never causes a refresh loop.
+ version = 3;
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
+ await settle();
+ expect(mocks.getBotGroup.mock.calls.length - afterFirstEdit).toBe(2);
+ await settle();
+ expect(mocks.getBotGroup.mock.calls.length - afterFirstEdit).toBe(2);
+ });
+
+ it('waits for a follow-up before another, whatever else commits meanwhile', async () => {
+ const share = { messageId: 'old-reply', threadRootId: 'old-root', status: 'available' as const, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '原文', attachments: [], createdAt: 1, edited: false, version: 1 };
+ const oldShare = msg({ id: 'old-share', sequence: 20, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 卡片文字', threadShare: share });
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 2, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] });
+ const followUps: Array<() => void> = [];
+ mocks.getBotGroup.mockImplementation((_groupId: string, options?: { beforeSequence?: number; shownShares?: unknown[] }) => {
+ if (options?.beforeSequence === 50) return Promise.resolve({ ok: true, group: { ...latest, messages: [oldShare] } });
+ if (options?.beforeSequence) return Promise.resolve({ ok: true, group: { ...latest, hasMoreBefore: false, messages: [msg({ id: 'oldest', sequence: 1, content: '更早' })] } });
+ // A follow-up checking the stale share stays in flight until released.
+ if (options?.shownShares?.length) return new Promise(resolve => followUps.push(() => resolve({ ok: true, group: latest })));
+ return Promise.resolve({ ok: true, group: latest });
+ });
+ renderView();
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ await waitFor(() => expect(followUps).toHaveLength(1));
+ // Another older page lands while that follow-up is still in flight.
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ await screen.findByText('更早');
+ await act(async () => { await Promise.resolve(); });
+ expect(followUps).toHaveLength(1);
+ });
+ });
+
+ describe('more older shares than one refresh re-reads', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+
+ it.each(['source', 'attachment'] as const)('settles every older %s after overlapping completion pushes', { timeout: 20_000 }, async (pending) => {
+ const older = Array.from({ length: 201 }, (_, i) => msg({ id: `share-${i}`, sequence: i + 1, content: 'card fallback',
+ threadShare: { messageId: `reply-${i}`, threadRootId: 'root', status: pending === 'source' ? 'loading' : 'available',
+ authorKind: 'user', authorBotId: null, authorName: 'Alice', sharedByAuthor: true, content: pending === 'source' ? '' : `原文 ${i}`,
+ attachments: pending === 'attachment' ? [{ id: `file-${i}`, name: `pending-${i}.pdf`, category: 'file', mimeType: 'application/pdf', size: 0, url: null, path: null, state: 'loading' }] : [],
+ createdAt: 1, edited: false, version: 2 } }));
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 2, messages: [msg({ id: 'new', sequence: 500, content: '最新' })] });
+ const finish: Array<() => void> = [];
+ mocks.getBotGroup.mockImplementation((_groupId: string, options?: { beforeSequence?: number; shownShares?: Array<{ id: string }> }) => {
+ if (options?.beforeSequence) return Promise.resolve({ ok: true, group: { ...latest, hasMoreBefore: false, messages: older } });
+ if (!options?.shownShares?.length) return Promise.resolve({ ok: true, group: latest });
+ const updates = Object.fromEntries(options.shownShares.map(ref => {
+ const i = Number(ref.id.slice(6));
+ return [ref.id, { ...older[i]!.threadShare!, status: 'available', content: `核对 ${i}`, attachments: [] }];
+ }));
+ return new Promise(resolve => finish.push(() => resolve({ ok: true, group: { ...latest, threadShareUpdates: updates } })));
+ });
+ renderView();
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ await waitFor(() => expect(document.querySelectorAll('[data-share-message-id]').length).toBeGreaterThan(200));
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
- expect(finish).toHaveLength(2);
- await act(async () => finish[1]!());
++ // The optimized reader coalesces pushes while a read is in flight. Its follow-up
++ // must still reconcile every loaded share, including those beyond one server batch.
++ expect(finish).toHaveLength(1);
+ await act(async () => finish[0]!());
++ await waitFor(() => expect(finish).toHaveLength(2));
++ await act(async () => finish[1]!());
+ expect(await screen.findByText('核对 0')).toBeTruthy();
+ expect(screen.getByText('核对 200')).toBeTruthy();
+ expect(screen.queryByText(t('loadingSource'))).toBeNull();
+ expect(screen.queryByText('pending-0.pdf')).toBeNull();
+ expect(finish).toHaveLength(2);
+ });
+
+ it('checks all loaded shares in one refresh, including the oldest deleted source', { timeout: 20_000 }, async () => {
+ type Share = NonNullable<BotGroupMessageView['threadShare']>;
+ const shareOf = (i: number, extra: Partial<Share> = {}): Share => ({ messageId: `reply-${i}`, threadRootId: 'root', status: 'available', authorKind: 'bot',
+ authorBotId: 'xiaoman', authorName: '小满', sharedByAuthor: false, content: `原文 ${i}`, attachments: [], createdAt: 1, edited: false, version: 1, ...extra });
+ const older = Array.from({ length: 201 }, (_, i) => msg({ id: `share-${i}`, sequence: i + 1, authorKind: 'user', isSelf: false, authorBotId: 'alice',
+ authorName: 'Alice', content: `↪ 卡片 ${i}`, threadShare: shareOf(i) }));
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 1, messages: [msg({ id: 'new', sequence: 500, content: '最新' })] });
+ let version = 1;
+ const refreshes: Array<string[]> = [];
+ mocks.getBotGroup.mockImplementation(async (_groupId: string, options?: { beforeSequence?: number; shownShares?: Array<{ id: string; messageId: string }> }) => {
+ if (options?.beforeSequence) return { ok: true, group: { ...latest, hasMoreBefore: false, messages: older } };
+ refreshes.push((options?.shownShares ?? []).map(share => share.id));
+ // The oldest share's reply has been deleted on the server since it was shown.
+ const threadShareUpdates = Object.fromEntries((options?.shownShares ?? []).map(share => [share.id, share.messageId === 'reply-0'
+ ? shareOf(0, { status: 'unavailable', authorName: '', content: '', version }) : shareOf(Number(share.messageId.slice(6)), { version })]));
+ return { ok: true, group: { ...latest, threadShareVersion: version, threadShareUpdates } };
+ });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ expect(await screen.findByText('原文 0')).toBeTruthy();
+ version = 2;
+ act(() => { for (const push of mocks.pushes) push({ groupId: 'g1', change: 'messages' }); });
+ await screen.findByText(t('sourceUnavailable'));
+ await waitFor(() => expect(screen.queryByText(t('loadingSource'))).toBeNull());
+ expect(screen.queryByText('原文 0')).toBeNull();
+ expect(screen.getAllByText(t('sourceUnavailable')).length).toBe(1);
+ // Initial load and one push refresh: no per-batch follow-ups.
+ expect(refreshes).toHaveLength(2);
+ expect(refreshes[1]).toHaveLength(201);
+ expect(screen.queryByText('↪ 卡片 0')).toBeNull();
+ });
+
+ it('checks a stale share even when a full batch of newer ones is still loading', { timeout: 20_000 }, async () => {
+ type Share = NonNullable<BotGroupMessageView['threadShare']>;
+ const shareOf = (i: number, extra: Partial<Share> = {}): Share => ({ messageId: `reply-${i}`, threadRootId: 'root', status: 'available', authorKind: 'bot',
+ authorBotId: 'xiaoman', authorName: '小满', sharedByAuthor: false, content: `原文 ${i}`, attachments: [], createdAt: 1, edited: false, version: 2, ...extra });
+ // The newest 200 are still being read by the main process; the oldest predates an edit.
+ const older = Array.from({ length: 201 }, (_, i) => msg({ id: `share-${i}`, sequence: i + 1, authorKind: 'user', isSelf: false, authorBotId: 'alice',
+ authorName: 'Alice', content: `↪ 卡片 ${i}`, threadShare: i === 0 ? shareOf(0, { version: 1 }) : shareOf(i, { status: 'loading', authorName: '', content: '' }) }));
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 2, messages: [msg({ id: 'new', sequence: 500, content: '最新' })] });
+ const refreshes: Array<string[]> = [];
+ mocks.getBotGroup.mockImplementation(async (_groupId: string, options?: { beforeSequence?: number; shownShares?: Array<{ id: string; messageId: string }> }) => {
+ if (options?.beforeSequence) return { ok: true, group: { ...latest, hasMoreBefore: false, messages: older } };
+ refreshes.push((options?.shownShares ?? []).map(share => share.id));
+ const threadShareUpdates = Object.fromEntries((options?.shownShares ?? []).map(share => [share.id, share.messageId === 'reply-0'
+ ? shareOf(0, { content: '核对后的原文' }) : shareOf(Number(share.messageId.slice(6)), { status: 'loading', authorName: '', content: '' })]));
+ return { ok: true, group: { ...latest, threadShareUpdates } };
+ });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ expect(await screen.findByText('核对后的原文')).toBeTruthy();
+ // The first refresh that checks older shares already takes the stale one.
+ expect(refreshes.find(ids => ids.length)).toContain('share-0');
+ expect(refreshes.find(ids => ids.length)).toHaveLength(201);
+ });
+ });
+
+ describe('pending main-chat copies across accounts', () => {
+ const t = (name: string) => `bots.groupChat.server.thread.${name}`;
+ beforeEach(() => { vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }); });
+ afterEach(() => { mocks.ownerGeneration = { dataOwnerId: 'account-a', generation: 1 }; });
+
+ it('does not offer one account\'s failed copy to the next account in the same group', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: 'A' })] }) });
+ mocks.shareToMain.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR' });
+ const user = userEvent.setup();
+ const view = renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ let panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'from account A{Enter}');
+ await within(panel).findByRole('button', { name: t('retryPost') });
+ view.unmount();
+ // Another account opens the same server group and thread.
+ mocks.ownerGeneration = { dataOwnerId: 'account-b', generation: 2 };
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ panel = await screen.findByRole('complementary');
+ await within(panel).findByText('Reply to u1');
+ expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull();
+ });
+
+ it('keeps failed copies across same-owner repair and ignores an old-generation retry result', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: 'A' })] }) });
+ let finishOldRetry!: (result: { ok: true; messageId: string; alreadyShared: boolean }) => void;
+ mocks.shareToMain.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR' })
+ .mockImplementationOnce(() => new Promise(resolve => { finishOldRetry = resolve; }));
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.startTopic' }));
+ const panel = await screen.findByRole('complementary');
+ await user.click(within(panel).getByRole('checkbox', { name: t('alsoSend') }));
+ await user.type(within(panel).getByRole('textbox'), 'copy me{Enter}');
+ await user.click(await within(panel).findByRole('button', { name: t('retryPost') }));
+ expect(mocks.shareToMain).toHaveBeenCalledTimes(2);
+
+ // Runtime repair leaves the same account and panel mounted, but replaces generation.
+ mocks.ownerGeneration = { dataOwnerId: 'account-a', generation: 2 };
+ await user.type(within(panel).getByRole('textbox'), 'next draft');
+ expect(within(panel).getByRole('button', { name: t('retryPost') })).toBeTruthy();
+ await act(async () => { finishOldRetry({ ok: true, messageId: 'old-share', alreadyShared: false }); });
+ expect(within(panel).getByRole('button', { name: t('retryPost') })).toBeTruthy();
+
+ await user.click(within(panel).getByRole('button', { name: t('retryPost') }));
+ await waitFor(() => expect(within(panel).queryByRole('button', { name: t('retryPost') })).toBeNull());
+ expect(mocks.shareToMain.mock.calls).toEqual(Array.from({ length: 3 }, () => [{ groupId: 'g1', messageId: 'new-reply' }]));
+ expect(mocks.reply).toHaveBeenCalledTimes(1);
+ });
+ });
diff --cc apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
index d3838dea08,04841b92d8..ebcd5aef67
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
@@@ -6,8 -6,7 +6,9 @@@ import { afterEach, beforeEach, describ
import { ChatInviteButton, ChatMessageActions } from '../ChatServerControls';
import { ChatInviteDialog } from '../ChatInviteDialog';
import { ChatThreadPanel } from '../ChatThreadPanel';
+import { botGroupThreadDraftKey } from '../botGroupAttachments';
+import { clearDraft } from '@/lib/composerDraftStore';
+ import { flashThreadTarget } from '../BotGroupThreadViews';
import { chatErrorKey } from '../chatError';
import type { BotGroupDetail, BotGroupMessageView } from '../../../../shared/botGroupChat';
import { shareSelectionStore } from '@/components/chat/shareSelectionStore';
@@@ -15,13 -14,10 +16,13 @@@ import { queryShareableMessageIds, stri
const mocks = vi.hoisted(() => ({
status: vi.fn(), react: vi.fn(), reactors: vi.fn(), thread: vi.fn(), reply: vi.fn(), createInvite: vi.fn(), previewInvite: vi.fn(), acceptInvite: vi.fn(),
- refresh: vi.fn(), ownerCurrent: true,
+ refresh: vi.fn(), shareToMain: vi.fn(), ownerCurrent: true,
}));
-vi.mock('react-i18next', async (original) => ({ ...(await original<typeof import('react-i18next')>()),
- useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
+// Partial: the 话题 reply box shares the group composer, whose attachment pieces pull in the app i18n instance.
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
vi.mock('@/components/chat/MarkdownRenderer', () => ({ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div> }));
vi.mock('../BotAvatar', () => ({ BotAvatar: () => null }));
vi.mock('../botGroupStore', () => ({ refreshBotGroups: mocks.refresh }));
@@@ -231,6 -192,70 +255,71 @@@ describe('chat interaction controls', (
expect(mocks.thread.mock.calls.at(-1)?.[0]).toMatchObject({ sourceMessageIds: [older.id, latest.id] });
});
+ it('stops a bulk retry of main-chat copies once the account is switched', async () => {
+ mocks.reply.mockResolvedValueOnce({ ok: true, messageId: 'first' }).mockResolvedValueOnce({ ok: true, messageId: 'second' });
+ mocks.shareToMain.mockResolvedValue({ ok: false, errorCode: 'SERVICE_ERROR' });
+ render(<ChatThreadPanel group={group} rootId="retry-root" onClose={vi.fn()} />);
+ const input = screen.getByRole('textbox', { name: k('replyPlaceholder') });
+ for (const [count, text] of [[1, 'one'], [2, 'two']] as const) {
+ fireEvent.click(screen.getByRole('checkbox', { name: k('thread.alsoSend') }));
+ fireEvent.change(input, { target: { value: text } });
+ fireEvent.click(screen.getByRole('button', { name: k('sendReply') }));
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledTimes(count));
+ }
+ const retry = await screen.findByRole('button', { name: k('thread.retryPost') });
+ let finish!: (value: unknown) => void;
+ mocks.shareToMain.mockClear().mockReturnValueOnce(new Promise(resolve => { finish = resolve; }))
+ .mockResolvedValue({ ok: true, messageId: 'share', alreadyShared: false });
+ fireEvent.click(retry);
+ await waitFor(() => expect(mocks.shareToMain).toHaveBeenCalledTimes(1));
+ // The account changes while the first copy is in flight: the second must not go out.
+ mocks.ownerCurrent = false;
+ finish({ ok: true, messageId: 'share', alreadyShared: false });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(mocks.shareToMain).toHaveBeenCalledTimes(1);
+ });
+
+ it('names an unavailable share only for posting; a missing message elsewhere stays generic', () => {
+ expect(chatErrorKey('SHARE_UNAVAILABLE')).toBe(k('thread.shareUnavailable'));
+ expect(chatErrorKey('MESSAGE_NOT_FOUND')).toBe(k('requestFailed'));
+ });
+
+ it.each([[true, 'auto'], [false, 'smooth']] as const)('jumps to a shared reply without smooth scrolling when reduced motion is %s', (reduced, behavior) => {
+ vi.stubGlobal('matchMedia', (query: string) => ({ matches: reduced && query === '(prefers-reduced-motion: reduce)' }));
+ const target = document.createElement('article');
+ target.scrollIntoView = vi.fn();
+ flashThreadTarget(target);
+ expect(target.scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior });
+ });
+
+ it('keeps looking for a shared reply when group pushes overtake its older-page reads', async () => {
- const latest = { ...message, id: 'latest', sequence: 100, content: 'Latest reply' };
++ let latest = { ...message, id: 'latest', sequence: 100, content: 'Latest reply' };
+ const target = { ...message, id: 'target', sequence: 4, content: 'Target reply' };
+ const olderReads: Array<(value: unknown) => void> = [];
+ mocks.thread.mockImplementation(({ before }: { before?: number }) => before
+ ? new Promise(resolve => { olderReads.push(resolve); })
+ : Promise.resolve({ ok: true, root: message, replies: [latest], hasMore: true }));
+ let push!: (event: { groupId: string }, stamp: unknown) => void;
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: {
+ chatServer: mocks, onBotGroupChanged: (listener: typeof push) => { push = listener; return () => {}; },
+ } } });
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ onTestFinished(() => { delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView; });
+ render(<ChatThreadPanel group={group} rootId="root" focus={{ messageId: target.id, nonce: 1 }} onClose={vi.fn()} />);
+ await waitFor(() => expect(olderReads).toHaveLength(1));
+ // Each push refresh lands while an older page is in flight, so that page is discarded.
+ for (let overtaken = 1; overtaken <= 6; overtaken += 1) {
++ latest = { ...latest, id: `latest-${overtaken}`, sequence: latest.sequence + 100 };
+ push({ groupId: 'room' }, null);
+ await waitFor(() => expect(olderReads).toHaveLength(overtaken + 1));
+ olderReads[overtaken - 1]!({ ok: true, root: message, replies: [], hasMore: true });
+ }
+ olderReads.at(-1)!({ ok: true, root: message, replies: [target], hasMore: false });
+ expect(await screen.findByText('Target reply')).toBeTruthy();
+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalled());
+ });
+
it('preserves copy and image sharing beside thread replies and reactions in one toolbar', async () => {
const writeText = vi.fn().mockResolvedValue(undefined), reply = vi.fn();
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });
diff --cc apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
index ddea6be36f,c1b9a753d5..9beefa7e7c
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx
@@@ -503,22 -502,11 +503,30 @@@ it('localizes the join preview without
expect(screen.queryByText(/Fallback text/)).toBeNull();
});
+it('badges the real number of unread group messages, falling back to one on older hosts', async () => {
+ window.localStorage.clear();
+ resetBotReadStateForTests();
+ markBotRead(botGroupReadKey('g1'), 15);
+ markBotRead(botGroupReadKey('g2'), 15);
+ const at = (ms: number) => new Date(ms).toISOString();
+ mocks.groups = [
+ group({ lastReplyAt: 30, incomingMessageTimes: [at(10), at(20), at(30)] } as Partial<BotGroupSummary>),
+ group({ id: 'g2', name: '读书会', lastReplyAt: 30 }),
+ ];
+ try {
+ await renderSidebar();
+ expect(screen.getByLabelText('sidebar.teammateUnreadCount:{"count":2}').textContent).toBe('2');
+ expect(screen.getByLabelText('sidebar.teammateUnreadCount:{"count":1}').textContent).toBe('1');
+ } finally {
+ resetBotReadStateForTests();
+ window.localStorage.clear();
+ }
+});
+ it.each([[false, 'bots.groupChat.sidebar.sharedReply:{"name":"Alice"}'], [true, 'bots.groupChat.sidebar.sharedReplyYou']] as const)(
+ 'names who shared a thread reply without quoting any card text (self: %s)', async (isSelf, label) => {
+ mocks.groups = [group({ lastMessage: { authorKind: 'user', isSelf, authorName: 'Alice', threadShare: true,
+ preview: '↪ 冒充: 卡片文字', createdAt: 30 } })];
+ await renderSidebar();
+ expect(screen.getByText(label)).toBeTruthy();
+ expect(screen.queryByText(/冒充|卡片文字/)).toBeNull();
+ });
diff --cc docs/design-rules/design-inventory.md
index 76754f2894,3bd150bfde..7c38d53d5f
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@@ -18,7 -18,7 +18,7 @@@
| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
| `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 |
| `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
- | `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 509 |
-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 275 | 38 | 502 |
++| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupThreadViews.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/islandEntryAlert.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useSessionEntryLocationCommits.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 516 |
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 45 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 3 |
| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 249 | 38 | 337 |